Home > Enterprise >  Use dynamic name in tidyverse
Use dynamic name in tidyverse

Time:06-09

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

CodePudding user response:

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))
  • Related