Reputation: 1944
I have a vector say
column_index<-c(2,1,3)
and a data frame say
data<-data.frame(A=c(1,2,3),B=c(1,6,9),C=c(1,2,3))
Now I want a vector such that first element is element in data corresponding to row 1 and column index given by first element in column_index. The second element will be row 2 and column index given by second element in column_index and so on. The vector will have 3 elements. Is there any way to acheive this without looping?
Upvotes: 1
Views: 1367
Reputation: 887118
We have the column index, cbind
with the row index (1:nrow(data)
) to extract the elements.
data[cbind(1:nrow(data), column_index)]
Upvotes: 5