首页 > 解决方案 > 针对 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)
  }
}

因为这会随着很多elses 快速增长。

我尝试提出一个测试 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)

标签: r

解决方案


如果这是您所要求的,我并不绝对肯定,但这里有一些选择。如果您正在使用列表并且您希望列表中的索引同时满足您的两个条件,您可以尝试以下操作:

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

如果这不是您想要的,请给我更多详细信息,我将编辑我的答案。


推荐阅读