简体   繁体   English

R中的模拟,for循环

[英]Simulation in R, for loop

I am trying to simulate the data for 10 times in R but I did not figure out how to achieve that.我试图在 R 中模拟数据 10 次,但我不知道如何实现。 The code is shown below, you could run it in R straightway!代码如下所示,你可以直接在R中运行它! When I run it, it will give me 5 numbers of "w" as output, I think this is only one simulation, but actually what I want is 10 different simulations of that 5 numbers.当我运行它时,它会给我 5 个“w”数字作为输出,我认为这只是一个模拟,但实际上我想要的是这 5 个数字的 10 个不同模拟。

I know I will need to write a for loop for it but I did not get that, could anyone help please?我知道我需要为它写一个 for 循环,但我没有得到,有人可以帮忙吗?

# simulate 10 times

# try N = 10, for loop?
# initial values w0 and E

w0=1000
E= 1000
data = c(-0.02343731, 0.045509474 ,0.076144158,0.09234636,0.0398257)
constant = exp(cumsum(data))
exp.cum = cumsum(1/constant)
w=constant*(W0 - exp.cum)- E
w

You'll want to generate new values of data in each simulation.您需要在每次模拟中生成新的数据值。 Do this within the curly brackets that follow the for loop.在 for 循环后面的大括号内执行此操作。 Then, before closing the curly brackets, be sure to save your statistical output in the appropriate position in a object, like a vector.然后,在关闭大括号之前,请确保将您的统计输出保存在对象中的适当位置,例如向量。 For a simple example,举个简单的例子,

W0=1000
E= 1000
n_per_sim <- 5
num_sims <- 10

set.seed(12345) #seed is necessay for reproducibility
sim_output_1 <- rep(NA, times = num_sims) #This creates a vector of 10 NA values

for (sim_number in 1:num_sims){ #this starts your for loop
data <- rnorm(n=n_per_sim, mean=10, sd=2) #generate your data
average <- mean(data)
sim_output_1[sim_number] <- average #this is where you store your output for each simulation
}
sim_output_1 #Now you can see the average from each simulation

Note that if you want to save five values from each simulation, you can make use a matrix object instead of a vector object, as shown here请注意,如果您想从每次模拟中保存五个值,您可以使用矩阵对象而不是矢量对象,如下所示

matrix_output <- matrix(NA, ncol=n_per_sim, nrow=num_sims) #This creates a 10x5 matrix

for (sim_number in 1:num_sims){ #this starts your for loop
  data <- rnorm(n=n_per_sim, mean=10, sd=2) #generate your data

  constant = exp(cumsum(data))
  exp.cum = cumsum(1/constant)
  w=constant*(W0 - exp.cum)- E
  matrix_output[sim_number, ] <- w #this is where you store your output for each simulation
}
matrix_output #Now you can see the average from each simulation

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

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