Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sort tabyl columns on adorn_totals(c("row")) descending (highest to lowest; left to right) #487

Closed
m31uk3 opened this issue Aug 1, 2022 · 2 comments

Comments

@m31uk3
Copy link

m31uk3 commented Aug 1, 2022

Brief description of the problem

This may just be inexperience but my use of the tabyl function is frequent and I find myself always wanting to have the columns sorted based on the adorn_total values for each column.

diamonds %>% 
  tabyl(clarity, cut) %>% 
  adorn_totals(c("col")) %>%
  arrange(desc(as.numeric(Total))) %>%
  adorn_totals(c("row")) %>%
  #### {INSERT logic to sort columns by adorn_total column "Total"} ####
  adorn_title()
@jzadra
Copy link
Contributor

jzadra commented Aug 6, 2022

The best way I've found to do this is, as is often the case, to go to long and then back to wide:

arrange_cols <- function(.data, key_col) {
  key_col <- sym(key_col)
  
  .data %>% 
    pivot_longer(-!!key_col) %>% 
    mutate(!!key_col := recode(!!key_col, `Total` = "!Total")) %>% 
    group_by(!!key_col) %>% 
    arrange(!!key_col, value) %>% 
    pivot_wider() %>% 
    mutate(!!key_col := recode(!!key_col, `!Total` = "zTotal")) %>% 
    arrange(!!key_col) %>% 
    mutate(!!key_col := recode(!!key_col, `zTotal` = "Total"))
}


diamonds %>% 
  tabyl(clarity, cut) %>% 
  adorn_totals(c("col")) %>%
  arrange(desc(as.numeric(Total))) %>%
  adorn_totals(c("row")) %>% 
  arrange_cols("clarity")

If we want to add this to janitor, we should add a bit more error checking and also allow bare column names in the function call.

@sfirke
Copy link
Owner

sfirke commented Aug 7, 2022

This will be best solved outside of janitor. Here's one I came up based on the first StackOverflow hit from my search. I had to modify that one since in a tabyl, the left-most column is descriptive and should stay on the left. With your example:

x <- diamonds %>% 
  tabyl(clarity, cut) %>% 
  adorn_totals(c("col")) %>%
  arrange(desc(as.numeric(Total))) %>%
  adorn_totals(c("row"))


x[, c(1, order(-x[nrow(x),-1]) + 1)] # the 1s and -1 is to work around the first column being character

The first five StackOverflow hits from this search appeared promising if you want to look into it more: https://www.google.com/search?q=order+columns+based+on+row+values+r

@sfirke sfirke closed this as completed Aug 7, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants