如何引用tibble列作为map函数的参数?

问题描述 投票:0回答:1

我想对 tibble 应用一个函数。 我将不得不对不同的 tibble 列重复它。

示例:

df <- tibble(
  g1 = c("A", "A", "B"),
  g2 = c("D", "E", "E"),
  b = c(4,5,6)
)

calc <- function(df, x) {
  df |> 
    group_by({{x}}) |> 
    summarise(val = sum(b))
}

calc(df, g1)
calc(df, g2)
# I have a long list of groups...

# Should I use a map? How to do it without getting an error?
map(list("g1", "g2"), ~ calc(df, .))

r parameter-passing
1个回答
0
投票

您必须先强制

x
来符号。请注意,现在必须引用列名称。

library(tidyverse)

df <- tibble(
  g1 = c("A", "A", "B"),
  g2 = c("D", "E", "E"),
  b = c(4,5,6)
)

calc <- function(df, x) {
  var <- sym(x)
  df |> 
    group_by({{var}}) |> 
    summarise(val = sum(b))
}

calc(df, g1)
#> Error in eval(expr, envir, enclos): object 'g1' not found
calc(df, "g1")
#> # A tibble: 2 × 2
#>   g1      val
#>   <chr> <dbl>
#> 1 A         9
#> 2 B         6
# I have a long list of groups...

map(list("g1", "g2"), ~ calc(df, .))
#> [[1]]
#> # A tibble: 2 × 2
#>   g1      val
#>   <chr> <dbl>
#> 1 A         9
#> 2 B         6
#> 
#> [[2]]
#> # A tibble: 2 × 2
#>   g2      val
#>   <chr> <dbl>
#> 1 D         4
#> 2 E        11

创建于 2024-08-24,使用 reprex v2.1.0

© www.soinside.com 2019 - 2024. All rights reserved.