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

>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

Leave a Reply