r - R 中的模拟,for 循环

标签 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

最佳答案

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

关于r - R 中的模拟,for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36928592/

相关文章:

r - 在 R 中使用 map() rowise

r - 使用 kable 在表格下方添加另一个标题

用于重复添加的 Python for 循环

matlab - Web 应用程序、动态图表和模拟工具? (针对 MATLAB 用户)

simulation - 2D 光线追踪

r - ggplot2:如何在主题中设置geom_bar()的默认填充色

r - 2个逻辑向量的元素之间的快速最小距离(间隔)(取2)

检查井字棋中对角线是否获胜

iphone - 迭代充满日期的 NSArray 并与另一个 NSArray 进行比较

c# - 我是如何搞砸 PLINQ 的? (并行化简单/快速计算)