使用行,列索引的矩阵索引值

这可能很容易解决。我有一个mat500行×335列的2D矩阵,以及一个dat120425行的data.frame。data.frame dat有两列I和J,它们是从索引到行的整数mat。我想将的值从添加mat到的行中dat。


这是我的概念上的失败:


> dat$matval <- mat[dat$I, dat$J]

Error: cannot allocate vector of length 1617278737

(我在Win32上使用R 2.13.1)。深入研究,我发现我在滥用矩阵索引,因为看来我只是得到的子矩阵mat,而不是我所期望的一维值数组,即:


> str(mat[dat$I[1:100], dat$J[1:100]])

 int [1:100, 1:100] 20 1 1 1 20 1 1 1 1 1 ...

我期待着类似的东西int [1:100] 20 1 1 1 20 1 1 1 1 1 ...。使用行,列的索引获取值来索引2D矩阵的正确方法是什么?


手掌心
浏览 695回答 3
3回答

呼如林

几乎。需要提供给“ [”作为两列矩阵:dat$matval <- mat[ cbind(dat$I, dat$J) ] # should do it.有一个警告:尽管这也适用于数据帧,但它们首先被强制转换为矩阵类,如果有任何非数字类,则整个矩阵将成为“最低分母”类。

牛魔王的故事

这是使用apply基于行的操作的单线> dat <- as.data.frame(matrix(rep(seq(4),4),ncol=2))> colnames(dat) <- c('I','J')> dat&nbsp; &nbsp;I&nbsp; J1&nbsp; 1&nbsp; 12&nbsp; 2&nbsp; 23&nbsp; 3&nbsp; 34&nbsp; 4&nbsp; 45&nbsp; 1&nbsp; 16&nbsp; 2&nbsp; 27&nbsp; 3&nbsp; 38&nbsp; 4&nbsp; 4> mat <- matrix(seq(16),ncol=4)> mat&nbsp; &nbsp; &nbsp;[,1] [,2] [,3] [,4][1,]&nbsp; &nbsp; 1&nbsp; &nbsp; 5&nbsp; &nbsp; 9&nbsp; &nbsp;13[2,]&nbsp; &nbsp; 2&nbsp; &nbsp; 6&nbsp; &nbsp;10&nbsp; &nbsp;14[3,]&nbsp; &nbsp; 3&nbsp; &nbsp; 7&nbsp; &nbsp;11&nbsp; &nbsp;15[4,]&nbsp; &nbsp; 4&nbsp; &nbsp; 8&nbsp; &nbsp;12&nbsp; &nbsp;16> dat$K <- apply( dat, 1, function(x,mat) mat[ x[1], x[2] ], mat=mat )> dat&nbsp; I J&nbsp; K1 1 1&nbsp; 12 2 2&nbsp; 63 3 3 114 4 4 165 1 1&nbsp; 16 2 2&nbsp; 67 3 3 118 4 4 16
打开App,查看更多内容
随时随地看视频慕课网APP