Double loop with random sampling
I wanted to generate score i (0:36) with frequency j. I wanted j loop to be random numbers. 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开发者_StackOverflow)?
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 <- 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 (e.g. replace=FALSE assures that each j is chosen at most one time.
If you want a random number, you should use 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) 
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.
...and print doesn't print multiple args like that - but cat does!
Try
for(i in 0:36) {
  for(k in 1:sample(70, 1)) {
    print(c(i,k))
  }
}
 加载中,请稍侯......
      
精彩评论