我如何在 R 中按 ID 分组并按 na.rm = TRUE 的平均值进行汇总

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)))

输出:

# A tibble: 3 × 2
     ID     x
  <dbl> <dbl>
1     1   2.5
2     2   2.5
3     3   1