How to reshape tabular data to one row per group

后端 未结 5 1326
轻奢々
轻奢々 2020-12-21 23:57

I am an R (and coding novice) and I am looking for a way to reconfigure Table A show below into Table B.

Table A:

type   x1  x2  x3  
A      4   6            


        
5条回答
  •  感动是毒
    2020-12-22 00:17

    Take a try and the solution is not such concise, just give you a hint.I think lots of things can be improved.

    But finally we have to introduce NAs in here :(

    zz <- "type   x1  x2  x3  
    A      4   6   9  
    A      7   4   1  
    A      9   6   2   
    B      1   3   8  
    B      2   7   9"
    
    dA <- read.table(text=zz, header=T)
    
    
    tmp<-(sapply(unique(dA$type), FUN=function(x) as.vector(t(dA[dA$type == x, -1]))))
    
    t(sapply(tmp, '[', seq(max(sapply(tmp, length)))))
          [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
    [1,]    4    6    9    7    4    1    9    6    2
    [2,]    1    3    8    2    7    9   NA   NA   NA
    

提交回复
热议问题