假设我有一些如下所示的计数数据:
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"
and 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
,所以我感兴趣的是找到一条更直接的路线within tidyr
and dplyr
.