To calculate quantiles by group in R, you can use quantile() function from dplyr package.

The following method shows how you can do it with syntax.

Method: Use quantile() Function

library(dplyr)

df %>%
group_by(column1) %>%
summarize(quant25 = quantile(column2, 0.25,
quant50 = quantile(column2, 0.50),
quant75 = quantile(column2, 0.75),
quant100 = quantile(column2, 1.0))


The following example shows how to calculate quantile values by group in R.

Using quantile() Function

Let’s see how we can calculate quantile values of column of of data frame:

# Load library
library(dplyr)

# Create data frame
df <- data.frame(Machine_name=c("A","B","A","C","D","B","C","D","D","C","A","B","B","C","D","D"),
Pressure=c(12.39,11.25,12.15,13.48,13.78,12.89,12.21,12.58,11.25,11.69,78.96,14.52,14.56,11.23,12.36,12.85),
Temperature=c(78,89,85,84,81,79,77,85,77,78,75,74,71,79,76,78),
Humidity=c(5,7,1,2,7,8,9,4,5,1,3,4,7,8,9,5))

# Define quantiles of interest
q = c(.25, .5, .75, 1)

# Calculate quantiles by grouping Machine_name
df %>%
group_by(Machine_name) %>%
summarize(quant25 = quantile(Pressure, probs = q[1]),
quant50 = quantile(Pressure, probs = q[2]),
quant75 = quantile(Pressure, probs = q[3]),
quant100 = quantile(Pressure, probs = q[4]))


Output:

 Machine_name quant25 quant50 quant75 quant100
<chr>          <dbl>   <dbl>   <dbl>    <dbl>
1 A               12.3    12.4    45.7     79.0
2 B               12.5    13.7    14.5     14.6
3 C               11.6    12.0    12.5     13.5
4 D               12.4    12.6    12.8     13.8


The output shows quantile values for Pressure column which group by Machine_name column of data frame.