简体   繁体   English

如何编写多个if语句R

[英]How to write multiple if statement R

I am manipulating raster data in R with the rgdal and raster packages.我正在使用rgdalraster包在 R 中操作光栅数据。 I want to get rid of all infinite, no values, negative values and replace them with zero:我想摆脱所有无限、无值、负值并用零替换它们:

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)

Then the ndii_noNA have only a value of 0. I tried if else statement but it raises an error in然后ndii_noNA的值只有 0。我试过 if else 语句,但它引发了一个错误

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

Is there any way to solve this?有没有办法解决这个问题?

You are very close, but have made two errors:你非常接近,但犯了两个错误:

  1. You need to use which() in the index of x , rather than just the truth statement.您需要在x的索引中使用which() ,而不仅仅是真相陈述。 Otherwise, you will index either x[TRUE] or x[FALSE] , which is not what you want.否则,您将索引x[TRUE]x[FALSE] ,这不是您想要的。 which() will return the indices of all "bad" elements in your vector. which()将返回向量中所有“坏”元素的索引。
  2. When you make the assignment with <- , the local copy of x will be changed, not the one that was passed.当您使用<-进行分配时, x的本地副本将被更改,而不是通过的副本。 If you want to change x in place, you need to use <<- .如果要原地更改x ,则需要使用<<- That said, you would be wise to stick to R's functional paradigm, in which you would make the change to the local copy, then return it with return(x) , rather than change in place.也就是说,您最好坚持 R 的功能范式,在这种范式中,您将对本地副本进行更改,然后使用return(x)返回它,而不是原地更改。

Here is the function you want:这是你想要的功能:

# 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)
}

Edit: ifelse() is cleaner but the @cgmil's answer is indeed faster.编辑: 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM