Transpose/reshape rows in columns with given conditions

后端 未结 2 1867
星月不相逢
星月不相逢 2021-01-21 02:21

I have the following data:

request   user   group
1         1      1
4         1      1
7         1      1
5         1      2
8         1      2
1         2              


        
相关标签:
2条回答
  • 2021-01-21 02:48

    aggregate gets you very close:

    dat <- data.frame(
        user = c(1,1,1,2,2,3,3,3,4), 
        group = c(1,1,1,1,1,2,2,2,2), 
        request = c(1,4,7,5,8,1,4,7,9)
    )
    
    aggregate(request~group + user, dat, FUN=c)
    
      group user request
    1     1    1 1, 4, 7
    2     1    2    5, 8
    3     2    3 1, 4, 7
    4     2    4       9
    
    0 讨论(0)
  • 2021-01-21 03:06
    library(reshape)
    
    # Make some fake data
    dat <- data.frame(user = c(1,1,1,2,2,3), group = c(1,1,1,1,1,2), request = c(1,4,7,5,8,1))
    # Add in an ordered id
    newdat <- ddply(dat, .(user, group), transform, idx = paste("request", 1:length(request), sep = ""))
    # Use cast to get what we want
    cast(newdat, user + group ~ idx, value = .(request))
    

    There is probably a nicer way to get what I call idx which is essentially what becomes the column title. It might be possible to do this without creating the newdat data set but this is what I thought of.

    0 讨论(0)
提交回复
热议问题