0

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.

4

1 回答 1

0

如果要获取向量的百分位数(单个值):

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

但这似乎不是你所说的百分位数。如果您想要返回一个观察值在 75% 以内的向量:

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

apply(b, 2, function (x) percentOfVector(x, 0.75))
于 2014-11-14T20:56:17.610 回答