1

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

Phil
  • 7,287
  • 3
  • 36
  • 66
Merik
  • 2,767
  • 6
  • 25
  • 41

2 Answers2

4

Here are 5 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]])
  1. Latest addition is function pick
dt %>% arrange(pick(all_of(sort_by)))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0

Try get

dt %>% arrange(get(sort_by))
MKa
  • 2,248
  • 16
  • 22