【问题标题】:Simulation in R, for loopR中的模拟,for循环
【发布时间】:2016-04-29 02:32:39
【问题描述】:

我试图在 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

【问题讨论】:

  • data 是从某个分布中随机抽取的吗?在这种情况下,模拟意味着什么?
  • 这里没有随机的东西。重复只会给你同样的结果。您可以使用 replicate() 重复一段代码(请参阅帮助页面),但要确保其中确实存在一些随机性。
  • 感谢您的回答!我真正想要的是随机数据 10 次,所以每次我都能得到不同的 w 值。我能做到吗?

标签: r for-loop simulation


【解决方案1】:

您需要在每次模拟中生成新的数据值。在 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-30
    • 2019-09-07
    • 2021-03-04
    • 1970-01-01
    • 2021-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多