1

I am trying to figure out how to use the tidyverse to dynamically arrange a dataframe. I used to use arrange_ but this is now deprecated.

Some more specifics. I need to arrange decending if numeric, ascending if not. I have logic for that built in but I can't figure out how to get this to work with arrange.

some data:

library(tidyverse)
dat <- tibble(`Project ID` = c(rep("Project A", 3), rep("Project B", 3), rep("Project C", 3)),
                  `Summary Col numeric` = c(50, 50, 20, 500, 500, 200, 3000, 1000, 3000),
                  `Summary Col alpha` = c("A", "B", "C", "A", "B", "C", "A", "B", "C"))

some code:

# set the sort order. Should work either way
sortOrder = c("Summary Col alpha", "Summary Col numeric")


# Problem 1. doesn't work with spaces in names (not essential to fix as 
# I can work around with gsub)

names(dat) <- gsub(" ", "_", names(dat))
sortOrder = gsub(" ", "_", sortOrder)

# get the sort correct - numeric is descending, character is ascending
# figure out numeric cols and paste desc
numericSorts <- sapply(dat[sortOrder], is.numeric) 
sortOrder[numericSorts] <- paste0("desc(",sortOrder[numericSorts], ")")


  # Problem 2 - deprecated solution. Essential to fix
  dat %>% 
  dplyr::arrange_(.dots = sortOrder)  

Does anybody have a solution using the tidyverse?

Thanks

user1658170
  • 814
  • 2
  • 14
  • 24

1 Answers1

2

Maybe you can use a solution proposed in this post. We need to use both expression from rlang and execute this code thanks to !! :

dat %>% dplyr::arrange(!!rlang::parse_expr(sortOrder[1]),
                       !!rlang::parse_expr(sortOrder[2]))

Edit 1 This will solve your problem :

dplyr::arrange(!!!rlang::parse_exprs(sortOrder))

Find their.

Rémi Coulaud
  • 1,684
  • 1
  • 8
  • 19