Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to rename a variable with spaces in the name dynamically in dplyr?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var <- "Test1"

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

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading