I would like to write a function that can arrange a dataframe by several columns, some in an ascending way, some others in a descending way. I am using dplyr::arrange() and !!!rlang::syms() to do so, but this is not working.
Here what I need to get without a function:
# Library
library(tidyverse)
# Original tibble
tbl_mtcars <- mtcars
# Without a function
tbl_mtcars_arrange_0 <-
tbl_mtcars %>%
dplyr::arrange(cyl ,desc(disp) ,hp)
It is working when I do not specify anything for the descending colums:
# With a function
func_arrange <- function(tbl ,arrangeby) {
obj <-
tbl %>%
dplyr::arrange(!!!rlang::syms(arrangeby))
return(obj)
}
## Working
tbl_mtcars_arrange_1 <- func_arrange(
tbl = tbl_mtcars
,arrangeby = c("cyl" ,"disp" ,"hp")
)
But not when I want to arrange by a descending colum:
## Not working
tbl_mtcars_arrange_2 <- func_arrange(
tbl = tbl_mtcars
,arrangeby = c("cyl" ,desc("disp") ,"hp")
)
Error in `dplyr::arrange()`:
! Problem with the implicit `transmute()` step.
x Problem while computing `..1 = c("cyl", "disp")`.
x `..1` must be size 32 or 1, not 2.
I'm using !!!rlang::syms() and not {{}} because {{}} is not working when I want to arrange by several columns (and I don't know why, it's working for dplyr::select() and dplyr::filter() for example).
Could you help me understand what's wrong in my code and how to solve it? Thank you very much!
Still I am currently learning about the ... syntax and do not understand everything yet. I am wondering for example how it could work if I compute a more complex function with more statements (like dplyr::select() for example) and how it would work if I need to use the ... with other statements but with different columns.
Every element should be put between quotes though, otherwise it's nor working ("desc(col)" instead of desc("col")):
## Carefull to put also the "desc()" part between quotes
## Not working if not
test_2 <- func_arrange(
tbl = mtcars
,arrangeby = c("cyl" ,desc("disp") ,"hp")
)
comp_0_2 <- dplyr::all_equal(
test_0
,test_2
,ignore_col_order = FALSE
,ignore_row_order = FALSE
)
print(comp_0_2)