以iris为例。在按Species分组之后,我想按其mean汇总Sepal.Length,然后按last汇总所有剩余的列;(不单独调用其余的列。)想要结果
# A tibble: 3 x 5
Species Sepal.Length Sepal.Width Petal.Length Petal.Width
<fct> <dbl> <dbl> <dbl> <dbl>
1 setosa 5.01 3.3 1.4 0.2
2 versicolor 5.94 2.8 4.1 1.3
3 virginica 6.59 3 5.1 1.8运行时不会出现错误:
library(tidyverse)
iris %>%
as_tibble %>%
group_by(Species) %>%
summarise_all(~last(.))但这不是:
iris %>%
as_tibble %>%
group_by(Species) %>%
summarise_all(Sepal.Length = mean(Sepal.Length), ~ last(.))我尝试过使用everything()以及使用summarise_at和summarise_if,但是我还没有找到正确的语法来做到这一点。
发布于 2020-06-11 07:29:53
因为summarise_at和summarise_all将相同的函数映射到选定的变量,所以不能在这里使用它们。
以自动方式对不同列执行不同汇总的一种方法是使用引用和取消引用技术创建expression:
library(dplyr)
cols = names(iris)[2:4] # select remaining columns
col_syms = syms(cols) # create symbols from strings
summary_vars <- lapply(col_syms, function(col) {
expr(last(!!col)) # expression that should be evaluated in summarise
})
names(summary_vars) = cols # new column names (set old names)
iris %>%
group_by(Species) %>%
summarise(Sepal.Length = mean(Sepal.Length), !!!summary_vars) # open expressions您可以通过将dplyr的管道包装到rlang::qq_show()中来查看要计算的内容
发布于 2020-06-11 01:55:13
做这份工作,并没有发现更优雅:
inner_join(iris %>%
select(Species,Sepal.Length) %>%
group_by(Species) %>%
summarise_all(list(mean)),
iris %>%
select(-Sepal.Length) %>%
group_by(Species) %>%
summarise_all(list(last)),
by = "Species")https://stackoverflow.com/questions/62308729
复制相似问题