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

时间:2019-12-04 19:27:18

标签: r dplyr summarization

在R中,在tidyverse中工作: 我的数据源发生了变化。有一个专栏只出现了几个星期。当它是,我想总结一下。以Text file encoding为例,假设Inherited from container (UTF-8)有时会丢失。从概念上讲,我想要这样的功能

iris

会回来的

Sepal.Width

我可以通过将逻辑包装在library(tidyverse) summIris <- function(irisDf){ irisDf %>% group_by(Species) %>% summarise_ifPresent( Sepal.Length = mean(Sepal.Length), Sepal.Width = mean(Sepal.Width)) } 中来解决。但是还有更简洁,更优雅的东西吗?

1 个答案:

答案 0 :(得分:3)

summarize_at允许您定义在哪个列上执行摘要,并且可以使用starts_withends_withmatchescontains动态选择列。

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