![](/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.