In dplyr mutate, how do you use a variable to assign a new column name?

Viewed 37

I can use a variable to represent a column name in dplyr mutate, as long as it's on the right-hand side, in the calculation section. This works fine:

library(dplyr)
var <- "mass"
x <- starwars %>%
  mutate(height = height * 2,
         mass = get(var) * 2)

However, if I try to use a variable to represent a new column name (i.e., on the left-hand side), it throws an error. e.g, this leads to an error:

var <- "mass"
x <- starwars %>%
  mutate(height = height * 2,
         get(var) = get(var) * 2)

How do I use a variable as a column name in mutate?

1 Answers

Use the := operator with !! - instead of get, we could use [[ to extract with .data pronoun (or convert to symbol and evaluate (!!)

library(dplyr)
starwars %>%
  mutate(height = height * 2,
         !! var := .data[[var]] * 2)
         #or convert to symbol and evaluate
         # !! var := !! rlang::sym(var) * 2)
         #or use `{{}}`
        # {{var}} := !! rlang::sym(var) * 2)

-output

# A tibble: 87 × 14
   name               height  mass hair_color    skin_color  eye_color birth_year sex    gender    homeworld species films     vehicles  starships
   <chr>               <dbl> <dbl> <chr>         <chr>       <chr>          <dbl> <chr>  <chr>     <chr>     <chr>   <list>    <list>    <list>   
 1 Luke Skywalker        344   154 blond         fair        blue            19   male   masculine Tatooine  Human   <chr [5]> <chr [2]> <chr [2]>
 2 C-3PO                 334   150 <NA>          gold        yellow         112   none   masculine Tatooine  Droid   <chr [6]> <chr [0]> <chr [0]>
 3 R2-D2                 192    64 <NA>          white, blue red             33   none   masculine Naboo     Droid   <chr [7]> <chr [0]> <chr [0]>
 4 Darth Vader           404   272 none          white       yellow          41.9 male   masculine Tatooine  Human   <chr [4]> <chr [0]> <chr [1]>
 5 Leia Organa           300    98 brown         light       brown           19   female feminine  Alderaan  Human   <chr [5]> <chr [1]> <chr [0]>
 6 Owen Lars             356   240 brown, grey   light       blue            52   male   masculine Tatooine  Human   <chr [3]> <chr [0]> <chr [0]>
 7 Beru Whitesun lars    330   150 brown         light       blue            47   female feminine  Tatooine  Human   <chr [3]> <chr [0]> <chr [0]>
 8 R5-D4                 194    64 <NA>          white, red  red             NA   none   masculine Tatooine  Droid   <chr [1]> <chr [0]> <chr [0]>
 9 Biggs Darklighter     366   168 black         light       brown           24   male   masculine Tatooine  Human   <chr [1]> <chr [0]> <chr [1]>
10 Obi-Wan Kenobi        364   154 auburn, white fair        blue-gray       57   male   masculine Stewjon   Human   <chr [6]> <chr [1]> <chr [5]>
# … with 77 more rows
Related