R:当键位于不同列并返回值频率时,传播键值对

时间:2016-10-05 19:25:17

标签: r dplyr tidyr

我已经四处寻找,但找不到我问题的具体答案。

假设我有一个数据框df:

df = data.frame(id = c(10, 11, 12, 13, 14),
                V1 = c('blue', 'blue', 'blue', NA, NA),
                V2 = c('blue', 'yellow', NA, 'yellow', 'green'),
                V3 = c('yellow', NA, NA, NA, 'blue'))

我想将V1-V3的值用作唯一列标题,并且我希望每行的每个列的出现频率填充行。

期望的输出:

desired = data.frame(id = c(10, 11, 12, 13, 14),
                     blue = c(2, 1, 1, 0, 1),
                     yellow = c(1, 1, 0, 1, 0),
                     green = c(0, 0, 0, 0, 1))

使用tidyr :: spread和dplyr :: summarize可能有一种很酷的方法。但是,当我想传播的密钥遍布不同的列并且包含NA时,我不知道如何传播V *列。

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

使用包melt中的dcastreshape2

dcast(melt(df, id="id", na.rm = TRUE), id~value)

  id blue green yellow
1 10    2     0      1
2 11    1     0      1
3 12    1     0      0
4 13    0     0      1
5 14    1     1      0

根据David Arenburg的建议,使用recastmeltdcast的包装更简单:

recast(df, id ~ value, id.var = "id")[,1:4]   # na.rm is not possible then

  id blue green yellow
1 10    2     0      1
2 11    1     0      1
3 12    1     0      0
4 13    0     0      1
5 14    1     1      0