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