我觉得应该有一个非常简单的方法来执行此操作,但是我无法弄清楚。我想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
,但无法使用list
或保存变量c
。
请帮忙!寻找一种优雅的tidyverse解决方案。
有很多选项供您选择。
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 ...
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句