Hi,
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!