gpt4 book ai didi

r - 使用 "{{"运算符通过环境变量隧道数据变量

转载 作者:行者123 更新时间:2023-12-02 09:04:18 26 4
gpt4 key购买 nike

遵循 https://www.tidyverse.org/blog/2020/02/glue-strings-and-tidy-eval/ 中的示例

如何将变量传递给这个函数?

library(tidyverse)
#> Warning: package 'tidyverse' was built under R version 3.6.2
#> Warning: package 'tidyr' was built under R version 3.6.2

mean_by <- function(data, by, var, prefix = "avg") {
data %>%
group_by({{ by }}) %>%
summarise("{prefix}_{{ var }}" := mean({{ var }}, na.rm = TRUE))
}

mean_by(mtcars, by = cyl, var = mpg, prefix = "avg")
#> # A tibble: 3 x 2
#> cyl avg_mpg
#> <dbl> <dbl>
#> 1 4 26.7
#> 2 6 19.7
#> 3 8 15.1

# Variables to pass into function
params <- setdiff(colnames(mtcars) ,"mpg")

# How do you pass a variables into this function?
purrr::map(params, mean_by(mtcars, by = .x, var = mpg, prefix = "avg"))
#> Error: Column `.x` is unknown

reprex package 创建于 2020-02-19 (v0.3.0)

最佳答案

对列名使用.data代词:

purrr::map(params, ~ mean_by(mtcars, by = .data[[.x]], var = mpg, prefix = "avg"))

关于r - 使用 "{{"运算符通过环境变量隧道数据变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60305159/

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