测试列表的元素是否存在,没有命名索引

时间:2013-10-07 05:35:43

标签: r list

如果您的列表中包含names,则可以查看this question是否存在列表元素:

foo <- list(a=1)
"a" %in% names(list)  # TRUE
"b" %in% names(list)  # FALSE

但是,不清楚是否或如何将其扩展到未命名的列表:

foo <- list(1)
names(list)    # NULL

我可以使用tryCatch对此进行测试,但不是特别优雅:

indexExists <- function(list, index) {
  tryCatch({
    list[[index]]  # Efficiency if element does exist and is large??
    TRUE
  }, error = function(e) {
    FALSE
  })
}

有没有更好的方法来解决这个问题?

1 个答案:

答案 0 :(得分:0)

Hong Ooi的答案适用于一个维度,但我想我会添加一个适用于多维索引的答案。

indexExists <- function(ind, form) {
    if (ind[[1]] > length(form) || ind[[1]] < 1)
        return(FALSE)
    dim <- 1
    while (dim + 1 <= length(ind)) {
        if (ind[dim + 1] > length(form[[ ind[1:dim] ]] ) || ind[dim + 1] < 1)
            return(FALSE)
        dim <- dim + 1
    }
    return(TRUE)
}

以下是一些示例输出:

> aList <- list( list(1,2,list(1,10,100,1000),3), 5 )
> indexExists(c(1), aList)
[1] TRUE
> indexExists(c(2), aList)
[1] TRUE
> indexExists(c(0), aList)
[1] FALSE
> indexExists(c(3), aList)
[1] FALSE
> indexExists(c(1,1), aList)
[1] TRUE
> indexExists(c(1,3), aList)
[1] TRUE
> indexExists(c(1,4), aList)
[1] TRUE
> indexExists(c(1,0), aList)
[1] FALSE
> indexExists(c(1,5), aList)
[1] FALSE
> indexExists(c(1,3,4), aList)
[1] TRUE
> indexExists(c(1,3,5), aList)
[1] FALSE

请注意,我不认为问题中答案的效率取决于列表元素的大小,因为在这种情况下,如果修改复制的对象,R只会在内存中创建一个新对象。我可能会建议分配list[[index]](这清楚表明您正在分配而不是例如打印)。

相关问题