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

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:

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

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

How can i fix it, thank all very much

>Solution :

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