Rajarshi Bhadra
Rajarshi Bhadra

Reputation: 1944

Extract elements from specified column for each row in vector

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

Answers (1)

akrun
akrun

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

Related Questions