gpt4 book ai didi

r - 按聚合动态列名匹配分组

转载 作者:行者123 更新时间:2023-12-04 17:43:59 25 4
gpt4 key购买 nike

是否可以group_by使用 dplyr 在列名上使用正则表达式匹配?

library(dplyr) # dplyr_0.5.0; R version 3.3.2 (2016-10-31)

# dummy data
set.seed(1)
df1 <- sample_n(iris, 20) %>%
mutate(Sepal.Length = round(Sepal.Length),
Sepal.Width = round(Sepal.Width))

按静态版本分组(看起来/工作正常,想象一下我们有 10-20 列):
df1 %>% 
group_by(Sepal.Length, Sepal.Width) %>%
summarise(mySum = sum(Petal.Length))

按动态分组 - “丑陋”版本:
df1 %>% 
group_by_(.dots = colnames(df1)[ grepl("^Sepal", colnames(df1))]) %>%
summarise(mySum = sum(Petal.Length))

理想情况下,像这样(不起作用,因为 starts_with 返回索引):
df1 %>% 
group_by(starts_with("Sepal")) %>%
summarise(mySum = sum(Petal.Length))

Error in eval(expr, envir, enclos) : 
wrong result size (0), expected 20 or 1


预期输出:
# Source: local data frame [6 x 3]
# Groups: Sepal.Length [?]
#
# Sepal.Length Sepal.Width mySum
# <dbl> <dbl> <dbl>
# 1 4 3 1.4
# 2 5 3 10.9
# 3 6 2 4.0
# 4 6 3 43.7
# 5 7 3 15.7
# 6 8 4 6.4

注:听起来很像重复的帖子,请链接相关帖子(如果有)。

最佳答案

此功能将在 future 版本中实现,引用 GitHub issue #2619 :

解决方案是使用 group_by_at功能:

df1 %>%
group_by_at(vars(starts_with("Sepal"))) %>%
summarise(mySum = sum(Petal.Length))

编辑:这现在在 中实现dplyr_0.7.1

关于r - 按聚合动态列名匹配分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43229133/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com