Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
691 views
in Technique[技术] by (71.8m points)

r - How to use dplyr::arrange(desc()) when using a string as column name?

How can I use dplyr::arrange(dplyr::desc()) and pass in a string as the column name?

Here is a sample dataset:

df <- data.frame(a = 1:3, b = 3:1)

Examples that work:

df %>% dplyr::arrange(b)
df %>% dplyr::arrange_("b")
df %>% dplyr::arrange(dplyr::desc(b))

But I can't seem to use a string with both arrange and desc, these are the two version I tried that don't work:

df %>% dplyr::arrange(dplyr::desc("b"))
df %>% dplyr::arrange_(dplyr::desc("b"))

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...