模拟R,for循环

时间:2016-04-29 02:32:40

标签: r for-loop simulation

我试图在R中模拟数据10次但我没有弄清楚如何实现这一点。代码如下所示,您可以直接在R中运行它!当我运行它时,它会给我5个" w"作为输出,我认为这只是一个模拟,但实际上我想要的是5个数字的10种不同的模拟。

我知道我需要为它写一个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

1 个答案:

答案 0 :(得分:2)

您希望在每次模拟中生成新的数据值。在for循环后面的花括号内执行此操作。然后,在关闭大括号之前,请务必将统计输出保存在对象中的适当位置,如矢量。举个简单的例子,

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

请注意,如果要从每个模拟中保存五个值,可以使用矩阵对象而不是矢量对象,如下所示

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
相关问题