Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make a column into column names in R

I have a dataframe of 3 columns as below

    batsman1                 bowler1         timesOut
1   A Ashish Reddy          A Ashish Reddy        0
2   A Ashish Reddy              A Chandila        1
3   A Ashish Reddy             A Choudhary        3
4   A Ashish Reddy             A Dananjaya        0

I would like to transform the above dataframe where the second column becomes column names as below

    batsman1         A Ashish Reddy A Chandila A Choudhary A Danajaya

 A Ashish Reddy.         0             1         3             0
 A Chandila
 A Choudhary
 A Danajaya

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

A possible solution, based on tidyr::pivot_wider:

library(tidyverse)

df %>% 
  pivot_wider(batsman1, names_from = bowler1, values_from = timesOut) %>% 
  bind_rows(list(batsman1 = df$bowler1)) %>% 
  filter(!duplicated(batsman1))

#> # A tibble: 4 × 5
#>   batsman1       `A Ashish Reddy` `A Chandila` `A Choudhary` `A Dananjaya`
#>   <chr>                     <int>        <int>         <int>         <int>
#> 1 A Ashish Reddy                0            1             3             0
#> 2 A Chandila                   NA           NA            NA            NA
#> 3 A Choudhary                  NA           NA            NA            NA
#> 4 A Dananjaya                  NA           NA            NA            NA
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading