Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

arrange_() multiple columns with descending order

Tags:

r

dplyr

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

Below is what I need to achieve:

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

Error: incorrect size (1), expecting : 5

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

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

Error: object 'myCol' not found

Feels like I am missing something very obvious, ideas?

like image 510
zx8754 Avatar asked Jun 27 '16 11:06

zx8754


People also ask

What does arrange () do in R?

The arrange() function lets you reorder the rows of a tibble. It takes a tibble, followed by the unquoted names of columns. For example, to sort in ascending order of the values of column x , then (where there is a tie in x ) by descending order of values of y , you would write the following.

How do I sort multiple columns in ascending order pandas?

You can sort pandas DataFrame by one or multiple (one or more) columns using sort_values() method and by ascending or descending order. To specify the order, you have to use ascending boolean property; False for descending and True for ascending.

How do I arrange descending in R?

To sort a data frame in R, use the order( ) function. By default, sorting is ASCENDING. Prepend the sorting variable by a minus sign to indicate DESCENDING order.


1 Answers

This may do the trick: arrange(grp, across(c(x), desc))

dplyr version 1.0.5

like image 173
Daydownunder Avatar answered Sep 24 '22 02:09

Daydownunder