如何写多个if语句R

时间:2016-05-04 20:34:29

标签: r if-statement raster r-raster rgdal

我正在使用rgdalraster包处理R中的栅格数据。我想摆脱所有无限,没有值,负值并用零替换它们:

NoNA <- function (x) { 
    x[is.infinite(x) | is.na(x) | is.nan(x) | is.null(x) | is.na(x < 0)] <- 0
}
ndii_noNA <- calc(ndii, NoNA)

然后ndii_noNA只有一个值0.我试过if else语句但是它会引发错误

.calcTest(x[1:5], fun, na.rm, forcefun, forceapply).

有什么方法可以解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

你非常接近,但犯了两个错误:

  1. 您需要在which()的索引中使用x,而不仅仅是真实陈述。否则,您将索引x[TRUE]x[FALSE],这不是您想要的。 which()将返回向量中所有“坏”元素的索引。
  2. 当您使用<-进行作业时,x的本地副本将被更改,而不是已通过的副本。如果您想更改x,则需要使用<<-。也就是说,坚持使用R的功能范例是明智的,在这种范例中,您将对本地副本进行更改,然后使用return(x)返回,而不是更改。
  3. 这是你想要的功能:

    # The "change in place" method (may be considered bad style)
    NoNA <- function(x) {
      x[which(is.infinite(x) | is.na(x) | is.nan(x) | is.null(x) | is.na(x < 0))] <<- 0
    }
    # The functional way (recommended)
    NoNA <- function(x) {
      x[which(is.infinite(x) | is.na(x) | is.nan(x) | is.null(x) | is.na(x < 0))] <- 0
      return(x)
    }
    

答案 1 :(得分:0)

编辑:ifelse()更干净但@ cgmil的答案确实更快。

    x = rep(c(Inf, -Inf, NULL, NaN, NA, 1), 250e3)

    no_na = function(x){

      ifelse(
        is.infinite(x) | is.na(x) | is.nan(x) | is.null(x) | is.na(x < 0), 0, x
      )

    }


NoNA <- function(x) {
  x[which(is.infinite(x) | is.na(x) | is.nan(x) | is.null(x) | is.na(x < 0))] <- 0
  return(x)
}

microbenchmark(
  no_na(x), NoNA(x),
  times = 50
)

# Unit: milliseconds
# expr      min       lq     mean   median       uq      max neval
# no_na(x) 380.9375 399.7520 416.7729 424.5490 429.6005 451.0534    50
# NoNA(x) 242.8555 249.0034 255.8857 251.3694 254.8176 285.1451    50