Calculating 5th, 15th... etc percentile in R

Viewed 21

I'm a little new to R and was hoping to get some insight about how to calculate for any percentile, for example 5th, 15th , etc...

The data I'm working with has two columns:

  • salary: (datatype is numeric / double)
  • student (set up as factor / integer, but only has yes/no)

I've already used:

favstats(salary~student, data=Default, na.rm=TRUE)

to get the two rows of stats broken down by whether they're a student or not; however, I'm not sure how to have the output show me a percentile of my choosing.

Would love to know the simplest way to go on about this in R Studio.

Thank you!

1 Answers

The quantile() function in base r does this.

x <- rnorm(100)
percentiles <- c(0.05, 0.15)

quantile(x, percentiles)
#>        5%       15% 
#> -1.593506 -1.120130

If you need to produce a more complex summary table, you can do something with {tidyverse} like this:

library(tidyverse)
n <- 50
d <- tibble(student = rep(c(T, F), each = n),
            salary = c(rnorm(n, 75, 10), rnorm(n, 95, 15)))

d %>% 
  group_by(student) %>% 
  summarize(quantile_salary = quantile(salary, percentiles))
#> # A tibble: 4 × 2
#> # Groups:   student [2]
#>   student quantile_salary
#>   <lgl>             <dbl>
#> 1 FALSE              70.0
#> 2 FALSE              78.5
#> 3 TRUE               57.3
#> 4 TRUE               64.0

Created on 2022-09-22 by the reprex package (v2.0.1)

Related