Group values with identical ID into columns without summerizing them in R

后端 未结 2 679
栀梦
栀梦 2021-01-21 20:25

I have a dataframe that looks like this, but with a lot more Proteins

Protein      z
  Irak4  -2.46
  Irak4  -0.13
    Itk  -0.49
    Itk   4.22
    Itk  -0.51
          


        
2条回答
  •  后悔当初
    2021-01-21 20:43

    library(data.table)
    
    dcast(setDT(df),rowid(Protein)~Protein,value.var='z')
    
       Protein Irak4   Itk  Ras
    1:       1 -2.46 -0.49 1.53
    2:       2 -0.13  4.22   NA
    3:       3    NA -0.51   NA
    

    in base R you can do:

    data.frame(sapply(a<-unstack(df,z~Protein),`length<-`,max(lengths(a))))
      Irak4   Itk  Ras
    1 -2.46 -0.49 1.53
    2 -0.13  4.22   NA
    3    NA -0.51   NA
    

    Or using reshape:

    reshape(transform(df,gr=ave(z,Protein,FUN=seq_along)),v.names = 'z',timevar = 'Protein',idvar = 'gr',dir='wide') 
      gr z.Irak4 z.Itk z.Ras
    1  1   -2.46 -0.49  1.53
    2  2   -0.13  4.22    NA
    5  3      NA -0.51    NA
    

提交回复
热议问题