tl;dr : df %>% arrange(desc(!!sym("b")))
First of all the standard evaluations of dplyr
verbs are deprecated, so instead of:
library(dplyr)
x <- "b"
df %>% arrange_(x)
it is now recommended to type:
library(dplyr)
library(rlang)
df %>% arrange(!!sym(x))
See ?arrange_
, it links to a help topic named Deprecated SE versions of main verbs.
and offers some details.
From there to sort descending it is straightforward to adapt the new formulation :
df %>% arrange(desc(!!sym(x)))
These work as well if your data is not grouped:
df %>% arrange(desc(.[[x]]))
df %>% arrange(desc(.data[[x]]))
FYI, to make it work with arrange_
we could have done the following, better use the approach above however!
df %>% arrange_(paste0("desc(",x,")"))
Which can be simplified if we have numeric variables like in OP's example:
df %>% arrange_(paste0("-",x))
Or using lazyeval::interp
df %>% arrange_(interp(~desc(y),y=as.name(x)))
Or as @shyam-saladi proposes:
desc_ <- function(x) lazyeval::interp(~desc(var), var = as.name(x))
# or just
# desc_ <- function(x) paste0("desc(",x,")")
df %>% arrange_(desc_(x))
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…