简体   繁体   中英

Calculate percentile for every column in a data frame in R

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!

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM