user3507767
user3507767

Reputation: 87

Pick an element from each matrix columns

I have a matrix m and a vector v. The vector specifies which element I need in each of m's columns. The length of v equals the number of columns in m. I tried apply(m,2, FUN) but couldn't come up with the right function to do the trick. My data and vector are defined bellow.

set.seed(12)
m <- matrix(sample(1:100,28),4)
v <- c(3,2,2,3,1,4,3)

The result I want is a vector vv:

vv <- c(93,4,1,23,39,82,85)

Help is greatly appreciated!

Upvotes: 1

Views: 56

Answers (1)

gagolews
gagolews

Reputation: 13046

Matrix elements may also be indexed via a 2 column matrix. Such a matrix determines which elements (#row, #column) you want to extract. In your case these are (3,1), (2,2), (2,3), (3,4), etc., i.e. (v[1], 1), (v[2], 2), and so on. Thus, this is a solution:

set.seed(12)
m <- matrix(sample(1:100,28),4)
v <- c(3,2,2,3,1,4,3)

m[cbind(v,seq_along(v))]
## [1] 93  4  1 23 39 82 85

Upvotes: 1

Related Questions