R Dplyr:汇总列(如果存在)

R Dplyr: Summarizing a column, if it is present

在 R 中,在 tidyverse 中工作: 我的数据源发生变化。有一个专栏仅出现几周。到时候,我想总结一下。以 iris 为例,假设 Sepal.Width 有时会丢失。从概念上讲,我想要这样的函数

library(tidyverse)

summIris <- function(irisDf){
  irisDf %>% 
    group_by(Species) %>% 
      summarise_ifPresent(
                Sepal.Length = mean(Sepal.Length),
                Sepal.Width = mean(Sepal.Width))
}

哪个 return

R >  summIris(iris  )
# A tibble: 3 x 3
  Species    Sepal.Length Sepal.Width
  <fct>             <dbl>       <dbl>
1 setosa             5.01        3.43
2 versicolor         5.94        2.77
3 virginica          6.59        2.97

 > summIris(iris %>% select(- Sepal.Width ))
# A tibble: 3 x 2
  Species    Sepal.Length 
  <fct>             <dbl> 
1 setosa             5.01 
2 versicolor         5.94  
3 virginica          6.59 

我可以通过将逻辑包装在 if else 中来解决问题。但是有没有更简洁优雅的呢?

summarize_at 允许您定义在哪些列上执行摘要,您可以使用 starts_withends_withmatchescontains动态 select 列。

library(dplyr)
iris %>%
  group_by(Species) %>%
  summarize_at(vars(starts_with("Sepal")), funs(mean(.)))
# # A tibble: 3 x 3
#   Species    Sepal.Length Sepal.Width
#   <fct>             <dbl>       <dbl>
# 1 setosa             5.01        3.43
# 2 versicolor         5.94        2.77
# 3 virginica          6.59        2.97
iris %>%
  select(-Sepal.Length) %>%
  group_by(Species) %>%
  summarize_at(vars(starts_with("Sepal")), funs(mean(.)))
# # A tibble: 3 x 2
#   Species    Sepal.Width
#   <fct>            <dbl>
# 1 setosa            3.43
# 2 versicolor        2.77
# 3 virginica         2.97

另一个也有效,但给出了未找到列的警告:

iris %>%
  select(-Sepal.Length) %>%
  group_by(Species) %>%
  summarize_at(vars(one_of(c("Sepal.Width", "Sepal.Length"))), funs(mean(.)))
# Warning: Unknown columns: `Sepal.Length`
# # A tibble: 3 x 2
#   Species    Sepal.Width
#   <fct>            <dbl>
# 1 setosa            3.43
# 2 versicolor        2.77
# 3 virginica         2.97