Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Apply a ggplot2 function to a data frame to compute kernel density estimate

I’m able to use the group_modify function to apply the ggplot2:::compute_density function to a grouped dataframe however I’m unable to get it to work for an ungrouped data frame

Here’s a simple example:

mtcars %>% group_by(cyl) %>% group_modify(~ggplot2:::compute_density(.x$am, NULL))

How can this be modified to be computed on an un-grouped data frame? I’ve tried using mutate but I understand that compute_density returns additional columns so mutate is not the right approach.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can simply use summarise:

library(tidyverse)

mtcars %>% summarise(ggplot2:::compute_density(am, NULL)) %>% as_tibble()
#> # A tibble: 512 x 6
#>         x density scaled ndensity count     n
#>     <dbl>   <dbl>  <dbl>    <dbl> <dbl> <int>
#>  1 -0.674  0.0118 0.0112   0.0112 0.379    32
#>  2 -0.669  0.0126 0.0119   0.0119 0.403    32
#>  3 -0.664  0.0134 0.0127   0.0127 0.428    32
#>  4 -0.660  0.0142 0.0135   0.0135 0.455    32
#>  5 -0.655  0.0151 0.0143   0.0143 0.482    32
#>  6 -0.651  0.0160 0.0152   0.0152 0.512    32
#>  7 -0.646  0.0170 0.0161   0.0161 0.543    32
#>  8 -0.641  0.0180 0.0171   0.0171 0.576    32
#>  9 -0.637  0.0191 0.0181   0.0181 0.610    32
#> 10 -0.632  0.0202 0.0191   0.0191 0.646    32
#> # ... with 502 more rows

Created on 2023-01-19 with reprex v2.0.2

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading