0

I would like to move a data.frame from long to wide. Whenever I have a duplicate id, I want to copy my results in a particular var to a new col. In the end I want id to be a unique id. I have looked at using the reshape function - but can't seem how to handle not having the "timevar" - in my particular case, I don't have a grouping var that I want to reshape based on. There is a ton on stack overflow with reshaping data but I can't seem to find this issue.

I have:

a<- 
    data.frame( 
        id = c( 11,12,13,14,15,15,16,17,17,18,19,10) ,
        pi = c( 21:32 )
)

I want

b<- 
    data.frame( 
        id = c( 11,12,13,14,15,16,17,18,19,10) ,
        pi = c( 21:25,27:28,30:32 ),
        pi2 = c( NA,NA,NA,NA,26,NA,29,NA,NA,NA)     
)
MatthewR
  • 2,660
  • 5
  • 26
  • 37

1 Answers1

0

You can do this in a few steps:

bb <- aggregate(pi~id, data=a, FUN=c)
cols <- max(sapply(bb$pi, length))
b <- cbind(bb$id, sapply(seq(cols), function(i) sapply(bb$pi, '[', i)))
b
##    [,1] [,2] [,3]
## 1    10   32   NA
## 2    11   21   NA
## 3    12   22   NA
## 4    13   23   NA
## 5    14   24   NA
## 6    15   25   26
## 8    16   27   NA
## 9    17   28   29
## 11   18   30   NA
## 12   19   31   NA
Matthew Lundberg
  • 42,009
  • 6
  • 90
  • 112