Home > Software engineering >  How to rename a variable with spaces in the name dynamically in dplyr?
How to rename a variable with spaces in the name dynamically in dplyr?

Time:06-29

I want to rename a variable in my dataframe using dplyr to have spaces but this variable name is a concatenation of a dynamic variable and a static string. In the following example, I'd need "Test1" to be a dynamic variable

df <- mtcars %>% select(`Test1 mpg` = "mpg")

So when I try this, I end up with an error:

var <- "Test1"

df <- mtcars %>% select(paste0(var, " mpg") = "mpg")

How could I go about making those new variable names dynamic?

CodePudding user response:

Using the special assignment operator := you could do:

library(dplyr)

df <- mtcars %>% select(`Test1 mpg` = "mpg")

var <- "Test1"

mtcars %>% 
  select("{var} mpg" := "mpg")
#>                     Test1 mpg
#> Mazda RX4                21.0
#> Mazda RX4 Wag            21.0
#> Datsun 710               22.8
#> Hornet 4 Drive           21.4

or using !!sym():

mtcars %>% 
  select(!!sym(paste(var, " mpg")) := "mpg")
#>                     Test1  mpg
#> Mazda RX4                 21.0
#> Mazda RX4 Wag             21.0
#> Datsun 710                22.8
#> Hornet 4 Drive            21.4
  • Related