简体   繁体   中英

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?

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

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM