Index values from a matrix using row, col indices

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.

Leave a Comment