dplyr计数变量的一个特定值的数量

Jac*_*tis 12 r count dplyr

假设我有这样的数据集:

id <- c(1, 1, 2, 2, 3, 3)
code <- c("a", "b", "a", "a", "b", "b")
dat <- data.frame(id, code)
Run Code Online (Sandbox Code Playgroud)

也就是说,

    id  code
1   1   a
2   1   b 
3   2   a
4   2   a
5   3   b
6   3   b
Run Code Online (Sandbox Code Playgroud)

使用dplyr,我如何计算每个id的数量

   id  countA
1   1   1
2   2   2
3   3   0
Run Code Online (Sandbox Code Playgroud)

我正在尝试这样不起作用的东西,

countA<- dat %>%
group_by(id) %>%
summarise(cip.completed= count(code == "a"))
Run Code Online (Sandbox Code Playgroud)

上面给出了一个错误,"错误:没有适用于'group_by_'的方法应用于类的对象"逻辑""

谢谢你的帮助!

cof*_*nky 18

请尝试以下方法:

library(dplyr)
dat %>% group_by(id) %>%
  summarise(cip.completed= sum(code == "a"))

Source: local data frame [3 x 2]
    id cip.completed
  (dbl)         (int)
1     1             1
2     2             2
3     3             0
Run Code Online (Sandbox Code Playgroud)

这是有效的,因为逻辑条件code == a只是一系列零和1,而这个系列的总和是出现的次数.

请注意,您无论如何都不一定要使用dplyr::count内部summarise,因为它是用于summarise调用其中一个n()或其sum()自身的包装器.见?dplyr::count.如果你真的想使用count,我猜你可以通过首先过滤数据集来保留所有行code==a,然后使用count然后给你所有严格正(即非零)计数.例如,

dat %>% filter(code==a) %>% count(id)

Source: local data frame [2 x 2]

     id     n
  (dbl) (int)
1     1     1
2     2     2
Run Code Online (Sandbox Code Playgroud)