按顺序,数字前面是NA

时间:2016-12-16 11:24:28

标签: r

我想创建一个Sieve of Eratosthenes,它非常简单但是当我尝试在正确的位置调用所有值时,就像我在下面seq.int中所做的那样,我收到一条非常奇怪的错误消息,因为prime * 2绝对只是一个数字。

q4 <- function (n) {
  art <- rep (TRUE, n)
  art [1] <- FALSE
  prime <- 2
  for (i in 2:n) {
    if (i^2 > n) {break}
    else {
      art [seq.int (2 * prime, length (art), prime)] <- FALSE
      prime <- min (which (art [prime + 1:length (art)]))
    }
  }
  art
}

q4(20)
Error in seq.int(from = 2 * prime, to = length(art), by = prime) : 
  'from' cannot be NA, NaN or infinite
In addition: Warning message:
In min(which(art[prime + 1:length(art)])) :
  no non-missing arguments to min; returning Inf

我很想知道这个表达式中的哪些内容使R将其称为NA。 谢谢!

1 个答案:

答案 0 :(得分:0)

由于以下问题导致错误,如果art已满FALSE,则prime <- min (which (art [prime + 1:length (art)]))的结果为Inf =&gt; Inf * 2 = Inf == NaN