2013-07-11 59 views
3

簡單的問題無疑。以此爲出發點:將列表索引號添加到矩陣項目作爲新列

l = matrix(1:6, ncol=2) 
lst = list(l, l) 

如何將列表索引作爲新列添加到每個矩陣?例如

[[1]] 
    [,1] [,2] [,3] 
[1,] 1 4 1 
[2,] 2 5 1 
[3,] 3 6 1 

[[2]] 
    [,1] [,2] [,3] 
[1,] 1 4 2 
[2,] 2 5 2 
[3,] 3 6 2 

...假設矩陣有不同數量的行。我試過lapply的各種排列,但沒有運氣。提前致謝。

回答

3

稍微簡單一點。實際上涉及爲了將函數應用於兩個(或3,或n)對象中的每個元件的任何問題,可以給出的mapplyMap溶液(感謝,@mnel):

mapply(cbind, lst, seq_along(lst), SIMPLIFY=FALSE) 
# ...and with Map being a wrapper for mapply with no simplification 
Map(cbind, lst, seq_along(lst)) 

[[1]] 
    [,1] [,2] [,3] 
[1,] 1 4 1 
[2,] 2 5 1 
[3,] 3 6 1 

[[2]] 
    [,1] [,2] [,3] 
[1,] 1 4 2 
[2,] 2 5 2 
[3,] 3 6 2 
+2

'map'是較短的包裝''mapply(...,SIMPLIFY = FALSE)' – mnel

+0

@mnel - 在回答中更新了包括'Map'(有大寫) – thelatemail

+0

是的,我認爲這應該是tick,因爲它更多靈活的解決方案:例如額外的矢量數據可以作爲列添加,而不僅僅是列表索引信息。然後例如列表項可以與'do.call(rbind,lst)'結合成一個data.frame .. – geotheory

2
lapply(seq_along(lst), function(idx) { 
    unname(cbind(lst[[idx]], idx)) 
}) 
+0

感謝@Arun!令人驚訝的複雜解決方案。 – geotheory