如何跨 dplyr 使用变量列表?

How to use a list of variables with dplyr across?

我觉得应该有一个非常简单的方法来做到这一点,但我想不出来。我想在大型数据集中将 across 与变量列表和 tidyselect 助手一起使用,但我将使用 iris 作为示例。

在 dplyr 1.0 更新之前,我可以像这样成功地使用作用域动词:

VARS <- vars(Sepal.Length, starts_with("Petal"))
iris %>% 
  mutate_at(VARS, as.character)

我认为 iris %>% mutate(across(!!!VARS, as.character)) 可以,但我收到错误消息。我知道更新会取代 vars,但我无法使用 listc.

保存变量

请帮忙!寻找一个优雅的 tidyverse 解决方案。

vars 自 dplyr 1.0.0 以来已被取代。您可以在 across.

中直接将列名用作字符串或不带引号的变量
library(dplyr)
iris %>% 
  mutate(across(c(Sepal.Length, starts_with("Petal")), as.character))

如果你想先保存变量然后再应用函数你可以这样做。

VARS <- c('Sepal.Length', grep('^Petal', names(iris), value = TRUE))

iris %>% mutate(across(VARS, as.character)) 

有多种选择供您选择。

library(dplyr)
VARS1 <- quote(c(Sepal.Length, starts_with("Petal")))
VARS2 <- expr(c(Sepal.Length, starts_with("Petal")))
VARS3 <- quo(c(Sepal.Length, starts_with("Petal")))

输出

> iris %>% mutate(across(!!VARS1, as.character)) %>% str()
'data.frame':   150 obs. of  5 variables:
 $ Sepal.Length: chr  "5.1" "4.9" "4.7" "4.6" ...
 $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
 $ Petal.Length: chr  "1.4" "1.4" "1.3" "1.5" ...
 $ Petal.Width : chr  "0.2" "0.2" "0.2" "0.2" ...
 $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...

> iris %>% mutate(across(!!VARS2, as.character)) %>% str()
'data.frame':   150 obs. of  5 variables:
 $ Sepal.Length: chr  "5.1" "4.9" "4.7" "4.6" ...
 $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
 $ Petal.Length: chr  "1.4" "1.4" "1.3" "1.5" ...
 $ Petal.Width : chr  "0.2" "0.2" "0.2" "0.2" ...
 $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...

> iris %>% mutate(across(!!VARS3, as.character)) %>% str()
'data.frame':   150 obs. of  5 variables:
 $ Sepal.Length: chr  "5.1" "4.9" "4.7" "4.6" ...
 $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
 $ Petal.Length: chr  "1.4" "1.4" "1.3" "1.5" ...
 $ Petal.Width : chr  "0.2" "0.2" "0.2" "0.2" ...
 $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...