Skip to content

Instantly share code, notes, and snippets.

@tomhopper
Created July 20, 2019 00:01

Revisions

  1. tomhopper renamed this gist Jul 20, 2019. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. tomhopper created this gist Jul 20, 2019.
    26 changes: 26 additions & 0 deletions Sorting variables in tidyverse
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,26 @@
    # Sort a grouping variable by a second numeric variable, in the presence of a faceting variable
    # Ostensibly so that the grouping variable plots in ascending (or descending) order of the
    # central tendency of the numeric variable.

    library(tidyverse)

    # Create a dataset
    set.seed(10001)
    my_df <- tibble(facet_var = rep(letters[1:4], each = 5*10),
    group_var = rep(rep(letters[13:17], each = 10), times = 4),
    group_shift = rep(rep(runif(5, min = 1, max = 5), each = 10), times = 4),
    value = runif(4*5*10, min = 20, max = 40) + group_shift)
    set.seed(NULL)

    # Sort the grouping variable
    # This approach entirely within tidyverse
    my_df <- my_df %>%
    mutate(group_var = as.factor(group_var)) %>%
    group_by(facet_var) %>%
    mutate(group_var = fct_reorder(.f = group_var, .x = value,.fun = median))

    # And plot
    my_df %>%
    ggplot(aes(x = group_var, y = value, color = group_var)) +
    geom_boxplot() +
    facet_wrap(.~facet_var)