Domanda

I'm trying to take random samples from UK population projections and store them in a matrix.

At the moment, I'm using the following code

# Read in Data
Year = data.frame(2010, 2011, 2012, 2013, 2014)
Mean_ONS_Population_Growth = data.frame(0.0076, 0.0158, 0.0240, 0.0323, 0.0404)
SD_ONS_Population_Growth = data.frame(0.0003, 0.0015, 0.0029, 0.0045, 0.006193468)

MC_RUNS = 1000 # Specify number of runs

Projected_Population_Growth = array(0,dim=c(49,MC_RUNS,5)) # Specify number of runs

Projected_Population_Growth = rnorm(MC_RUNS,mean=Mean_ONS_Population_Growth,sd=SD_ONS_Population_Growth)

But I'm getting this error:

Error in rnorm(MC_RUNS, mean = Mean_ONS_Population_Growth, sd = SD_ONS_Population_Growth) :
 invalid arguments

Ideally, I would like a matrix with 1000 columns and 5 rows - each row representing a year and each column representing a random chosen Monte Carlo sample.

Thanks for the help.

È stato utile?

Soluzione

mapply(rnorm,mean=Mean_ONS_Population_Growth,sd=SD_ONS_Population_Growth,MoreArgs=list(n=MC_RUNS))

Altri suggerimenti

the function rnorm in R can only handle univariate distributions. I'm not aware of any base package including functions for multivariate distributions but you can check out cran. I personally prefer the package mvtnorm. Included in that package is the function rmvnorm which is basically the multivariate version of rnorm. Though if you want to have independent univariate distributions, you could do an sapply for example like this:

sapply(1:length(Mean_ONS_Population_Growth), 
    function(iMC) {
        rnorm(MC_RUNS, 
            mean=as.numeric(Mean_ONS_Population_Growth[iMC]),
            sd=as.numeric(SD_ONS_Population_Growth[iMC]))
     }
)

One issue you have with your code is, that rnorm takes only numerics as arguments.

class(Mean_ONS_Population_Growth[1])
[1] "data.frame"

Hth, D

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top