我想按ID和摘要分组,同时删除NAs。请参见下面的示例代码。
# 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
使用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)))
输出:
# A tibble: 3 × 2
ID x
<dbl> <dbl>
1 1 2.5
2 2 2.5
3 3 1