Kevin_Nguyen
Kevin_Nguyen

Reputation: 112

Use dynamic name in tidyverse

I want to round the variable with name of variable is object.I have problem with using dynamic name in mutate. Here sample data:

df <- structure(list(f116_gr = c(1, 2, 3, 5, 4, 6, NA), 
                     f116_gr_sc = c(-1.36988327957453,-0.144575006139099, 0.63865967223421, 
                                    1.23657391288124, 1.53907997023586,-0.280185492819537, 0)), 
                row.names = c(NA, -7L), class = c("tbl_df","tbl", "data.frame"))

I can do it with this code:

z <- "f116_gr_sc"
df[, eval(z)] = round(df[, eval(z)], 2)

But when i try it using mutate function, there is a error:

library(dplyr)
z <- "f116_gr_sc"
df %>%
    mutate(!!z := round(paste0(!!z), 2))

How can i fix it, thank all very much

Upvotes: 1

Views: 144

Answers (2)

Yuriy Saraykin
Yuriy Saraykin

Reputation: 8880

use sym

df <- data.frame(
  f116_gr = c(1, 2, 3, 5, 4, 6, NA),
  f116_gr_sc = c(-1.36988327957453,-0.144575006139099,
                 0.63865967223421,1.23657391288124,1.53907997023586,
                 -0.280185492819537,0))
z <- "f116_gr_sc"

library(tidyverse)
df %>% 
 mutate(!!sym(z) := round(!!sym(z), 2))
#>   f116_gr f116_gr_sc
#> 1       1      -1.37
#> 2       2      -0.14
#> 3       3       0.64
#> 4       5       1.24
#> 5       4       1.54
#> 6       6      -0.28
#> 7      NA       0.00

# or
z <- sym("f116_gr_sc")
df %>% 
  mutate(!!z := round(!!z, 2))
#>   f116_gr f116_gr_sc
#> 1       1      -1.37
#> 2       2      -0.14
#> 3       3       0.64
#> 4       5       1.24
#> 5       4       1.54
#> 6       6      -0.28
#> 7      NA       0.00

Created on 2022-06-09 by the reprex package (v2.0.1)

Upvotes: 1

Kra.P
Kra.P

Reputation: 15123

Add as.name will helps.

x <- "f116"
z <- "f116_gr_sc"
df %>%
  mutate(!!z := round(!!as.name(paste0(x,"_gr_sc")), 2))

  f116_gr f116_gr_sc
    <dbl>      <dbl>
1       1      -1.37
2       2      -0.14
3       3       0.64
4       5       1.24
5       4       1.54
6       6      -0.28
7      NA       0   

This will works.

new z

df %>%
  mutate(!!z := round(!!as.name(paste0(z)), 2))

Upvotes: 1

Related Questions