R中的奇怪错误

时间:2013-12-12 11:09:51

标签: r

出于某种原因,每当我运行我的函数时,我的代码中的if语句在R中会产生一些奇怪的错误:

Error in if (P > 0) { : missing value where TRUE/FALSE needed

如果B是单位矩阵,则我的函数应该返回对称正半定矩阵A的最小特征值。我使用

测试了我的功能
set.seed(12345)
a <- crossprod(matrix (rnorm(40), 10 ,4)) / 10
b <- diag(1, 4, 4)

它确实产生了正确答案(我使用特征函数检查了。)

无论如何,我需要将theta设置为最小化某个函数的值。对于我使用的例子,该值是(-Q - sqrt(under.sqrt))/(2 * P),但一般来说它取决于P的符号。为什么我的if语句给我这样的错误?我被困在这里一段时间了。任何帮助,将不胜感激。

myFunction <- function(A, B, eps = 1e-6, itmax = 100, verbose = FALSE) {

  n <- nrow(A)
  m <- ncol(A)
  x <- rep (1, n)
  u <- A %*% x
  v <- B %*% x
  r <- t(u) %*% x
  s <- t(v) %*% x
  y <- r / s

  itel <- 1

  repeat {
    tmax <- 0

    for(j in 1:m) {
      P <- (u[j] * B[j, j]) - (v[j] * A[j, j])
      Q <- (r * B[j, j]) - (s * A[j, j])
      R <- (r * v[j]) - (s * u[j])

      under.sqrt <- Q^2 - 4 * P * R

      # Error right here
      if (P > 0) {
        theta <- (-Q + sqrt(under.sqrt)) / (2 * P)
      }

      else {
        theta <- (-Q - sqrt(under.sqrt)) / (2 * P)
      }


      x[j] <- x[j] + theta
      r <- r + 2 * theta * u[j] + A[j, j] * theta * theta
      s <- s + 2 * theta * v[j] + B[j, j] * theta * theta
      u <- u + theta * A[ ,j]
      v <- v + theta * B[, j]

      y <- r / s

      tmax <- max(tmax, abs(theta))
    }

      if ((tmax < eps) || (itel == itmax)) {
        break()
      }

      itel <- itel + 1  

  }

  return(y)
}

4 个答案:

答案 0 :(得分:4)

你算法不稳定。使用options(error=recover),您可以浏览出错的函数:

Browse[1]> P
[1] NaN
Browse[1]> theta
     [,1]
[1,]  Inf

在这里,您可以看到PNaN,这是由theta引发无限值引起的。这会反映到xuv和最终P,并使比较失败。

答案 1 :(得分:2)

这是我的赌注:P是NA

> if(NA > 0){}
Error in if (NA > 0) { : missing value where TRUE/FALSE needed

P呈现NaN:

> if(NaN > 0){}
Error in if (NaN > 0) { : missing value where TRUE/FALSE needed

关于P是向量的猜测:

> if(1:2 > 0){}
NULL
Warning message:
In if (1:2 > 0) { :
  the condition has length > 1 and only the first element will be used

答案 2 :(得分:0)

您确定P是单个值吗?即,不是长度的矢量&gt; 1?

答案 3 :(得分:0)

尝试ifelse

theta <- ifelse(P > 0,
                (-Q + sqrt(under.sqrt)) / (2 * P),
                (-Q - sqrt(under.sqrt)) / (2 * P))

ifelse可以处理NA比较:

ifelse(NA>0,print("x"),print("y"))
[1] NA

if(NA>0) print("x") else print("y")
Error in if (NA > 0) print("x") else print("y") : 
  missing value where TRUE/FALSE needed