Question

I have following data

>Data <- data.frame(
X = c(22,22,22,22,22,33,33,33,33),
Y = c(123,234,567,678,433,555,664,77,88),
Z = c(2,2,2,1,2,2,1,1,1)
)

>Data
#    X     Y      Z
#   22    123    2
#   22    234    2
#   22    567    2
#   22    678    1
#   33    433    2
#   33    555    2
#   33    664    1
#   33    77     1
#   33    88     1

I want to get a result which combines the Y column in one cell when X are the same. When Z =2, the Y will be at front in YY, and when z=1, the Y will be added after.

The result will be like this

>result
#   XX           YY                
#   22    123  234  567 678            
#   33    433  555  664 77  88            

How to do that? Thank you!

Was it helpful?

Solution

setNames( aggregate(Data$Y,Data['X'], paste, collapse="  "), c("XX","YY"))
  XX                      YY
1 22 123  234  567  678  433
2 33        555  664  77  88

Looks like your grouping was off.... at least as far as I could parse your intent. The English sentence at the end didn't make much sense to me anyway, because the phrase "added after" was unclear.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top