0

I am trying use the arrange() function from dplyr but specify the column dynamically.

Here is a reprex:

dt <- tibble(
  foo = 1:10,
  bar = 101:110
)

sort_by <- 'bar'

dt %>% arrange(sort_by) # does not work

dt %>% arrange(!!quo_name(sort_by)) # does not work either

What is the correct way to pass a dynamic column name to arrange()?

Merik
  • 2,587
  • 3
  • 23
  • 38

2 Answers2

3

Here are 4 approaches to pass string variables in arrange.

library(dplyr)
library(rlang)
  1. arrange_at
dt %>% arrange_at(sort_by)
  1. across - _at verbs are deprecated so we can use across from dplyr 1.0.0 instead.
dt %>% arrange(across(all_of(sort_by)))
  1. Using non-standard evaluation with sym and !!.
dt %>% arrange(!!sym(sort_by))
  1. Using .data pronoun
dt %>% arrange(.data[[sort_by]])
Ronak Shah
  • 355,584
  • 18
  • 123
  • 178
0

Try get

dt %>% arrange(get(sort_by))
MKa
  • 2,031
  • 14
  • 20