1

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?

Stataq
  • 2,237
  • 6
  • 14
  • Does this answer your question? [Use dynamic name for new column/variable in \`dplyr\`](https://stackoverflow.com/questions/26003574/use-dynamic-name-for-new-column-variable-in-dplyr) – user438383 Aug 11 '22 at 18:41

1 Answers1

1

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)))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Do you think `eval` and/or `parse` can be used for this case? I am not familiar with these. Just a thought. Thanks. – Stataq Aug 11 '22 at 18:53
  • 1
    @Stataq Yes, the updated one with eval/parse_expr or `eval(parse(text = sprintf('df %%>%% arrange(%s)', order_var)))` – akrun Aug 11 '22 at 18:54
  • I original tried `arrange( eval(parse(paste0(order_var))))`. it must be wrong. could you tell me what did I do wrong if it is possible? – Stataq Aug 11 '22 at 18:57
  • 1
    @Stataq there are multiple issues in that statement i.e.`parse(text = `, but even then it returns error because of the `,`.. You can also check [here](https://stackoverflow.com/questions/17639325/unexpected-symbol-error-in-parsetext-str-with-hyphen-after-a-digit) – akrun Aug 11 '22 at 19:06
  • It looks like `across()` must only be used inside dplyr verbs. What if I want to use in `compareDF::compare_df` and its `group_col=`? – Stataq Aug 11 '22 at 20:30
  • @Stataq can you show an example – akrun Aug 11 '22 at 20:31
  • sth like `compareDF::compare_df( df_new , df_old , group_col = cross(all_of(strsplit(order_var, ",\\s*"))[[1]]), stop_on_error = FALSE )` – Stataq Aug 11 '22 at 20:35
  • 1
    why do you use `cross` and `all_of`, does `group_col = strsplit(order_var, ",\\s*")[[1]]` works? – akrun Aug 11 '22 at 20:37
  • 1
    i.e. `order_var <- "gear, carb"; compare_df(head(mtcars), head(mtcars, 10), group_col = strsplit(order_var, ",\\s*")[[1]])` works for me – akrun Aug 11 '22 at 20:38
  • what if I want to use `eval(parse..` for this case? – Stataq Aug 11 '22 at 20:41
  • 1
    @Stataq that would be `eval(parse(text = sprintf("compare_df(head(mtcars), head(mtcars, 10), group_col = c(%s))", gsub('(\\w+)', '"\\1"', order_var))))` – akrun Aug 11 '22 at 20:45