使用 tidyr 和 dplyr 在计数中包含空因子水平
Include empty factor levels in tally with tidyr and dplyr
作为学习 dplyr 及其同类的问题。
我正在计算一个因子的计数和相对频率,该因子以 df 中的其他两个变量为条件。例如:
library(dplyr)
library(tidyr)
set.seed(3457)
pct <- function(x) {x/sum(x)}
foo <- data.frame(x = rep(seq(1:3),20),
y = rep(rep(c("a","b"),each=3),10),
z = LETTERS[floor(runif(60, 1,5))])
bar <- foo %>%
group_by(x, y, z) %>%
tally %>%
mutate(freq = (n / sum(n)) * 100)
head(bar)
我希望输出 bar
包含 foo$z
的所有级别。即,这里没有 C
的情况:
subset(bar, x==2 & y=="a")
如何让 bar
计算缺失的水平,以便我得到:
subset(bar, x==2 & y=="a",select = n)
到 return 4, 5, 0, 1(和 select = freq
到 40, 50, 0, 10)?
非常感谢。
编辑:运行 种子集!
我们可以使用 complete
来自 tidyr
bar1 <- bar %>%
complete(z, nesting(x, y), fill = list(n = 0, freq = 0))%>%
select_(.dots = names(bar))
filter(bar1, x==2 & y=="a")
# x y z n freq
# <int> <fctr> <fctr> <dbl> <dbl>
#1 2 a A 4 40
#2 2 a B 5 50
#3 2 a C 0 0
#4 2 a D 1 10
作为学习 dplyr 及其同类的问题。
我正在计算一个因子的计数和相对频率,该因子以 df 中的其他两个变量为条件。例如:
library(dplyr)
library(tidyr)
set.seed(3457)
pct <- function(x) {x/sum(x)}
foo <- data.frame(x = rep(seq(1:3),20),
y = rep(rep(c("a","b"),each=3),10),
z = LETTERS[floor(runif(60, 1,5))])
bar <- foo %>%
group_by(x, y, z) %>%
tally %>%
mutate(freq = (n / sum(n)) * 100)
head(bar)
我希望输出 bar
包含 foo$z
的所有级别。即,这里没有 C
的情况:
subset(bar, x==2 & y=="a")
如何让 bar
计算缺失的水平,以便我得到:
subset(bar, x==2 & y=="a",select = n)
到 return 4, 5, 0, 1(和 select = freq
到 40, 50, 0, 10)?
非常感谢。
编辑:运行 种子集!
我们可以使用 complete
来自 tidyr
bar1 <- bar %>%
complete(z, nesting(x, y), fill = list(n = 0, freq = 0))%>%
select_(.dots = names(bar))
filter(bar1, x==2 & y=="a")
# x y z n freq
# <int> <fctr> <fctr> <dbl> <dbl>
#1 2 a A 4 40
#2 2 a B 5 50
#3 2 a C 0 0
#4 2 a D 1 10