In R, for a school project, I am trying to turn a function that uses a for loop to a function that uses the apply function.
My function simulates a Poisson distribution where the person can enter the parameters n, lambda and m. m is the number of simulations. It then outputs the mean of all of the means of the m Poisson simulations and outputs a 2x2 grid of box plots so the user can show multiple plots with different parameter values. It is posted below.
I struggling to figure out how to turn this into a function that uses the apply function. As apply needs a matrix, would I need to already have a matrix m.out for certain parameter values from my for loop function. Also, I am not sure exactly what the function would be using apply. I would want to take the mean of every value in the matrix.
Any help is appreciated.
Venom<-function(n,l,m){
if(!is.numeric(c(n,l,m))){return("Error non-numeric value entered for at `enter code here`least one parameter")}
m.out<-NULL
for(i in 1:m){
data1<-rpois(n,l)
m.sim<-mean(data1)
m.out<-rbind(m.out, m.sim)
}
finalmean<-mean(m.out)
hist(m.out, main=paste("Poisson n=",n))
return(c(finalmean, m.out))
}
par(mfrow=c(2,2))