我有一个二维矩阵 mat
具有 500 行 × 335 列和一个数据框 dat
有 120425 行。数据框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 ...
这样的东西.使用行、列索引来索引二维矩阵以获取值的正确方法是什么?
最佳答案
几乎。需要提供给“[”作为两列矩阵:
dat$matval <- mat[ cbind(dat$I, dat$J) ] # should do it.
有一个警告:虽然这也适用于数据帧,但它们首先被强制转换为矩阵类,如果有任何非数字矩阵,则整个矩阵将成为“最低分母”类。
关于r - 使用 row, col 索引从矩阵中索引值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6920441/