![](/img/trans.png)
[英]How to Use na.rm=TRUE with n() While Using Dplyr's Group_by and Summarise_at
[英]How can I in R, group by ID and summarise by mean with na.rm = TRUE
我想按 ID 分組並進行總結,同時刪除 NA。 請參閱下面的示例代碼。
# Example data
ID <- c(1, 1, 1, 2, 2, 3, 3)
x <- c(2, 3, NA, 2, 3, 1, 1)
ID_x <- tibble(ID, x)
# 1. Works
ID_x %>%
group_by(ID) %>%
summarise_each(mean)
# 2. Does not work with na.rm=TRUE
ID_x %>%
group_by(ID) %>%
summarise_each(mean(., na.rm=TRUE))
提前致謝
使用 lambda ( ~
library(dplyr)
ID_x %>%
group_by(ID) %>%
summarise_each(~ mean(., na.rm=TRUE))
-輸出
# A tibble: 3 × 2
ID x
<dbl> <dbl>
1 1 2.5
2 2 2.5
3 3 1
此外,在最近的版本中, summarise_each
將伴隨警告,因為這些已被棄用,有利於across
ID_x %>%
group_by(ID) %>%
summarise(across(everything(), ~ mean(., na.rm=TRUE)))
一個不同的選擇是使用funs
。 你也可以使用這個:
ID_x %>%
group_by(ID) %>%
summarise_each(funs(mean(., na.rm = TRUE)))
Output:
# A tibble: 3 × 2
ID x
<dbl> <dbl>
1 1 2.5
2 2 2.5
3 3 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.