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"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With