Get Values in a Matrix by Pair-wise Indices

pindex(m, i, j)

Arguments

m

A matrix or a 3-dimension array.

i

Row indices or the indices in the first dimension.

j

Column indicies or the indices in the second dimension.

Value

If m is a matrix, the value returned is a vector c(m[i1, j1], m[i2, j2], ...)`.

If m is an array, the value returned is a matrix rbind(m[i1, j1, ], m[i2, j2, ], ...)`.

Examples

m = matrix(rnorm(100), 10) m2 = m[m > 0] ind = do.call("rbind", lapply(1:10, function(ci) { i = which(m[, ci] > 0) cbind(i = i, j = rep(ci, length(i))) })) pindex(m, ind[, 1], ind[, 2])
#> [1] 0.31030923 0.66651132 0.45825713 1.23923784 0.32142619 1.98665079 #> [7] 1.88720053 0.66381092 0.73569713 0.60318930 0.54504614 0.65076758 #> [13] 0.30038830 1.41536821 0.73609075 0.58291632 0.51167333 0.81057520 #> [19] 1.01772098 0.59880248 1.01672953 0.04375947 0.97048785 0.87070062 #> [25] 0.47912409 0.57563890 1.54384492 1.83154531 0.63925483 0.46531229 #> [31] 0.19790749 0.25733554 0.16704424 0.29074462 0.87210366 2.28670551 #> [37] 0.52292860 2.27514007 0.87646511 2.21329543 1.71954343 1.11922942 #> [43] 0.49667542 0.21108201 0.86968687 1.07345732 0.40879306 0.78597642 #> [49] 2.15207805 0.72119043 0.02362363
identical(pindex(m, ind[, 1], ind[, 2]), m[m > 0])
#> [1] TRUE
# 3d array arr = array(1:27, dim = c(3, 3, 3)) pindex(arr, 1:2, 2:3)
#> [,1] [,2] [,3] #> [1,] 4 13 22 #> [2,] 8 17 26
identical(pindex(arr, 1:2, 2:3), rbind(arr[1, 2, ], arr[2, 3, ]))
#> [1] TRUE