r - Index values from a matrix using row, col indicies -


this simple solve. have 2d matrix mat 500 rows × 335 columns, , data.frame dat 120425 rows. data.frame dat has 2 columns i , j, integers index row, column mat. add values mat rows of dat.

here conceptual fail:

> dat$matval <- mat[dat$i, dat$j] error: cannot allocate vector of length 1617278737 

(i using r 2.13.1 on win32). digging bit deeper, see i'm misusing matrix indexing, appears i'm getting sub-matrix of mat, , not single-dimension array of values 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 ... 

i expecting int [1:100] 20 1 1 1 20 1 1 1 1 1 .... correct way index 2d matrix using indices of row, column values?

almost. needs offered "[" 2 column matrix:

dat$matval <- mat[ cbind(dat$i, dat$j) ] # should it. 

there caveat: although works dataframes, first coerced matrix-class , if non-numeric, entire matrix becomes "lowest denominator" class.


Comments

Popular posts from this blog

sql - VB.NET Operand type clash: date is incompatible with int error -

SVG stroke-linecap doesn't work for circles in Firefox? -

python - TypeError: Scalar value for argument 'color' is not numeric in openCV -