Reputation: 837
I've created an 8 x 1000 matrix of Exp() variables. This represents 1000 iterations (columns) of sampling 8 times from an exponential distribution. 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. I've tried a couple things but still being relatively new to R I'm having some difficulty.
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. 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
Upvotes: 3
Views: 1409
Reputation: 66814
You can use colMeans
:
colMeans(Mxs < crit)
[1] 0.500 0.750 0.250 0.375 0.375 0.875 ...
Upvotes: 5
Reputation: 78590
You can use apply
without any for loop and get the answer:
percentages = apply(Mxs, 2, function(column) mean(column < crit))
Note the creation of an anonymous function with 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.
Also note that mean(column < crit)
is a good way to get the percentage of values in column
less than crit
.
Upvotes: 5