Search code examples
rmeanmedian

How to calculate a median and mean of 95 percentile in R


My dataset contains multiple observations (Mean Intensity gfp) for different species (aapl2). Each species has a several number of observations.

I have already grouped observations in groups by species and calculated 95 percentil with:

data2 = aggregate(data$"Mean Intensity gfp" ~ data$aapl2, FUN = quantile, probs = c(0.95)).

But now, I have problem and I don't know how to solve it. I need to calculate a median and mean of calculated 95 percentile , but I really don't know how to do it.

Could somebody help me, please?

Thank you very very much

enter image description here


Solution

  • Using iris... To get the mean/median of those where the value is below the 95th percentile (of its species)

    library(data.table)
    data.table(iris)[, keep := Petal.Length < quantile(Petal.Length, 0.95), 
                       by = Species][
                       keep==TRUE, 
                       .(mean(Petal.Length), median(Petal.Length)), 
                       by = Species]
    

    And using dplyr

    library(dplyr)
    iris %>% 
      group_by(Species) %>%
      filter(Petal.Length < quantile(Petal.Length, 0.95)) %>%
      summarize("mean"=mean(Petal.Length), 
                "med"=median(Petal.Length))