I want to write a R function that give me the value on 10th percentile of observations. I want to use this function with sapply
. Like for mean
, sapply
is
sapply(1 : n, function(i) mean(a1))
Say eg I have 100 values and 10th percentile of 100 is 10 i want that the value that is on 10th line get printed.
X
45
80
70
56
78
78
56
90
35
190
.......... up till 100 values
Desired output: print value on 10th line ie 190 in the above column
I want the function to calculate first 10th percentile of my 100 observations and later just print the value that come on that position.
The desired function will look like:
give_quant_value <- function(vec, quantile) {
return(vec[quantile(1:length(vec),p=quantile,type=1)])
}
where
- vec
is vector of interest
- quantile
is quantile of interest
Proof:
set.seed(42)
a1 <- rnorm(100)
give_quant_value(a1, 0.1)
-0.062714099052421
You may read more about quantile
function while typing ?quantile
in your terminal
Here is a simple function I wrote: It takes on data as a data.frame
object.
select_percentile<-function(df,n){
df<-df
nth<-(n/nrow(df))*100
return(df[nth,])
}
Using data from another answer:
set.seed(42)
a1 <- rnorm(100)
df1<-as.data.frame(a1)
select_percentile(df1,10)
Result:
#[1] -0.0627141
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.