我在 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 的數量。
有人可以告訴我如何做到這一點嗎?
謝謝
uj5u.com熱心網友回復:
您不能count()在內部使用,summarize但可以使用sum()布林值計算值。sum(col2==0)將告訴您帶有 0 的行數并n()給出總行數(每組)
dplyr_data %>%
group_by(col1) %>%
summarize(mean_count=mean(col2),
special_count = n() - sum(col2==0))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/340032.html
上一篇:折疊R中的行:無法將“公式”類強制轉換為data.frame(R)
下一篇:選擇只包含特定字母的字串
