How to use dplyr :: arr (desc ()) when using a row as a column name?

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

Here is an example 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 not use the line with arrange and desc , these are two versions that I tried that do not work:

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

Thanks!

+7
source share
1 answer

tl; dr: df %>% arrange(desc(!!sym("b")))

First of all, standard verbs of dplyr verbs dplyr out of date, so instead of:

 library(dplyr) x <- "b" df %>% arrange_(x) 

Now it is recommended to type:

 library(dplyr) library(rlang) df %>% arrange(!!sym(x)) 

See ?arrange_ , this is a link to the ?arrange_ help" called Deprecated SE versions of main verbs. and offers some details.

From there, sorting in descending order it is easy to adapt the new wording:

 df %>% arrange(desc(!!sym(x))) 

This also works if your data is not grouped:

 df %>% arrange(desc(.[[x]])) df %>% arrange(desc(.data[[x]])) 

For your information, to make arrange_ work arrange_ we could do the following, but it’s better to use the approach described above!

 df %>% arrange_(paste0("desc(",x,")")) 

Which can be simplified if we have numerical variables, as in the example with OP:

 df %>% arrange_(paste0("-",x)) 

Or using lazyeval::interp

 df %>% arrange_(interp(~desc(y),y=as.name(x))) 

Or as @ shyam-saladi suggests:

 desc_ <- function(x) lazyeval::interp(~desc(var), var = as.name(x)) # or just # desc_ <- function(x) paste0("desc(",x,")") df %>% arrange_(desc_(x)) 
+6
source

Source: https://habr.com/ru/post/1207287/


All Articles