Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using row-wise column indices in a vector to extract values from data frame [duplicate]

Tags:

r

Using vector of column positional indexes such as:

> i <- c(3,1,2)

How can I use the index to extract the 3rd value from the first row of a data frame, the 1st value from the second row, the 2nd value from the third row, etc.

For example, using the above index and:

> dframe <- data.frame(x=c("a","b","c"), y=c("d","e","f"), z=c("g","h","i"))

> dframe  
  x y z  
1 a d g  
2 b e h  
3 c f i  

I would like to return:

> [1] "g", "b", "f"
like image 482
Scott Funkhouser Avatar asked Aug 30 '14 15:08

Scott Funkhouser


1 Answers

Just use matrix indexing, like this:

dframe[cbind(seq_along(i), i)]
# [1] "g" "b" "f"

The cbind(seq_along(i), i) part creates a two column matrix of the relevant row and column that you want to extract.

like image 99
A5C1D2H2I1M1N2O1R2T1 Avatar answered Oct 06 '22 02:10

A5C1D2H2I1M1N2O1R2T1