Jared
Jared

Reputation: 3570

Get a Different Column for Each Row of a data.frame

I have a data.frame with an arbitrary number of columns and I need a way to grab different columns (just one) from each row. For instance if I have a data.frame like this:

myDF <- data.frame(A=letters[1:5], B=letters[6:10], C=LETTERS[26:22], stringsAsFactors=FALSE)

I want to grab the letters a, g, c, W and V.

If this were a matrix it would be easy to solve.

myDF[cbind(c(1, 2, 3, 4, 5), c(1, 2, 1, 3, 3))]

But I have to store the data in a data.frame because the data is often a POSIXlt and I have not found a way to convert a data.frame of those to a matrix.

Does anyone have a good way of doing this without looping row-by-row? I have many failed attempts that I'd be happy to share.

Upvotes: 2

Views: 1024

Answers (1)

Jared
Jared

Reputation: 3570

It's ineloquent, but it works for dates which are particularly difficult:

vect <- do.call(c, args=as.list(myDF))
vect[(1:NROW(myDF)) + NROW(myDF) * (c(1, 2, 1, 3, 3) - 1)]

Upvotes: 1

Related Questions