Saugandh Datta Saugandh Datta - 1 month ago 9
R Question

Reshape from long to wide format

example

customer_code items
1 sugar
1 salt
2 sugar
2 accessories
3 salt


Desired output

customer_code item item2 item3
1 sugar salt
2 sugar accessories
3 salt

Answer

You could use spread from tidyr

library(dplyr)
library(tidyr)
  mutate(df1, var=factor(items, levels=unique(items), 
      labels=paste0('items', seq(n_distinct(items))))) %>% 
            spread(var, items, fill='')
#  customer_code items1 items2      items3
#1             1  sugar   salt            
#2             2  sugar        accessories
#3             3          salt        
Comments