使用row,col指示的矩阵的索引值 [英] Index values from a matrix using row, col indicies

查看:411
本文介绍了使用row,col指示的矩阵的索引值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This is probably simple to solve. I have a 2D matrix mat with 500 rows × 335 columns, and a data.frame dat with 120425 rows. The data.frame dat has two columns I and J, which are integers to index the row, column from mat. I would like to add the values from mat to the rows of dat.

这是我的概念失败:

> dat$matval <- mat[dat$I, dat$J]
Error: cannot allocate vector of length 1617278737


的向量

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

(I am using R 2.13.1 on Win32). Digging a bit deeper, I see that I'm misusing matrix indexing, as it appears that I'm only getting a sub-matrix of mat, and not a single-dimension array of values as I expected, i.e.:

> 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矩阵以获取值的正确方法是什么?

I was expecting something like int [1:100] 20 1 1 1 20 1 1 1 1 1 .... What is the correct way to index a 2D matrix using indices of row, column to get the values?

推荐答案

几乎。需要提供[作为两列矩阵:

Almost. Needs to be offered to "[" as a two column matrix:

dat$matval <- mat[ cbind(dat$I, dat$J) ] # should do it.

有一点需要注意:虽然这也适用于数据帧,但它们首先被强制转换为矩阵类,如果有任何非数字,则整个矩阵成为最低分母类。

There is a caveat: Although this also works for dataframes, they are first coerced to matrix-class and if any are non-numeric, the entire matrix becomes the "lowest denominator" class.

这篇关于使用row,col指示的矩阵的索引值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆