假设我有一些计数数据,如下所示:
library(tidyr)
library(dplyr)
X.raw <- data.frame(
x = as.factor(c("A", "A", "A", "B", "B", "B")),
y = as.factor(c("i", "ii", "ii", "i", "i", "i")),
z = 1:6
)
X.raw
# x y z
# 1 A i 1
# 2 A ii 2
# 3 A ii 3
# 4 B i 4
# 5 B i 5
# 6 B i 6
我想整理并总结如下:
X.tidy <- X.raw %>% group_by(x, y) %>% summarise(count = sum(z))
X.tidy
# Source: local data frame [3 x 3]
# Groups: x
#
# x y count
# 1 A i 1
# 2 A ii 5
# 3 B i 15
我知道,对于x=="B"
和y=="ii"
,我们观察到的是零计数,而不是缺失值.i、 e.现场工作人员确实在现场,但由于没有正计数,因此未在原始数据中输入任何行.我可以通过这样做明确地添加零计数:
X.fill <- X.tidy %>% spread(y, count, fill = 0) %>% gather(y, count, -x)
X.fill
# Source: local data frame [4 x 3]
#
# x y count
# 1 A i 1
# 2 B i 15
# 3 A ii 5
# 4 B ii 0
但这似乎有点迂回.有没有更简洁的成语来形容这一点?
只是想澄清一下:我的代码已经完成了我需要它做的事情,使用spread
然后gather
,所以我感兴趣的是找到一条更直接的路由within tidyr
和dplyr
.