R - function, matrix, apply

297 views Asked by At

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.

1

There are 1 answers

0
sebpardo On BEST ANSWER

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))