Stataq
Stataq

Reputation: 2297

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?

Upvotes: 1

Views: 39

Answers (1)

akrun
akrun

Reputation: 887118

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

Upvotes: 1

Related Questions