R:当键位于不同列和 return 值频率时传播 key-value 对
R: Spread key-value pairs when keys are in different columns and return value frequency
我四处搜索,但找不到我的问题的特定答案。
假设我有一个数据框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 的值用作唯一列 headers 并且我希望每行中每个值的出现频率填充行。
期望输出:
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::summarise 可能有一种非常酷的方法可以做到这一点。但是,当我想要传播的键遍布不同列并包括 NA 时,我不知道如何传播 V* 列。
感谢您的帮助!
使用包 reshape2
中的 melt
和 dcast
:
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 所建议的那样,使用 recast
更简单,它是 melt
和 dcast
的包装器:
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
我四处搜索,但找不到我的问题的特定答案。
假设我有一个数据框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 的值用作唯一列 headers 并且我希望每行中每个值的出现频率填充行。
期望输出:
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::summarise 可能有一种非常酷的方法可以做到这一点。但是,当我想要传播的键遍布不同列并包括 NA 时,我不知道如何传播 V* 列。
感谢您的帮助!
使用包 reshape2
中的 melt
和 dcast
:
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 所建议的那样,使用 recast
更简单,它是 melt
和 dcast
的包装器:
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