如何在没有变量的情况下以编程方式使用 dplyrcross()?

Blu*_*oxe 5 variables evaluation r dplyr across

问题:

我想以across()编程方式使用,例如,如果NULL向它传递一个空字符串,则该函数不会失败。这可能是使用函数的作用域变体,例如group_by_at(),但我想让它使用across().

另请注意,across()如果留空,当前将影响所有列。我不确定这样做的动机是什么;对我来说,如果没有列受到影响会更有意义。

例子

这是一个使用函数计算变量平均值的快速示例y。传递分组变量适用于group_by_at(),但不适用于across()如图所示:

my_df <- tibble("x" = c("a", "a", "b", "b"), y = 1:4)

compute_mean1 <- function(df, grouping) { # compute grouped mean with across()
  df %>% 
    group_by(across(all_of(grouping))) %>% 
    summarise(y = mean(y), .groups = "drop")
}

compute_mean2 <- function(df, grouping) { # compute grouped mean with group_by_at()
  df %>% 
    group_by_at(grouping) %>% 
    summarise(y = mean(y), .groups = "drop")
}


compute_mean1(my_df, "x")
#> # A tibble: 2 x 2
#>   x         y
#>   <chr> <dbl>
#> 1 a       1.5
#> 2 b       3.5
compute_mean1(my_df, NULL)
#> Error: `vars` must be a character vector.
compute_mean2(my_df, "x")
#> # A tibble: 2 x 2
#>   x         y
#>   <chr> <dbl>
#> 1 a       1.5
#> 2 b       3.5
compute_mean2(my_df, NULL)
#> # A tibble: 1 x 1
#>       y
#>   <dbl>
#> 1   2.5
Run Code Online (Sandbox Code Playgroud)

reprex 包(v0.3.0)于 2020 年 7 月 14 日创建

G. *_*eck 5

.add=TRUE像这样使用:

compute_mean3 <- function(df, grouping) { # compute grouped mean with across()
  df %>% 
    group_by(across(all_of(grouping)), .add = TRUE) %>%
    summarise(y = mean(y), .groups = "drop")
}
 
Run Code Online (Sandbox Code Playgroud)