arrange_()多个列按降序排列 [英] arrange_() multiple columns with descending order

查看:382
本文介绍了arrange_()多个列按降序排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用排列_()与字符串输入,其中一列按降序排列。

I am trying to use arrange_() with string input and in one of the columns in descending order.

library(dplyr) # R version 3.3.0 (2016-05-03) , dplyr_0.4.3 
# data
set.seed(1)
df1 <- data.frame(grp = factor(c(1,2,1,2,1)),
                  x = round(runif(5,1,10), 2))

#   grp    x
# 1   1 3.39
# 2   2 4.35
# 3   1 6.16
# 4   2 9.17
# 5   1 2.82

以下是我需要实现的:

df1 %>% arrange(grp, -x)
df1 %>% arrange(grp, desc(x))
#   grp    x
# 1   1 6.16
# 2   1 3.39
# 3   1 2.82
# 4   2 9.17
# 5   2 4.35

在我的情况下,第二列是一个字符串:

In my case second column is a string:

#dynamic string
myCol <- "x"

#failed attempts
df1 %>% arrange_("grp", desc(myCol))




错误:尺寸不正确(1),期望:5

Error: incorrect size (1), expecting : 5



df1 %>% arrange_("grp", "desc(myCol)")




错误:object'myCol'not发现

Error: object 'myCol' not found



df1 %>% arrange_(c("grp", "desc(myCol)"))
#wrong output
#   grp    x
# 1   1 3.39
# 2   1 6.16
# 3   1 2.82
# 4   2 4.35
# 5   2 9.17

我发现了类似的解决方案此处,但无法使其正常工作:

I found similar solution here, but couldn't make it work:

df1 %>% arrange_(.dots = c("grp", "desc(myCol)"))




错误:对象'myCol'未找到

Error: object 'myCol' not found

感觉像我错过了一些非常明显的想法? / p>

Feels like I am missing something very obvious, ideas?

推荐答案

我们可以将粘贴'desc'作为字符串进行评估。

We can paste 'desc' as a string to evaluate it.

 myCol1 <- paste0("desc(", "x)")
 df1 %>% 
     arrange_(.dots = c("grp", myCol1))
 #  grp    x
 #1   1 6.16
 #2   1 3.39
 #3   1 2.82
 #4   2 9.17
 #5   2 4.35

或与'myCol'

 df1 %>% 
      arrange_(.dots = c("grp", paste0("desc(", myCol, ")")))

或使用 lazyeval

 library(lazyeval)
 df1 %>%
     arrange_(.dots = c("grp", interp(~ desc(n1), n1 = as.name(myCol))))
 #  grp    x
 #1   1 6.16
 #2   1 3.39
 #3   1 2.82
 #4   2 9.17
 #5   2 4.35






使用desc(myCol) ,它是一个单一的字符串,'myCol'的值不被评估。


By using "desc(myCol)", it is a single string and the value of the 'myCol' is not evaluated.

这篇关于arrange_()多个列按降序排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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