2015-10-19 53 views
3

我試圖使用R在列表內的列表內找到矩陣內的向量。我曾嘗試使用以下'存在'代碼來存在矢量'ab',但它們都不起作用。我怎樣才能使它工作?查找列表中列表內矩陣內向量的存在

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" 
+1

'ab'不是'vector';它只是'矩陣'列的名稱(它不是由矢量構成的,而是用'dim'和'dimnames'屬性表示的矢量)。你可以在%colnames(aa $ x)中用''ab'%'來檢查'aa'列表中'x'元素包含的'matrix'是否有一個名爲'ab'的列。 – nicola

+0

你有興趣找到'ab'這個名字還是'ab'的內容? –

回答

3

列名稱是matrixdata.frames的一部分。所以,我們遍歷使用sapplylist,獲得列名(colnames),unlist和檢查「AB」是否是中是vector

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

如果我們想更具體的特定list元素,我們提取元素(aa$x),獲取列名並檢查其中是否包含「ab」。

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

或者另一個選擇是將循環通過「AA」,並if元素是matrix,提取「AB」列,並檢查它是否是一個vector,包裹sapplyany獲得單輸出爲TRUE/FALSE

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