l = matrix(1:6, ncol=2)
lst = list(l, l)
如何将列表索引作为新列添加到每个矩阵? e.g。
[[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
的各种排列而没有运气。提前谢谢。
答案 0 :(得分:3)
稍微简单一些。实际上,任何涉及将函数按顺序应用于两个(或3个或n个)对象的每个元素的问题都可以给出mapply
或Map
解决方案(谢谢,@ 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
答案 1 :(得分:2)
lapply(seq_along(lst), function(idx) {
unname(cbind(lst[[idx]], idx))
})