简体   繁体   English

R在两个地方生成相同的随机数

[英]R generating the same random numbers at two places

I have this code and I want sample(1:3650, 365, replace=T) to generate the same numbers at both instances, but different values for each replication. 我有这段代码,我希望sample(1:3650, 365, replace=T)在两个实例上生成相同的数字,但是每次复制都使用不同的值。 So that for each replication i generate 365 random values and those values are used for both appending for both mydf1allt and mydf2allt, but different 365 values for each replication. 因此,对于每个复制,我都会生成365个随机值,并且这些值都将同时用于mydf1allt和mydf2allt的附加值,但每个复制均使用不同的365个值。 Since there is correlation between them i want to capture that. 由于它们之间存在相关性,因此我想捕捉一下。 This is my attempt at making a function for bivariate bootstrap. 这是我为双变量引导程序创建函数的尝试。 I know how to fix this with a for loop but it takes forever to run, so would be nice it could be made without. 我知道如何使用for循环解决此问题,但它需要永远的时间才能运行,因此可以不使用它就很好了。

listboot1sl = c()
listboot2sl = c()

pairbootstrap2 <- function(y) {

  .GlobalEnv$listboot1sl <-  replicate(10**y, rbind(listboot1sl, max(sum(mydf1allt[,2][sample(1:3650, 365, replace=T)])-17980405,0)))

  .GlobalEnv$listboot2sl <-  replicate(10**y, rbind(listboot2sl, max(sum(mydf2allt[,2][sample(1:3650, 365, replace=T)])-137376627,0)))
}

(mydf2allt is made out of two columns with numbers.) (mydf2allt由带有数字的两列组成。)

This is with a foor loop doing what I want it to do without a foor loop: 这是一个foor循环,而没有foor循环就可以完成我想做的事情:

pairbootstrap2 <- function(y) {

  for (i in 1:10**y){

   z <- sample(1:3650, 365, replace=T)

  .GlobalEnv$listboot1sl <-  rbind(listboot1sl, max(sum(mydf1allt[,2][z])-17980405,0))

  .GlobalEnv$listboot2sl <-  rbind(listboot2sl, max(sum(mydf2allt[,2][z])-137376627,0))

  }

}

I solved it using: 我使用以下方法解决了问题:

mydfboth <- cbind(mydf1allt[,2], mydf2allt[,2])

list <- replicate(10**6, colSums(mydfboth[sample(1:3650, 365, replace=T),]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM