r - 用 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)
解决方案
听起来您正在寻找大致如下的功能:
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))
这就足够了,您不需要== TRUE
if 子句中的内容。
推荐阅读
- logging - Quarkus 记录到 json 在 openshift okd 版本 3.11 中不起作用
- python - Xpath for ElementTree Reference to XML with Namespace for UK Statute Metadata
- python - Python:编写相当复杂的代码作为列表理解
- sql - 根据sql中的日期拆分记录
- list - 使用列表中的字符串和路由
- c# - 在同一线程 NUnit 中运行所有测试
- php - 在 WordPress 的 Elementor Form 中显示自定义 PHP 代码的动态下拉列表
- vue.js - 更改 vue2leaflet 中脚本的 src
- onnx - 将 onnx 转换为 tensorrt 模型时找不到 ScatterND 插件
- javascript - next-i18next - 是否可以动态更改默认语言?