开发者

Convert two matrices into a list using apply

I have two matrix with the same number of columns, but with different number of rows:

a <- cbind(runif(5), runif(5))
b <- cbind(run开发者_如何学Cif(8), runif(8))

I want to associate these in a same list, so that the first columns of a and b are associated with each other, and so on:

my_result <- list(list(a[,1], b[,1]), list(a[,2], b[,2]))

So the result would look like this:

> print(my_result)
[[1]]
[[1]][[1]]
[1] 0.9440956 0.7259602 0.7804068 0.7115368 0.2771190

[[1]][[2]]
[1] 0.4155642 0.1535414 0.6983123 0.7578231 0.2126765 0.6753884 0.8160817
[8] 0.6548915

[[2]]
[[2]][[1]]
[1] 0.7343330 0.7751599 0.4463870 0.6926663 0.9692621

[[2]][[2]]
[1] 0.5708726 0.1234482 0.2875474 0.4760349 0.2027653 0.5142006 0.4788264
[8] 0.7935544

I can't figure how to do that without a for loop, but I'm pretty sure some *pply magic could be used here.

Any directions would be much appreciated.


I'm not sure how general a solution you're looking for (arbitrary number of matrices, ability to pass a list of matrices, etc.) but this works for your specific example:

lapply(1:2,function(i){list(a[,i],b[,i])})
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜