在列表中的列表中的矩阵中查找向量的存在

Finding the existance of a vector within matrix within list within list

我曾尝试使用 R 在列表中的列表中的矩阵中查找向量。我已经通过使用以下 'exists' 代码尝试了向量 'ab' 是否存在,但其中 none 有效。我怎样才能让它发挥作用?

 aa <- list(x = matrix(1,2,3), y = 4, z = 3)
 colnames(aa$x) <- c('ab','bb','cb')
 aa 
 #$x
 #     ab bb cb
 #[1,]  1  1  1
 #[2,]  1  1  1
 #
 #$y
 #[1] 4
 #
 #$z
 #[1] 3

 exists('ab', where=aa)
 #[1] FALSE
 exists('ab', where=aa$x)
 # Error in exists("ab", where = aa$x) : invalid 'envir' argument
 exists('ab', where=colnames(aa$x))
 # Error in as.environment(where) : no item called "ab" on the search list
 colnames(aa$x)
 #[1] "ab" "bb" "cb"

列名是 matrixdata.frames 的一部分。因此,我们使用 sapply 遍历 list,获取列名 (colnames),unlist 并检查 'ab' 是否在 [=19= 中]

'ab' %in% unlist(sapply(aa, colnames)) 
#[1] TRUE

如果我们想要更具体地针对特定的 list 元素,我们提取元素 (aa$x),获取列名并检查 'ab' 是否在其中。

'ab' %in% colnames(aa$x)
#[1] TRUE

或者另一种选择是遍历 'aa',并且 if 元素是 matrix,提取 'ab' 列并检查它是否是 vector,用 any 包装 sapply 以获得单个 TRUE/FALSE 输出。

any(sapply(aa, function(x) if(is.matrix(x)) is.vector(x[, 'ab']) else FALSE))