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但没有运气。提前致谢。

4

2 回答 2

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
于 2013-07-11T02:33:49.883 回答
2
lapply(seq_along(lst), function(idx) {
    unname(cbind(lst[[idx]], idx))
})
于 2013-07-11T02:04:18.657 回答