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

How to call a vector of seeds in a loop, save the results next to eachother each time the loop runs?

我有两个问题:

  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 行!

有人知道吗?

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

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