首页 > 解决方案 > 如何在循环中调用种子向量,每次循环运行时将结果保存在彼此旁边?

问题描述

我有两个问题:

  1. 我正在做一个模拟,我编写了必要的函数,并且我正在使用以下代码在循环中生成我需要的东西:
sim_seeds<- as.vector(sample(1:30000, 5, replace = FALSE), mode = "numeric")
save(sim_seeds,file = "~/Desktop/untitled folder/sim_seeds.Rda")
load(file = "~/Desktop/untitled folder/sim_seeds.Rda")

for (i in 1:5) {

load(file = "~/Desktop/untitled folder/sim_seeds.Rda")

seeds=set.seed(sim_seeds[i])

#Generating data using functions had been wrote before

data<-generate_data(seed =seeds )

Y_1<- mean(data$Y)

#estimation

weights<-generate_weights(T1=S1~Year+growth, T2=R1~Age+Sex+HIV, data=data)
w<-weights$w
g<-g_est(data=data)
p1<-g$p1
Q<-Q_est(data=data,w , p1)
mu1_Q<-Q$mu1


#Results
results <- rbind(seeds,Y_1,mu1_Q)
results
}

我的问题是关于种子的!我想要做的是生成 5 个不同的数据集,但是每次“for”运行时我都需要一个单独的种子,所以我想创建一个种子向量,然后在每次循环运行时调用第 i 个值,但是当我想在循环中调用它时,它会给出一个 NULL 值!

  1. 另一个问题是,我希望将最终结果保存并彼此相邻打印,以便我可以比较它们。简单来说,我正在生成 5 个不同的数据集,所以我在“结果”中确定了 5 行元素!

有谁有想法吗?

标签: rloopsstatisticssimulationrandom-seed

解决方案


1.:一开始就设置一个种子,足以在每次循环迭代时得到不同的结果。编辑用下面的例子来说明它

2.:例如:

set.seed(123)
seeds = 1:5
results = c()
for (i in 1:5){
  set.seed(1) #this is wrong, produces the same set of values at each loop iteration
  # set.seed(seeds[i]) # works, but is unecessary, setting one seed at the beginning is ok
  # commenting the two lines above is fine, and will generate 5 different vectors of random numbers. 
  x = rnorm(5,0,1)
  results = rbind(results, x)
}
results


推荐阅读