1

我觉得应该有一个非常简单的方法来做到这一点,但我无法弄清楚。我想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,但我无法使用listor保存变量c

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

4

2 回答 2

3

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)) 
于 2020-11-10T03:02:31.707 回答
1

有很多选项供您选择。

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 ...
于 2020-11-10T05:35:31.823 回答