gpt4 book ai didi

rlang:使用 ... 传递多个组以收集()

转载 作者:行者123 更新时间:2023-12-04 12:11:23 24 4
gpt4 key购买 nike

假设我想计算 mean , minmax对于自定义函数中任意数量的组。

玩具数据如下所示:

library(tidyverse)
df <- tibble(
Gender = c("m", "f", "f", "m", "m",
"f", "f", "f", "m", "f"),
IQ = rnorm(10, 100, 15),
Other = runif(10),
Test = rnorm(10),
group2 = c("A", "A", "A", "A", "A",
"B", "B", "B", "B", "B")
)

为了实现这两个组(性别,group2),我可以使用
df %>% 
gather(Variable, Value, -c(Gender, group2)) %>%
group_by(Gender, group2, Variable) %>%
summarise(mean = mean(Value),
min = min(Value),
max = max(Value))

可与新 curly-curly 集成运营商来自 rlang
descriptive_by <- function(data, group1, group2) {
data %>%
gather(Variable, Value, -c({{ group1 }}, {{ group2 }})) %>%
group_by({{ group1 }}, {{ group2 }}, Variable) %>%
summarise(mean = mean(Value),
min = min(Value),
max = max(Value))
}

通常,我会假设我可以用 ... 替换指定的组。 ,但它似乎不像那样工作
descriptive_by <- function(data, ...) {
data %>%
gather(Variable, Value, -c(...)) %>%
group_by(..., Variable) %>%
summarise(mean = mean(Value),
min = min(Value),
max = max(Value))
}

因为它返回错误

Error in map_lgl(.x, .p, ...) : object 'Gender' not found

最佳答案

这是一种可能的解决方案,其中 ...传递给 group_by直接和 gather只收集数字列(因为我认为它永远不应该收集独立于输入的非数字列 ... )。

library(tidyverse)

set.seed(1)

## data
df <- tibble(
Gender = c("m", "f", "f", "m", "m",
"f", "f", "f", "m", "f"),
IQ = rnorm(10, 100, 15),
Other = runif(10),
Test = rnorm(10),
group2 = c("A", "A", "A", "A", "A",
"B", "B", "B", "B", "B")
)

## function
descriptive_by <- function(data, ...) {

data %>%
gather(Variable, Value, names(select_if(., is.numeric))) %>%
group_by(..., Variable) %>%
summarise(mean = mean(Value),
min = min(Value),
max = max(Value))
}

descriptive_by(df, Gender, group2)
#> # A tibble: 12 x 6
#> # Groups: Gender, group2 [4]
#> Gender group2 Variable mean min max
#> <chr> <chr> <chr> <dbl> <dbl> <dbl>
#> 1 f A IQ 95.1 87.5 103.
#> 2 f A Other 0.432 0.212 0.652
#> 3 f A Test 0.464 -0.0162 0.944
#> 4 f B IQ 100. 87.7 111.
#> 5 f B Other 0.281 0.0134 0.386
#> 6 f B Test 0.599 0.0746 0.919
#> 7 m A IQ 106. 90.6 124.
#> 8 m A Other 0.442 0.126 0.935
#> 9 m A Test 0.457 -0.0449 0.821
#> 10 m B IQ 109. 109. 109.
#> 11 m B Other 0.870 0.870 0.870
#> 12 m B Test -1.99 -1.99 -1.99

关于rlang:使用 ... 传递多个组以收集(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56968968/

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