1

作为学习 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) 

返回 4、5、0、1(并select = freq给出 40、50、0、10)?

非常感谢。

编辑:带着种子组跑!

4

1 回答 1

1

我们可以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
于 2017-04-23T06:00:38.977 回答