Msena
Msena

Reputation: 1

Get specific column value for each row

I want to get a "m" length vector that, considering a m x n matrix, for each row, gives the value on the column identified by another column (say column "Z"). I made it using a for loop:

for (i in 1:dim(data.frame)[1]){vector[i] <- data.frame[i,data.frame$Z[i]]}

Do you see a simpler way to code it avoiding the loop?

Upvotes: 0

Views: 531

Answers (1)

mra68
mra68

Reputation: 2960

"apply" is a possibility:

> M <- cbind( matrix(1:15,3,5), "Z"=c(3,1,2) )

> M
                 Z
[1,] 1 4 7 10 13 3
[2,] 2 5 8 11 14 1
[3,] 3 6 9 12 15 2

> v <- apply(M,1,function(x){x[x["Z"]]})

> v
[1] 7 2 6
> 

Upvotes: 1

Related Questions