How to extract a range of specific values from a matrix in R?

Viewed 565

I've coded a matrix function for any integer, n. Now I would like to extract all the values 0.25 through 1.0 in the given matrix output. I'm only familiar with extracting elements based on the position in the matrix. What function do you recommend I use to do this? Thank you in advance; let me know if I need to include more information.

For n = 3:

        [,1]      [,2]      [,3]
[1,] 1.0000000 0.5000000 0.3333333
[2,] 0.5000000 0.3333333 0.2500000
[3,] 0.3333333 0.2500000 0.2000000
1 Answers

I think your matrix-producing function is something like this:

make_matrix <- function(n) {
  do.call(cbind, lapply(seq(n) - 1, function(x) 1/(seq(n) + x)))
}

So we can make your matrix like this:

m <- make_matrix(3)
m
#>           [,1]      [,2]      [,3]
#> [1,] 1.0000000 0.5000000 0.3333333
#> [2,] 0.5000000 0.3333333 0.2500000
#> [3,] 0.3333333 0.2500000 0.2000000

We can subset it the same way we subset a vector, since in R, a matrix is just a vector with an added dim attribute:

m[m > 0.25]
#> [1] 1.0000000 0.5000000 0.3333333 0.5000000 0.3333333 0.3333333

We can also find out the positions of the numbers of interest by using which, as long as we add the parameter arr.ind = TRUE:

which(m > 0.25, arr.ind = TRUE)
#>      row col
#> [1,]   1   1
#> [2,]   2   1
#> [3,]   3   1
#> [4,]   1   2
#> [5,]   2   2
#> [6,]   1   3
Related