Home > Mobile >  How to transform variable to multiple columns
How to transform variable to multiple columns

Time:03-08

How can I transform this data frame to a wider one? This:

> test_df <- data.frame(item = c(1,1,1,2,2,3), thoughts = c('stupid','nah','wrong','good','nice','ok'))
> test_df
  item thoughts
1    1   stupid
2    1      nah
3    1    wrong
4    2     good
5    2     nice
6    3       ok

into this:

> test_df_long <- data.frame(item = c(1,2,3), thoughts1 = c('stupid','good','ok'), thoughts2 = c('nah','nice', NA), thoughts3 = c('wrong', NA, NA))
> test_df_long
  item thoughts1 thoughts2 thoughts3
1    1    stupid       nah     wrong
2    2      good      nice      <NA>
3    3        ok      <NA>      <NA>

CodePudding user response:

Using reshape2 and adding one new column

test_df$cols=paste("thoughts",ave(rep(1,nrow(test_df)),test_df$item,FUN=cumsum))

library(reshape2)
dcast(
  test_df,
  item~cols,
  value.var="thoughts"
)

  item thoughts 1 thoughts 2 thoughts 3
1    1     stupid        nah      wrong
2    2       good       nice       <NA>
3    3         ok       <NA>       <NA>
  •  Tags:  
  • r
  • Related