首页 > 解决方案 > 用 NA 替换数值

问题描述

我正在编写一个函数,该函数接受一些向量并检查它是否为数字。如果为假,它将在 else 语句中将数值替换为 NA。我尝试过以多种方式使用 is.numeric() 函数,但运气不佳。任何帮助,将不胜感激!

test <- function(x){


if(is.numeric(x) == TRUE){
  mean.x <- mean(x)
  vectorlist <- list(mean.x)
  }
else

return(vectorlist)
}
x <- c("a", 1, 2)
test(x)

标签: r

解决方案


听起来您正在寻找大致如下的功能:

test <- function(x){
    if(is.numeric(x)){
        return(mean(x))
    }
    else{
        x[!is.na(as.numeric(x))] <- NA
        return(x)
    }
}
x <- c("a", 1, 2)
test(x)

请注意,if (is.numeric(x))这就足够了,您不需要== TRUEif 子句中的内容。


推荐阅读