locket
locket

Reputation: 761

R using vector as an index in a matrix

I have these two objects:

Vec<-c(1,3,2)
Matrix<-rbind(c(4,2,3,0),c(2,9,1,0),c(2,2,9,9))

For each row of the matrix I would like to use the corresponding value from Vec as an index to pull out the value from the matrix. E.g. for the first row c(4,2,3,0) I want to pick out the first element (4), for the second row c(2,9,1,0) I would like to pick out the third (1).

The result I would like is:

Result<-c(4,1,2)

Upvotes: 1

Views: 255

Answers (4)

s_baldur
s_baldur

Reputation: 33498

Similar logic to ThomasIsCoding's but skipping the transpose:

n = nrow(Vec)
stopifnot(n == length(Vec))
Matrix[1:n + n * (Vec - 1)]
# [1] 4 1 2

Upvotes: 1

Ma&#235;l
Ma&#235;l

Reputation: 51894

With diag:

diag(Matrix[seq_along(Vec), Vec])
#[1] 4 1 2

Upvotes: 1

ThomasIsCoding
ThomasIsCoding

Reputation: 101034

We can also use linear indexing

> t(Matrix)[Vec + ncol(Matrix) * (seq_along(Vec) - 1)]
[1] 4 1 2

Upvotes: 0

akrun
akrun

Reputation: 886938

We may need the row index to create a matrix by cbinding to extract the element based on the row/column index

 Matrix[cbind(seq_len(nrow(Matrix)), Vec)]
[1] 4 1 2

Or another option is

mapply(`[`, asplit(Matrix, 1), Vec)
[1] 4 1 2

Upvotes: 1

Related Questions