简体   繁体   English

双循环随机采样

[英]Double loop with random sampling

I wanted to generate score i (0:36) with frequency j . 我想用频率j生成分数i (0:36) I wanted j loop to be random numbers. 我希望j循环是随机数。 What I did was: 我所做的是:

j<-1:70
for(i in 0:36) {
  for (j in 1:sample(j)) {
    print(i,j)
  }
}

But I got error. 但是我出错了。 Should have I put sample(j,1, replacement=TRUE) instead of just sample(j) ? 我应该把sample(j,1, replacement=TRUE)而不是sample(j)放吗? thank you 谢谢

If I understand correctly, you want each element in i replicated from one to 70 times (randomly choosing the number of times to replicate the value). 如果我理解正确,则希望将i每个元素复制1到70次(随机选择要复制值的次数)。

i <- 0:36
j <- 1:70

#number of times to replicate each i
times <- sample(j, length(i), replace=FALSE)
result <- rep(i, times)

Whether to use replace=FALSE or not depends on how you'd like the sampling done (eg replace=FALSE assures that each j is chosen at most one time. 是否使用replace = FALSE取决于您希望如何进行采样(例如,replace = FALSE确保每个j最多被选择一次。

If you want a random number, you should use runif . 如果您想要一个随机数,则应使用runif It has min/max to control the range. 它具有最小/最大来控制范围。 You can also use sample , but then it's better to use sample.int(max, 1) 您也可以使用sample ,但是最好使用sample.int(max, 1)

j<-70
for(i in 0:36) {
  for (k in 1:runif(1,1,j)) {
    cat(i,k, "\n")
  }
}

Then the inner loop shouldn't overwrite j (which should be a constant) - so I renamed the loop variable to k . 然后,内部循环不应覆盖j (应为常数)-因此我将循环变量重命名为k ...and print doesn't print multiple args like that - but cat does! ...并且print不会那样打印多个args-但是cat可以!

Try 尝试

for(i in 0:36) {
  for(k in 1:sample(70, 1)) {
    print(c(i,k))
  }
}

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

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