Code for Monte Carlo simulation: generate samples of given size in R

前端 未结 3 1058
借酒劲吻你
借酒劲吻你 2021-02-06 18:02

I started by generating a sample of 500 uniformly-distributed random numbers between 0 and 1 using the code below:

set.seed(1234)
X<-runif(500, min=0, max=1)
         


        
3条回答
  •  耶瑟儿~
    2021-02-06 18:30

    I guess the answer I would give would really depend on if you want to learn to pseudocode or if you want to learn the "R" ish way of doing it. This answer is what I would recommend for somebody who wanted to learn how to work with R.

    First I would make a matrix with N columns and 10000 rows. R appreciates it when we make the space ahead of time for the numbers to go into.

    X=matrix(NA,nrow=10000,ncol=500)

    You know how to generate the 500 random variables for one row.

    runif(500,0,1)

    Now you need to figure out how to get that to happen 10000 times and assign each one to X. Maybe a for loop would work.

    for(i in 1:10000) X[i,]=runif(500,0,1)

    Then you need to figure out how to get the summaries of each row. One function that may help is rowMeans(). Look at its help page and then try to get the mean of each row of your table X

    to get the means of each iteration

    rowMeans(X)

    then to get an idea of what these numbers are like I might be inclined to

    plot(rowMeans(X))

    enter image description here

提交回复
热议问题