简体   繁体   English

通过矩阵的列查找满足某些条件的值的百分比

[英]Finding the percentage of values that meet some criterion by columns of a matrix

I've created an 8 x 1000 matrix of Exp() variables. 我创建了一个8 x 1000的Exp()变量矩阵。 This represents 1000 iterations (columns) of sampling 8 times from an exponential distribution. 这表示从指数分布中采样8次的1000次迭代(列)。 I am trying to figure out how to get the percentage of values in each column that are less than a critical value. 我试图弄清楚如何获取每列中小于临界值的值的百分比。 So I end up with a vector of 1000 percentages. 所以我最终得到了1000个百分比的向量。 I've tried a couple things but still being relatively new to R I'm having some difficulty. 我已经尝试了几件事,但是对于R还是比较陌生,我遇到了一些困难。

This is my current version of code that doesn't quite work. 这是我当前的代码版本,无法正常运行。 I've used the apply function (without the for loop) when I want the mean or variance of the samples, so I've been trying this approach but this percentage thing seems to require something different. 当我想要样本的均值或方差时,我已经使用了apply函数(没有for循环),因此我一直在尝试这种方法,但是这个百分比似乎需要一些不同的东西。 Any thoughts? 有什么想法吗?

 m=1000
 n=8
 theta=4
 crit=3
 x=rexp(m*n,1/theta)

 Mxs=matrix(x,nrow=n)

 ltcrit=matrix(nrow=m,ncol=1)

 for(i in 1:m){
    lt3=apply(Mxs,2,length(which(Mxs[,i]<crit)/n))
    }

 ltcrit

You can use apply without any for loop and get the answer: 您可以在没有任何for循环的情况下使用apply并获得答案:

percentages = apply(Mxs, 2, function(column) mean(column < crit))

Note the creation of an anonymous function with function(column) mean(column < crit) . 请注意,使用function(column) mean(column < crit)创建一个匿名函数。 You probably used apply(Mxs, 2, mean) when you wanted the means of the columns, or apply(Mxs, 2, var) when you wanted the variance of the columns, but notice that you can put any function you want into that space and it will perform it on each column. 想要使用列的apply(Mxs, 2, mean)apply(Mxs, 2, mean)您可能使用了apply(Mxs, 2, mean) ,或者想要使用列的方差时,则apply(Mxs, 2, var) ,但请注意,您可以在其中添加任何函数空间,它将在每一列上执行。

Also note that mean(column < crit) is a good way to get the percentage of values in column less than crit . 还要注意, mean(column < crit)是使column的值百分比小于crit的好方法。

You can use colMeans : 您可以使用colMeans

colMeans(Mxs<crit)
[1] 0.500 0.750 0.250 0.375 0.375 0.875 ...

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

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