如何在dplyr中使用变量列表?

问题描述

我觉得应该有一个非常简单的方法来执行此操作,但是我无法弄清楚。我想在大型数据集中使用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解决方案。

解决方法

自dplyr 1.0.0起,

vars已被取代。您可以直接在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,..: 1 1 1 1 1 1 1 1 1 1 ...

> iris %>% mutate(across(!!VARS3,..: 1 1 1 1 1 1 1 1 1 1 ...