【问题标题】:lapply needs boolean after if-statement conditionlapply 在 if 语句条件之后需要布尔值
【发布时间】:2014-03-02 22:46:52
【问题描述】:

我是 R 新手。我编写了一个适用于数字的函数,并希望将其应用于长度为 400 的数字。它去

 EGIDS.to.IUCN <- function(x){
   if(x==10){return(NA)} # 10 (Extinct)
   if(x==9){return(NA)} # 9 (Dormant)
   if(x==8.5){return(4)} # 8.5 (Nearly Extinct) → 4 (Critically endangered) 
   # 10 more similar lines here (no more NAs)
   else{stop}
 }  

我尝试使用 lapply 但后来我得到了

> austroIUCN <- lapply(austroEGIDS, EGIDS.to.IUCN)
Error in if (x == 10) { : missing value where TRUE/FALSE needed

austroEGIDS 是从 0 到 10 的 400 个数字的列表。我完全迷路了。为什么在关闭 if 条件后需要一个布尔值?

【问题讨论】:

  • austroEGIDS 是否包含缺失值 (NA)?
  • stop 语句应该做什么?如果不满足其中一个条件,您想要NA 吗?因为如果您删除 stop 它应该可以工作

标签: r function if-statement lapply


【解决方案1】:

如果您使用数字向量并使用向量化语句,效率会更高:

austroIUCN <- unlist(austroEGIDS)
austroIUCN[austroIUCN==10 | austroIUCN==9] <- NA
austroIUCN[austroIUCN==8.5] <- 4
...

每个语句都设置了给定级别的所有条目。

【讨论】:

  • 它工作了,但我不得不颠倒行顺序,因为最初在我的列表中austroIUCN[austroIUCN==4] &lt;- 0.258.5 值转换为4austroIUCN[austroIUCN==8.5] &lt;- 4 将被转换为@ 987654326@.
【解决方案2】:

没有stop 这应该可以工作,

EGIDS.to.IUCN <- function(x) {
    if (is.na(x)){ NA } else
        if (x == 10) { NA } else
            if (x == 9) { NA } else
                if(x == 8.5) { 4 } else
                    NA
}

或者,更具可读性和更快,

EGIDS.to.IUCN <- function(x){
    switch (x, 'NA'=NA, '10'=NA, '9'=NA, '8.5'=4, NA)
}

austroEGIDS <- sample(seq(1, 10, .5), 400, replace = TRUE)
austroIUCN <- sapply(austroEGIDS, EGIDS.to.IUCN)
table(unlist(austroIUCN), useNA = "ifany")

austroIUCN
   4 <NA> 
  23  377 

或者如果您希望它停止并在不匹配时抛出错误,

EGIDS.to.IUCN <- function(x){
    switch (x, 'NA'=NA, '10'=NA, '9'=NA, '8.5'=4, stop("Not a match!"))
}

【讨论】:

  • 当我将您的函数与您的示例数据一起使用时,它可以工作。但是,当我将您的函数与我的数据一起使用时,它不会 - 我的列表中有一些 NA,但没有其他异常。此外,当我对您的示例数据使用我的旧函数(少停止)时,我得到了同样的错误。
  • 它有效,但我使用 Karsten 的代码将其转换为数字,因为我无法将列表强制转换为一个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-01
  • 2013-03-26
  • 1970-01-01
  • 2018-04-17
  • 2014-08-19
相关资源
最近更新 更多