我想测试某些属性的变量,但是这些变量通常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
而快速增长。
我尝试想出一个函数来测试是否NULL
以及任意测试,但我在作用域方面遇到了一些问题(我认为(:
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
如果这不是您要找的,请给我更多细节,我会编辑我的答案。