Victor Proon
Victor Proon

Reputation: 271

Select an element from each row of a matrix in R

The question is the same as here, but in R. I have a matrix and a vector such that

length(vec) == nrow(mat)

How do i get a vector such that

v[i] == mat[v[i],i]

I tried to achieve this by using logical matrix:

>a = matrix(runif(12),4,3)
a
          [,1]      [,2]      [,3]
[1,] 0.6077585 0.5354680 0.2802681
[2,] 0.2596180 0.6358106 0.9336301
[3,] 0.5317069 0.4981082 0.8668405
[4,] 0.6150885 0.5164009 0.5797668
> sel = col(a) == c(1,3,2,1)
> sel
      [,1]  [,2]  [,3]
[1,]  TRUE FALSE FALSE
[2,] FALSE FALSE  TRUE
[3,] FALSE  TRUE FALSE
[4,]  TRUE FALSE FALSE
> a[sel]
[1] 0.6077585 0.6150885 0.4981082 0.9336301

It selects right elements but messes up the order. I thought of using mapply either, but i don't know how to make it iterate through rows, like in apply.

upd: @gsk3 suggested to use as.list(as.data.frame(t(a))) this works. But still i would like to know if there is a more vectorized way, without lists.

Upvotes: 2

Views: 2039

Answers (1)

Seth
Seth

Reputation: 4795

I am not 100% sure I understand your question, but it seems like this may be close?

> b=c(1,3,2,1)

> i=cbind(1:nrow(a),b)

> a[i]   

Upvotes: 7

Related Questions