R:逻辑条件不受尊重 [英] R: Logical Conditions Not Being Respected

查看:20
本文介绍了R:逻辑条件不受尊重的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用R编程语言。我正在尝试构建一个执行以下操作的循环:

  • 第一步:继续生成两个随机数,直到两个随机数都大于12

  • 第二步:跟踪在第一步完成之前需要生成多少随机数

  • 步骤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&q;和&q;b&q;都小于12。

有人知道为什么会发生这种情况吗?有人能告诉我如何解决此问题吗?

谢谢!

推荐答案

这边怎么样?当您标记while-loop时,我尝试使用它。

res <- matrix(0, nrow = 0, ncol = 3)    

for (j in 1:100){
  a <- rnorm(1, 10, 1)
  b <- rnorm(1, 10, 1)
  i <- 1
  while(a < 12 | b < 12) {
    a <- rnorm(1, 10, 1)
    b <- rnorm(1, 10, 1)
    i <- i + 1
  }
  x <- c(a,b,i)
  res <- rbind(res, x)
}

head(res)
      [,1]     [,2] [,3]
x 12.14232 12.08977  399
x 12.27158 12.01319 1695
x 12.57345 12.42135  302
x 12.07494 12.64841  600
x 12.03210 12.07949   82
x 12.34006 12.00365  782

dim(res)
[1] 100   3

这篇关于R:逻辑条件不受尊重的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆