从值重塑为colname

时间:2017-12-05 05:16:53

标签: r

我希望重新构建我的数据框,如下所示:

     Ech   pos    sm    nb
   <int> <chr> <dbl> <dbl>
 1     4    BD    10    80
 2     4    BG     5    80
 3     4    HD     1    80
 4     4    HG     2    80

     Ech    BD   BG   HD   HG  nb
 1     4    10    5    1   2   80

我的数据:

DF=structure(list(Ech = c(4L, 4L, 4L, 4L, 13L, 13L, 13L, 13L, 28L, 
28L, 28L, 28L, 37L, 37L, 37L, 37L, 40L, 40L, 40L, 40L), pos = c("BD", 
"BG", "HD", "HG", "BD", "BG", "HD", "HG", "BD", "BG", "HD", "HG", 
"BD", "BG", "HD", "HG", "BD", "BG", "HD", "HG"), sm = c(10, 5, 
1, 2, 2, 4, 2, 1, 3, 7, 1, 2, 6, 4, 2, 4, 11, 8, 1, 4), nb = c(80, 
80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 
80, 80, 80)), .Names = c("Ech", "pos", "sm", "nb"), row.names = c(NA, 
-20L), vars = "Ech", drop = TRUE, class = c("grouped_df", "tbl_df", 
"tbl", "data.frame"))

最快的方法是什么?感谢

1 个答案:

答案 0 :(得分:1)

tidyr::spread这样做:

spread(DF, pos, sm)

输出:

    Ech    nb    BD    BG    HD    HG
* <int> <dbl> <dbl> <dbl> <dbl> <dbl>
1     4    80    10     5     1     2
2    13    80     2     4     2     1
3    28    80     3     7     1     2
4    37    80     6     4     2     4
5    40    80    11     8     1     4