使用字符串作为列名时如何使用 dplyr::arrange(desc())? [英] How to use dplyr::arrange(desc()) when using a string as column name?
问题描述
如何使用 dplyr::arrange(dplyr::desc())
并传入一个字符串作为列名?
How can I use dplyr::arrange(dplyr::desc())
and pass in a string as the column name?
这是一个示例数据集:
df <- data.frame(a = 1:3, b = 3:1)
有效的例子:
df %>% dplyr::arrange(b)
df %>% dplyr::arrange_("b")
df %>% dplyr::arrange(dplyr::desc(b))
但我似乎无法同时使用 arrange
和 desc
的字符串,这是我尝试过的两个版本,但都不起作用:
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"))
谢谢!
推荐答案
tl;dr :
df %>%排列(desc(!!sym("b")))
首先,dplyr
动词的标准评估已被弃用,因此:
First of all the standard evaluations of dplyr
verbs are deprecated, so instead of:
library(dplyr)
x <- "b"
df %>% arrange_(x)
现在建议输入:
library(dplyr)
library(rlang)
df %>% arrange(!!sym(x))
请参阅 ?arrange_
,它链接到名为 Deprecated SE 版本的主要动词的帮助主题.
并提供了一些详细信息.
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]]))
<小时>
仅供参考,要使其与 arrange_
一起使用,我们可以执行以下操作,但最好使用上述方法!
FYI, to make it work with arrange_
we could have done the following, better use the approach above however!
df %>% arrange_(paste0("desc(",x,")"))
如果我们有 OP 示例中的数字变量,则可以简化:
Which can be simplified if we have numeric variables like in OP's example:
df %>% arrange_(paste0("-",x))
或者使用lazyeval::interp
df %>% arrange_(interp(~desc(y),y=as.name(x)))
或者如@shyam-saladi 建议的那样:
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))
这篇关于使用字符串作为列名时如何使用 dplyr::arrange(desc())?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!