Home > Software design >  Apply a ggplot2 function to a data frame to compute kernel density estimate
Apply a ggplot2 function to a data frame to compute kernel density estimate

Time:01-20

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.

CodePudding user response:

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

  • Related