【发布时间】:2020-01-10 12:36:31
【问题描述】:
我正在尝试通过不同的summarise_at/summarise_if 函数来dplyr::summarise 一个数据集(折叠),以便我的输出数据集中具有相同的命名变量。示例:
library(tidyverse)
data(iris)
iris$year <- rep(c(2000,3000),each=25) ## for grouping
iris$color <- rep(c("red","green","blue"),each=50) ## character column
iris$letter <- as.factor(rep(c("A","B","C"),each=50)) ## factor column
head(iris, 3)
Sepal.Length Sepal.Width Petal.Length Petal.Width Species year color letter
1 5.1 3.5 1.4 0.2 setosa 2000 red A
2 4.9 3.0 1.4 0.2 setosa 2000 red A
3 4.7 3.2 1.3 0.2 setosa 2000 red A
生成的数据集应如下所示:
full
Species year Sepal.Width Petal.Width Sepal.Length Petal.Length letter color
<fct> <dbl> <dbl> <dbl> <dbl> <dbl> <fct> <chr>
1 setosa 2000 87 6.2 5.8 1.9 A red
2 setosa 3000 84.4 6.1 5.5 1.9 A red
3 versicolor 2000 69.4 33.6 7 4.9 B green
4 versicolor 3000 69.1 32.7 6.8 5.1 B green
5 virginica 2000 73.2 51.1 7.7 6.9 C blue
6 virginica 3000 75.5 50.2 7.9 6.4 C blue
我可以通过执行以下有点重复的操作来实现这一点:
sums <- iris %>%
group_by(Species, year) %>%
summarise_at(vars(matches("Width")), list(sum))
max <- iris %>%
group_by(Species, year) %>%
summarise_at(vars(matches("Length")), list(max))
last <- iris %>%
group_by(Species, year) %>%
summarise_if(is.factor, list(last))
first <- iris %>%
group_by(Species, year) %>%
summarise_if(is.character, list(first))
full <- full_join(sums, max) %>% full_join(last) %>% full_join(first)
我在下面找到了类似的方法,但无法弄清楚我在这里尝试过的方法。我宁愿不创建自己的函数,因为我认为通过将所有内容都通过管道并加入,这样的事情会更干净:
test <- iris %>%
#group_by(.vars = vars(Species, year)) %>% #why doesnt this work?
group_by_at(.vars = vars(Species, year)) %>% #doesnt work
{left_join(
summarise_at(., vars(matches("Width")), list(sum)),
summarise_at(., vars(matches("Length")), list(max)),
summarise_if(., is.factor, list(last)),
summarise_if(., is.character, list(first))
)
} #doesnt work
这不起作用,有什么建议或其他方法吗?
有用的: How can I use summarise_at to apply different functions to different columns? Summarize different Columns with different Functions Using dplyr summarize with different operations for multiple columns
【问题讨论】:
-
您想要宽度列的总和、长度列的最大值、最后一个字母和第一个颜色?可以使用 summarise 函数来完成,例如
summarise(min(Sepal.Width), max(Sepal.Length)) -
只有当您有 2 个汇总语句时,您的第二种方法才有效,因为 full_join 只能连接 2 个数据框
-
left_join已编辑。 @Vikrant 如果我有一个包含许多变量的大型数据集,那将不够灵活。使用summarise_at/summarise_if可以解决这个问题。
标签: r group-by dplyr summarize