r - 针对 NULL 和其他东西测试变量
问题描述
我想测试某些属性的变量,但是这些变量通常是NULL
.
我试过了:
x = NULL
if (!is.null(x) & names(x) == 'a') {
return(0)
}
但这会返回:
Error in if (!is.null(x) & names(x) == "a") { :
argument is of length zero
有没有办法解决?
我不想写:
if (!is.null(x)) {
if (names(x) == 'a') {
return(0)
}
}
因为这会随着很多else
s 快速增长。
我尝试提出一个测试 ifNULL
以及任意测试的函数,但我在使用范围时遇到了一些问题(我认为):
is.null.test = function(x, test = NULL) {
if (is.null(x)) {
return(FALSE)
} else if (is.null(test)){
return(FALSE)
} else {
eval(parse(text = test))
}
}
test = 'names(x) == "a"'
is.null.test(x = list(shape = 'a'), test = test)
解决方案
如果这是您所要求的,我并不绝对肯定,但这里有一些选择。如果您正在使用列表并且您希望列表中的索引同时满足您的两个条件,您可以尝试以下操作:
my_list <- list(j = c(8:17), b = NULL, a = c(2,8,0), k = NULL)
which(!is.null(my_list) & names(my_list) %in% "a")
[1] 3
如果你真的想return(0)
在你的例子中,你可以试试这个:
ifelse(!is.null(my_list) & names(my_list) %in% "a", 0, NA)
[1] NA NA 0 NA
在这两种情况下,请注意我使用names() %in%
而不是names() ==
. 对于您的示例==
工作正常,但如果您想使用多个名称,%in%
则更好一点。
ifelse(!is.null(my_list) & names(my_list) %in% c("a", "b"), 0, NA)
[1] NA 0 0 NA
which(!is.null(my_list) & names(my_list) %in% c("a", "b"))
[1] 2 3
如果这不是您想要的,请给我更多详细信息,我将编辑我的答案。
推荐阅读
- javascript - 如何根据某些条件更改 Angular 11 中 favIcon 的位置
- c++ - constexpr 函数调用无法编译
- typescript - 你可以根据类型检查一个对象,而不指定它所说的类型吗?
- docker - Python REST POST 处理大型请求
- c - 如何在没有 init_pair 的情况下使用 ncurses color_output?
- javascript - 如何在玩笑中比较innerHTML
- javascript - 快速验证器从控制器调用方法的问题
- azure - Kubernetes ExternalName 指向 Azure SQL Server
- nginx - 100k 事务 nginxs 后抛出错误:(99:无法分配请求的地址)
- sql - Sql中的分组和排序列