Spreading a two column data frame with tidyr

后端 未结 5 1995
渐次进展
渐次进展 2020-11-30 14:47

I have a data frame that looks like this:

  a b
1 x 8
2 x 6
3 y 3
4 y 4
5 z 5
6 z 6

and I want to turn it into this:

  x y          


        
5条回答
  •  失恋的感觉
    2020-11-30 15:41

    You can do this with dcast and rowid from the data.table package as well:

    dat <- dcast(setDT(df), rowid(a) ~ a, value.var = "b")[,a:=NULL]
    

    which gives:

    > dat
       x y z
    1: 8 3 5
    2: 6 4 6
    

    Old solution:

    # create a sequence number by group
    setDT(df)[, r:=1:.N, by = a]
    # reshape to wide format and remove the sequence variable
    dat <- dcast(df, r ~ a, value.var = "b")[,r:=NULL]
    

    which gives:

    > dat
       x y z
    1: 8 3 5
    2: 6 4 6
    

提交回复
热议问题