Matrix Indexing R

I am trying to index a matrix in R using this code:

test <- matrix(0, nrow = 10, ncol = 2) 
test[1:10, 1]  <- 1:10
test[1:10, 2]  <- 11:20

index <- c(1,2,1,1,2,1,1,2,1,2)

answer <- test[ , index]

I get a 10 x 10 matrix. But I would like to get a vector.

[1] 1 12 3 4 15 6 7 18 9 20

Any ideas?

Edit: Also, how can you use exception indexing (for example -index) to exclude values ​​from the matrix.

[1] 11 2 13 14 5 16 17 8 19 10

0
source share
1 answer

We need indexing row/columnin order to retrieve an element by its corresponding position. To do this, we can cbindsequence the rows with the column index and get the elements.

test[cbind(seq_len(nrow(test)), index)]
#[1]  1 12  3  4 15  6  7 18  9 20
+1
source

All Articles