如何计算案例数(类似于SQL中的COUNT ... GROUP BY)?
这是我的代码
library(magrittr)
library(dplyr)
df <- data.frame(dose=c("A", "B", "C","D", "E", "B","B", "E", "A","C", "C", "B"),
len=c(4.2, 10, 29.5,4.2, 10, 29.5,4.2, 10, 29.5,4.2, 10, 29.5))
mt_mean <- df %>% group_by(dose) %>% summarise(avg_count = sum(len) )
mt_mean
但我希望计数不是总和
所以当我将avg_count = sum(len)
更改为avg_count = count(len)
时
抛出以下错误
Error in summarise_impl(.data, dots) :
Evaluation error: no applicable method for 'groups' applied to an object of class "c('double', 'numeric')".
如何按R中的计数进行分组?
答案 0 :(得分:4)
使用dplyr
库并使用summarise
:
mt_mean <- df %>%
group_by(dose) %>%
summarise(avg_count = n())
或者,您可以使用dplyr
({@ 1}} count
进行更简单的操作:
mt_mean <- df %>%
count(dose) %>%
rename(avg_count = n)
这样,您还可以避免不必要的分组。
无论哪种方式,这两种方法都可以为您提供:
> mt_mean
# A tibble: 5 x 2
dose avg_count
<fctr> <int>
1 A 2
2 B 4
3 C 3
4 D 1
5 E 2