xiaodai
xiaodai

Reputation: 16074

How do I do Standard evaluation with dplyr's arrange?

dplyr's arrange doesn't seem to work with !!

Please see MWE, where I am trying to sort a data.frame by the "date" variable, but instead of using date I want to parameterise it using a character/string

library(dplyr)

a = data.frame(date = 1:3, ok = 1:3)

a %>% 
  arrange(date)

date = "date"
a %>% 
  arrange(!!date) # doesn't work


meh = "date"
a %>% 
  arrange(!!meh) # doesn't work

I thought !! can be used in any dplyr function to perform Standard Evaluation (SE) of the variable. Is the understanding not correct? How do I correct this?

Upvotes: 4

Views: 143

Answers (3)

smarchese
smarchese

Reputation: 530

One approach (seems a bit roundabout but nevertheless works) is to use rlang::sym before applying the unquoting operator:

library(dplyr)

a = data.frame(date = 3:1, ok = 1:3)

a %>% 
  arrange(date)

acol = "date"
a %>% 
  arrange(!!rlang::sym(acol))

There's also a thorough guide here: dplyr programming guide.

See also this answer; basically the same thing.

Edit TIL via Diceboy's helpful comment that there are many ways to handle multiple variables:

a %>% arrange(get(name1),get(name2))
a %>% arrange(.data[[name1,name2]])
a %>% arrange(!!!rlang::syms(c(name1,name2)))

Though mget does not work nicely!

Upvotes: 1

G. Grothendieck
G. Grothendieck

Reputation: 270348

Use the .data variable:

a %>% arrange(.data[[date]])

Here are some more examples:

aa <- data.frame(date = c(13, 14, 11), ok = 3:1)

# sort by date
date <- "date"
aa %>% arrange(.data[[date]])
##   date ok
## 1   11  1
## 2   13  3
## 3   14  2

# sort by ok
date <- "ok"
aa %>% arrange(.data[[date]])
##   date ok
## 1   11  1
## 2   14  2
## 3   13  3

Upvotes: 1

fmarm
fmarm

Reputation: 4284

I don't know why !! does not work with arrange but you can still use get

a %>% arrange(get(meh))


#  date ok
#1    1  1
#2    2  2
#3    3  3

Upvotes: 2

Related Questions