Reputation: 113
I have a data set of 3 categorial columns and 40 columns with numerical values. I want to calculate the 90th percentile for each of the 40 numerical columns separetly.
Take this data frame as a reproducible example:
fruit = c("apple","orange","banana","berry") #1st col
ID = c(123,3453,4563,3235) #2nd col
price1 = c(3,5,10,20) #3rd col
price2 = c(5,7,9,2) #4th col
price3 = c(4,1,11,8) #5th col
df = data.frame(fruit,ID,price1,price2,price3) #combine into a dataframe
I want to do something like: calc_percentile = quantile(df[,3:5], probs = 0.90)
The output I'm looking for would be:
# Column 90thPercentile
# price1 17
# price2 8.4
# price3 10.1
Doing this one by one is not practical given that I have 40 columns. Your help is appreciated!
Upvotes: 2
Views: 5412
Reputation: 39858
Using dplyr
and tidyr
:
df %>%
summarise_at(3:5, ~ quantile(., probs = 0.9)) %>%
gather("Column", "90thPercentile")
Column 90thPercentile
1 price1 17.0
2 price2 8.4
3 price3 10.1
Upvotes: 1
Reputation: 73285
stack(lapply(df[3:5], quantile, prob = 0.9, names = FALSE))
# values ind
#1 17.0 price1
#2 8.4 price2
#3 10.1 price3
Upvotes: 3