使用字符串作为列名时如何使用dplyr :: arrange(desc())? [英] How to use dplyr::arrange(desc()) when using a string as column name?

查看:155
本文介绍了使用字符串作为列名时如何使用dplyr :: arrange(desc())?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 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))

但是我似乎不能同时使用 range 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%>%range(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 _ ,它链接到名为 main的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,")"))

如果我们有数值变量lik可以简化在OP的示例中为e:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆