The quantile() function in R used to calculate sample quantiles values from dataset.The quantile are values that divide dataset into equal groups.
The following method shows how you can do it with syntax.
Method: Use quantile() Function
quantile(x, probs = seq(0, 1, 0.25),na.rm=FALSE)
x : name of dataset probs : numeric dataset of probabilities na.rm : used for whether to remove NA values.
The following examples show how to use quantile() function in R.
Apply quantile() Function to Calculate Quantile Values of Dataset
Let’s create numeric dataset to calculate its quantile values:
# Create dataset
data <- c(78,89,85,84,81,79,77,85,85,81,78,89,84,84,81,80)
# Find quantile values
q1 <- quantile(data,probs=seq(0,1,1/4))
# Show quartile values
print(q1)
# Find quintiles values
q2 <- quantile(data,probs=seq(0,1,1/5))
# Show quintiles values
print(q2)
# Find deciles values
q3 <- quantile(data,probs=seq(0,1,1/10))
# Show deciles values
print(q3)
Output:
0% 25% 50% 75% 100%
77.00 79.75 82.50 85.00 89.00
0% 20% 40% 60% 80% 100%
77 79 81 84 85 89
0% 10% 20% 30% 40% 50% 60% 70% 80% 90% 100%
77.0 78.0 79.0 80.5 81.0 82.5 84.0 84.5 85.0 87.0 89.0
Here in the above code we created numeric dataset then we find the quantile values from dataset using quantile() function.
Apply quantile() Function to Calculate Quantile Values of Column of Data Frame
Let’s see how we can apply quantile() function column of data frame:
# Create data frame
df <- data.frame(Pressure=c(12.39,11.25,12.15,13.48,13.78,12.89,12.21,12.58),
Temperature=c(78,89,85,84,81,79,77,85),
Humidity=c(5,7,1,2,7,8,9,4))
# Calculate quartiles for 'Pressure'
q <- quantile(df$Pressure,probs = seq(0, 1, 1/4))
# Show quartile value
print(q)
Output:
0% 25% 50% 75% 100%
11.2500 12.1950 12.4850 13.0375 13.7800
Here in the above code we calculate quartile value for Pressure column of data frame using quantile() function.
Apply quantile() Function to Calculate Quantile Values of Entire Data Frame
You can calculate the quartile value for entire data frame using quantile() function.
# Create data frame
df <- data.frame(Pressure=c(12.39,11.25,12.15,13.48,13.78,12.89,12.21,12.58),
Temperature=c(78,89,85,84,81,79,77,85),
Humidity=c(5,7,1,2,7,8,9,4))
# Calculate quartiles for data frame
q <- sapply(df,function(x) quantile(x,probs=seq(0,1,1/4)))
# Print quartile values
print(q)
Output:
Pressure Temperature Humidity
0% 11.2500 77.00 1.00
25% 12.1950 78.75 3.50
50% 12.4850 82.50 6.00
75% 13.0375 85.00 7.25
100% 13.7800 89.00 9.00
The output shows quartile values for each variable of data frame.
By taking reference of above examples you can calculate quartile values for any dataset.