Thank you, @scottbrenstuhl and @jdb, for all of your time on your responses. I completely agree about being more descriptive in my column naming, and so I renamed the columns - and complicated things again haha!
My data frame now looks like,
credName <- c("CFA", "CFA", "MBA", "CFA", "MBA", "CFA", "MBA", "JD", "JD", "JD", "FINRA", "FINRA")
credBiz <- c("Bank", "NA", "Consulting", "NA", "Bank", "Consulting", "Law", "Law", "Law", "Law", "Bank", "Consulting")
credYear <- c(2017, 2016, 2017, 2015, 2016, 2014, 2015, 2017, 2016, 2015, 2016, 2017)
credPercent <- c(0.5, 0.25, 0.75, 0.1, 0.15, 0.20, 0.80, 0.55, 0.75, 0.9, 0.8, 0.2)
credDF <- data.frame(credName, credYear, credBiz, credPercent)
Ultimately, using mutate to create a new column, and then arranging by this new column, solved my initial problem. Thank you, @jdb !
credpipe <- credDF %>%
group_by(credName, credYear) %>%
summarise(percentMean = mean(credPercent, na.rm = TRUE)) %>%
mutate(group_percentMean = mean(percentMean, na.rm = TRUE)) %>%
arrange(desc(group_percentMean), desc(credName), desc(credYear)) %>%
select(-group_percentMean)
Which results in the groups sorted by the group average, as well as by year,
> credpipe
# A tibble: 12 x 3
# Groups: credName [4]
credName credYear percentMean
<fctr> <dbl> <dbl>
1 JD 2017 0.55
2 JD 2016 0.75
3 JD 2015 0.90
4 MBA 2017 0.75
5 MBA 2016 0.15
6 MBA 2015 0.80
7 FINRA 2017 0.20
8 FINRA 2016 0.80
9 CFA 2017 0.50
10 CFA 2016 0.25
11 CFA 2015 0.10
12 CFA 2014 0.20
Next question is how to carry this sorted tibble into my Shiny app. With a function created in a helper file, (the summarise/mutate/arrange piping from above, is the output of this function), I reference the function and assume that the output gets stored in the reactive credpipeInput(). However, when I plot the data, as "p", with renderPlotly(), the data is not in the sorted order from above.
server <- function(input, output) {
credpipeInput <- reactive({
credFunction(credDF,
credName_select,
credBiz_select,
credYear_select)
})
output$credtestplot <- renderPlotly(
p <- credpipeInput() %>%
plot_ly(y = ~percentMean, x = ~credName, color = ~factor(credYear),
type = "bar")
)
}
Happy to hear your thoughts - I can save the helper and app files to GitHub if needed.
Again, many thanks!
Andrew