r - 如何在循环中调用种子向量,每次循环运行时将结果保存在彼此旁边?
问题描述
我有两个问题:
- 我正在做一个模拟,我编写了必要的函数,并且我正在使用以下代码在循环中生成我需要的东西:
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 值!
- 另一个问题是,我希望将最终结果保存并彼此相邻打印,以便我可以比较它们。简单来说,我正在生成 5 个不同的数据集,所以我在“结果”中确定了 5 行元素!
有谁有想法吗?
解决方案
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
推荐阅读
- c# - 关闭用户绘制的圆
- vb.net - 加载时的公共变量(vb.net)
- visual-studio - 无法在 Linux 上的 Visual Studio Code 中打开“strlen.S”错误
- python - Painting QGraphicsPixmapItem border on hover
- xcode - 为什么 Xcode 10.2.1 的字体和颜色与 Xcode 9 不同?
- json - 后端只接受纯文本,不接受 JSON,只接受名称而不是 id
- regex - 用于捕获部分结构化字符串的正则表达式
- php - Laravel 中的动态轮播不工作只显示一张图像
- linux - 如何根据powershell中的变量在gcc6和gcc8之间切换
- algorithm - 以最低成本遍历无向加权图的 k 个节点(并返回原点)的算法