Search code examples
rdplyrrlangacross

How to use a list of variables with dplyr across?


I feel like there should be a very simple way to do this, but I can't figure this out. I want to use across with a list of variables and tidyselect helpers in a large dataset, but I'll use iris as an example.

Before the dplyr 1.0 update, I could successfully use scoped verbs like this:

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

I thought iris %>% mutate(across(!!!VARS, as.character)) would work but I get an error. I know the update supersedes vars, but I'm not able to save the variables with list or c.

Please help! Looking for an elegant tidyverse solution.


Solution

  • There are many options for you to choose.

    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")))
    

    Output

    > 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 ...