【发布时间】:2021-12-13 08:19:08
【问题描述】:
我在 R 中使用 dplyr 库。我有以下数据:
col1 = as.factor(c("a", "a", "a", "b", "b", "c", "c", "c"))
col2 = c(1,1,0,0,1, 0, 0, 1)
dplyr_data = data.frame(col1, col2)
head(dplyr_data)
col1 col2
1 a 1
2 a 1
3 a 0
4 b 0
5 b 1
6 c 0
7 c 0
8 c 1
我想知道是否可以直接写这样的代码:
library(dplyr)
summary_dplyr = data.frame(dplyr_data %>% group_by(col1) %>% dplyr::summarise(mean_count = mean(col1, na.rm = TRUE), special_count = count(1 - nrow(dplyr_data))))
这会返回以下错误:
Error: Problem with `summarise()` input `special_count`.
x no applicable method for 'group_vars' applied to an object of class "c('double', 'numeric')"
i Input `special_count` is `count(1 - nrow(dplyr_data))`.
i The error occurred in group 1: col1 = "a".
Run `rlang::last_error()` to see where the error occurred.
In addition: Warning messages:
1: In mean.default(col1, na.rm = TRUE) :
argument is not numeric or logical: returning NA
2: In mean.default(col1, na.rm = TRUE) :
argument is not numeric or logical: returning NA
3: In mean.default(col1, na.rm = TRUE) :
argument is not numeric or logical: returning NA
我正在尝试获得以下输出:
col1 mean_count special_count
1 a 0.66 3-1 = 2
2 b 0.50 2-1 = 1
3 c 0.33 3-2 = 1
基本上,“special_count” = 对于 col_1 的每个唯一组(即 a、b、c):取总行数并减去 0 的数量。
有人可以告诉我怎么做吗?
谢谢
【问题讨论】:
标签: r dplyr count mean data-manipulation