简体   繁体   English

在具有条件的矩阵中查找第 n 个百分位数

[英]Finding nth percentile in a matrix with conditions

I have a matrix measuring 100 rows x 10 columns:我有一个测量 100 行 x 10 列的矩阵:

mat1 = matrix(1:1000, nrow = 100, ncol = 10)

I wish to find the nth percentile of each column using colQuantiles, where the nth percentile is equal to a probability value contained in Probs, except when any of the values in Probs > 0.99 - in which case I want the value of 0.99 applied.我希望使用 colQuantiles 找到每列的第 n 个百分位数,其中第 n 个百分位数等于 Probs 中包含的概率值,除非 Probs 中的任何值> 0.99 - 在这种情况下,我希望应用 0.99 的值。

Probs = c(0.99, 0.95, 1, 1, 0.96, 0.92, 1, 0.98, 0.99, 1)

I have tried the following:我尝试了以下方法:

Res = ifelse(Probs > 0.99, colQuantiles(mat1, Probs = c(0.99)), colQuantiles(mat1, probs = Probs))

But this simply returns the if true part of the above statement for all ten columns of mat1, presumably because there at least one of the values in Probs is > 0.99.但这只是为 mat1 的所有十列返回上述语句的 if true 部分,大概是因为 Probs 中至少有一个值 > 0.99。 How can I adapt the above so it treats each column of mat1 individually according to the probabilities in Probs?如何调整上述内容,以便根据 Probs 中的概率单独处理 mat1 的每一列?

You can use mapply as follows:您可以按如下方式使用mapply

Probs[Probs > 0.99] <- 0.99
unname(mapply(function(x, p) quantile(x, p), 
    split(mat1, rep(1:ncol(mat1), each = nrow(mat1))),
    Probs))

output: output:

[1]  99.01 195.05 299.01 399.01 496.04 592.08 699.01 798.02 899.01 999.01

It splits the matrix into a set of column vectors (see How to convert a matrix to a list of column-vectors in R? ) and then find the nth percentile for each column.它将矩阵拆分为一组列向量(请参阅如何将矩阵转换为 R 中的列向量列表? ),然后找到每列的第 n 个百分位数。

We cannot pass different probability for different columns in colQuantiles but we can get all the probabilities for each column using colQuantiles我们不能为colQuantiles中的不同列传递不同的概率,但我们可以使用colQuantiles获得每列的所有概率

temp <- matrixStats::colQuantiles(mat1, probs = pmin(Probs, 0.99))

and then extract the diagonal of the matrix to get the required probability in each column.然后提取矩阵的对角线以获得每列所需的概率。

diag(temp)
#[1]  99.01 195.05 299.01 399.01 496.04 592.08 699.01 798.02 899.01 999.01

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

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