包括与tidyr和dplyr相关的空因子水平

时间:2017-04-23 05:51:43

标签: r dplyr tidyr levels tally

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

非常感谢。

编辑:使用种子集进行游戏!

1 个答案:

答案 0 :(得分: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
相关问题