Home > Blockchain >  how to call variables while variable names was stored as a string
how to call variables while variable names was stored as a string

Time:08-12

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?

CodePudding user response:

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)))
  •  Tags:  
  • r
  • Related