1

I would like to create multiple new columns for each value of one column, grouped by another. For example, if I have this:

    session      side_effect:

        1          dizzy
        1          irritable
        1          anxious
        3          focused
        3          anxious
        7          relaxed

Can I get this:

      session     side_effect1   side effect_2  side_effect_3
        1           dizzy          irritable       anxious
        3           focused        anxious
        7           relaxed 
markus
  • 25,843
  • 5
  • 39
  • 58
alex
  • 858
  • 5
  • 14

1 Answers1

0

We can use pivot_wider from tidyr to convert from 'long' to 'wide' format

library(dplyr)
library(tidyr)
df1 %>%
     group_by(session) %>% 
     mutate(rn = str_c('side_effect_', row_number())) %>% 
     pivot_wider(names_from = rn, values_from = side_effect)
# A tibble: 3 x 4
#  session side_effect_1 side_effect_2 side_effect_3
#    <int> <chr>         <chr>         <chr>        
#1       1 dizzy         irritable     anxious      
#2       3 focused       anxious       <NA>         
#3       7 relaxed       <NA>          <NA>      

data

df1 <- structure(list(session = c(1L, 1L, 1L, 3L, 3L, 7L), side_effect = c("dizzy", 
"irritable", "anxious", "focused", "anxious", "relaxed")),
class = "data.frame", row.names = c(NA, 
-6L))
akrun
  • 874,273
  • 37
  • 540
  • 662