[英]How can I in R, group by ID and summarise by mean with na.rm = TRUE
I want to group by ID and summarise, whilst removing NAs.我想按 ID 分组并进行总结,同时删除 NA。 please see example code below.
请参阅下面的示例代码。
# 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))
Thanks in advance提前致谢
Use the lambda ( ~
使用 lambda (
~
library(dplyr)
ID_x %>%
group_by(ID) %>%
summarise_each(~ mean(., na.rm=TRUE))
-output -输出
# A tibble: 3 × 2
ID x
<dbl> <dbl>
1 1 2.5
2 2 2.5
3 3 1
Also, in recent versions, the summarise_each
will accompany a warning as these are deprecated in favor of across
此外,在最近的版本中,
summarise_each
将伴随警告,因为这些已被弃用,有利于across
ID_x %>%
group_by(ID) %>%
summarise(across(everything(), ~ mean(., na.rm=TRUE)))
A different option would be using funs
.一个不同的选择是使用
funs
。 You can also use this:你也可以使用这个:
ID_x %>%
group_by(ID) %>%
summarise_each(funs(mean(., na.rm = TRUE)))
Output: 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.