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 call variables while variable names was stored as a string

If I have a df and I would like to arrange it by 3 variables: "ID, AGE, SEX". How can I call them when I store those three variables’ name in a variable "order_var"

order_var <- "ID, AGE, SEX"

df %>% arrange (paste0 (order_var))

How can I call those three variables?

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

>Solution :

Here is one option – split the ‘order_var’ at the , followed by any space (\\s*), extract the list element ([[1]]), and pass it inside across with all_of

library(dplyr)
df %>%
   arrange(across(all_of(strsplit(order_var, ",\\s*"))[[1]]))

Or another option is eval by creating the full expression

 eval(rlang::parse_expr(sprintf('df %%>%% arrange(%s)', order_var)))
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