gpt4 book ai didi

r - 如何避免省略号......在dplyr中?

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

我想创建一个接受分组参数的函数。其中可以是单个或多个变量。我希望它看起来像这样:

wanted <- function(data, groups, other_params){
data %>% group_by( {{groups}} ) %>% count()
}

这仅在给出单个组时有效,但在有多个组时会中断。我知道可以使用带有省略号的以下内容 ... (但我想要语法 groups = something ):
not_wanted <- function(data, ..., other_params){
data %>% group_by( ... ) %>% count()
}

这是整个代码:
library(dplyr)
library(magrittr)

iris$group2 <- rep(1:5, 30)

wanted <- function(data, groups, other_params){
data %>% group_by( {{groups}} ) %>% count()
}

not_wanted <- function(data, ..., other_params){
data %>% group_by( ... ) %>% count()
}

# works
wanted(iris, groups = Species )
not_wanted(iris, Species, group2)

# doesn't work
wanted(iris, groups = vars(Species, group2) )
wanted(iris, groups = c(Species, group2) )
wanted(iris, groups = vars("Species", "group2") )
# Error: Column `vars(Species, group2)` must be length 150 (the number of rows) or one, not 2

最佳答案

你们把事情复杂化了,这很好用:

library(tidyverse)

wanted <- function(data, groups){
data %>% count(!!!groups)
}

mtcars %>% wanted(groups = vars(mpg,disp,hp))

# A tibble: 31 x 4
mpg disp hp n
<dbl> <dbl> <dbl> <int>
1 10.4 460 215 1
2 10.4 472 205 1
3 13.3 350 245 1
4 14.3 360 245 1
5 14.7 440 230 1
6 15 301 335 1
7 15.2 276. 180 1
8 15.2 304 150 1
9 15.5 318 150 1
10 15.8 351 264 1
# … with 21 more rows

关于r - 如何避免省略号......在dplyr中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59611638/

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