我的工作R编程语言。 我在试图建立一个循环,执行以下:
步骤1:保持产生两个随机数字"a"和"b"之前的"a"和"b"大于12
步骤2:轨道如何很多随机数字有可产生直到它采取了步骤1的可完成
步骤3:重复步骤1和2步的100倍
因为我不知道如何保持产生随机数字,直到一个条件被满足,我试图产生大量的随机数字,希望在条件得到满足(有可能是一种更好的方式写这本):
results <- list()
for (i in 1:100){
# do until break
repeat {
# repeat many random numbers
a = rnorm(10000,10,1)
b = rnorm(10000,10,1)
# does any pair meet the requirement
if (any(a > 12 & b > 12)) {
# put it in a data.frame
d_i = data.frame(a,b)
# end repeat
break
}
}
# select all rows until the first time the requirement is met
# it must be met, otherwise the loop would not have ended
d_i <- d_i[1:which(d_i$a > 10 & d_i$b > 10)[1], ]
# prep other variables and only keep last row (i.e. the row where the condition was met)
d_i$index = seq_len(nrow(d_i))
d_i$iteration = as.factor(i)
e_i = d_i[nrow(d_i),]
results[[i]] <- e_i
}
results_df <- do.call(rbind.data.frame, results)
问题: 当我看看结果,我注意到,循环是不正确地考虑到要满足的条件,例如:
head(results_df)
a b index iteration
4 10.29053 10.56263 4 1
5 10.95308 10.32236 5 2
3 10.74808 10.50135 3 3
13 11.87705 10.75067 13 4
1 10.17850 10.58678 1 5
14 10.14741 11.07238 1 6
例如,在每一个这些行两个"a"和"b"小于12.
没有人知道这是为什么发生,并有人可以请告诉我如何来解决这个问题?
谢谢!