简体   繁体   English

R-函数,矩阵,应用

[英]R - function, matrix, apply

Write your own function that returns the 75th percentile of a vector. 编写自己的函数,该函数返回向量的第75个百分位。 Apply this function to all columns of matrix b. 将此函数应用于矩阵b的所有列。

Here's matrix b: 这是矩阵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. 我想知道是否可以使用apply函数来调整我得到的b向量。 Or should I use a for loop? 还是应该使用for循环?

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. PS:我尝试使用for循环来执行此操作,但是当我尝试将函数的结果存储在矩阵中时,cbind遇到了一些问题。

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: 如果您想要返回的观测值在第75个百分位数之内的向量:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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