假设我有一些如下所示的计数数据:
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"
观察到计数为零,而不是缺失值。即现场工作人员实际上在那里,但是因为没有正数,所以没有在原始数据中输入任何行。我可以通过这样做显式添加零计数:
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
只是为了澄清一下:我的代码已经使用then完成了我需要它做的事情gather
,所以我感兴趣的是在 tidyr
and中找到更直接的路线dplyr
。