Mitch
Mitch

Reputation: 315

Slicing R arrays by index pair

I have an array in R with 3 columns that looks like:

>x
[,1]     [,2] [,3]
V1 7.803550 0.000000    0
V2 7.842899 0.000000    0
V3 7.310273 0.000000    0
V4 7.230438 0.000000    0
V5 6.582147 1.097024    0
V6 9.364152 0.000000    0

For my array slice, I want different columns from each row, so that the indices of what I want are:

rows<-1:6
cols<-c(1,1,1,2,3,1)

When I try to get the appropriate array slice in R, instead of getting a vector with the appropriate values,

> t
      V1       V2       V3       V4       V5       V6 
7.803550 7.842899 7.310273 0.000000 0.000000 9.364152 

I get a 6x6 matrix of output where a given column is printed out for all selected rows

> t
       [,1]     [,2]     [,3]     [,4] [,5]     [,6]
V1 7.803550 7.803550 7.803550 0.000000    0 7.803550
V2 7.842899 7.842899 7.842899 0.000000    0 7.842899
V3 7.310273 7.310273 7.310273 0.000000    0 7.310273
V4 7.230438 7.230438 7.230438 0.000000    0 7.230438
V5 6.582147 6.582147 6.582147 1.097024    0 6.582147
V6 9.364152 9.364152 9.364152 0.000000    0 9.364152

How can I get my desired index pairs in a vector without a for loop?

Per David's suggestion, the code I was hoping would work would be

t<-x[rows,cols]

Upvotes: 2

Views: 2492

Answers (2)

IRTFM
IRTFM

Reputation: 263411

How about:

x[cbind(rows, cols)]

Read in ?"[" why this should work. (I will lay odds it's faster than Robinson's sapply strategy.)

Upvotes: 10

David Robinson
David Robinson

Reputation: 78610

Probably can't do better than

sapply(1:length(rows), function(i) x[rows[i], cols[i]])

Upvotes: 1

Related Questions