【问题标题】:Include empty factor levels in tally with tidyr and dplyr在 tidyr 和 dplyr 的计数中包含空因子级别
【发布时间】:2017-04-23 05:51:42
【问题描述】:

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

非常感谢。

编辑:带着种子组跑!

【问题讨论】:

  • 我认为您创建的数据集没有 set.seed。请运行您的数据并检查我得到3, 1, 4, 2
  • 射击。正在修复...

标签: r dplyr tidyr levels tally


【解决方案1】:

我们可以从tidyr使用complete

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

【讨论】:

  • 就是这样。谢谢。
猜你喜欢
  • 2019-10-13
  • 1970-01-01
  • 1970-01-01
  • 2020-03-07
  • 1970-01-01
  • 2016-06-05
  • 2017-12-09
  • 2018-11-02
  • 1970-01-01
相关资源
最近更新 更多