简体   繁体   中英

R - function, matrix, apply

Write your own function that returns the 75th percentile of a vector. Apply this function to all columns of matrix b.

Here's matrix b:

b = matrix(runif(1000*18, min=1000, max=10000), 1000, 18)

And here's the function I've created using indexing.

percentileOfAVector <- function(vector,percentile){
    adjustedVector=vector[0:floor(percentile * length(vector))]
    return (adjustedVector)
}

I was wondering if I can use the apply function to adjust the b vector that I've got. Or should I use a for loop?

PS: I tried to do it with a for loop but I had some problems with cbind when I was trying to store the results of my function in a matrix.

Any help would be greatly appreciated.

If you want to get the percentile of a vector (single value):

apply(b, 2, function (x) quantile(x, prob=0.75))

But it seems this isn't what you mean with percentile. If what you want is to return a vector with the observations that fall within the 75th percentile:

percentOfVector <- function(vector, percentile) {
    perc <- quantile(vector, prob=percentile)
    vector[which(vector <= perc)]
}

apply(b, 2, function (x) percentOfVector(x, 0.75))

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