 # Calculate the maximum density of a numeric variable grouped by 2 categorical variables

Hi everyone,

I have created a function that calculates the maximum in a density plot grouped by 1 categorical variable.

``````library(dplyr)
library(ggplot2)
library(purrr)

max_density <- function(data, num_var, group_var1) {

data %>%
group_split( {{group_var1}}) %>%
map(~select(., density_var = {{num_var}} )) %>%
map(~pull(., .data\$density_var)) %>%
map(~stats::density(., na.rm = TRUE)[]) %>%
map_dbl(~max(.)) %>%
max()
}

max_density(penguins, body_mass_g, sex)

ggplot(filter(penguins, !is.na(sex))) +
geom_density(aes(body_mass_g, col = sex, fill = sex), alpha = 0.1) +
scale_y_continuous(labels = scales::comma)
``````

Now I would like to come up with a function to calculate the maximum density where there are 2 grouping variables.

I am not sure how to do this, as it requires calculating the density of each sex/species group and then summing each of sex value groups - and then find of the max of these.

This can be visualised by the graph below.

``````ggplot(filter(penguins, !is.na(sex))) +
geom_density(aes(body_mass_g, col = sex, fill = sex), alpha = 0.1) +
scale_y_continuous(labels = scales::comma) +
facet_wrap(~species)
``````

Any help appreciated Thanks!
David

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.