【问题标题】:How to write multiple if statement R如何编写多个if语句R
【发布时间】:2016-08-30 11:15:19
【问题描述】:

我正在使用 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).

有没有办法解决这个问题?

【问题讨论】:

  • 你需要{x[stuff] &lt;- 0; x},你当前正在返回分配的值,而不是对象x
  • 操作后需要返回x向量。
  • 你可以x &lt;- c(1, NA, NaN, -2, 0, 1); x[!is.finite(x) | x &lt; 0] &lt;- 0; x

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


【解决方案1】:

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

  1. 你需要在x的索引中使用which(),而不仅仅是真话。否则,您将索引x[TRUE]x[FALSE],这不是您想要的。 which() 将返回向量中所有“坏”元素的索引。
  2. 当您使用&lt;- 进行分配时,x 的本地副本将被更改,而不是通过的那个。如果要原地更改x,则需要使用&lt;&lt;-。也就是说,您最好坚持 R 的功能范式,在这种范式中,您将对本地副本进行更改,然后使用 return(x) 将其返回,而不是原地更改。

这是你想要的功能:

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

【讨论】:

    【解决方案2】:

    编辑: 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
    

    【讨论】:

      猜你喜欢
      • 2010-10-29
      • 1970-01-01
      • 1970-01-01
      • 2022-11-29
      • 1970-01-01
      • 2016-06-28
      • 1970-01-01
      • 1970-01-01
      • 2021-10-13
      相关资源
      最近更新 更多