Index a data frame row-by-row using column names selected from a variable

I would use matrix indexing and match. That approach is vectorized, hence much faster than a for or apply loop would give you:

L <- c("A", "B", "C")
TEST$Value <- TEST[L][cbind(seq_len(nrow(TEST)), match(TEST$Select, L))]

If you are not familiar with matrix indexing, it is documented inside ?"[":

A third form of indexing is via a numeric matrix with the one column for each dimension: each row of the index matrix then selects a single element of the array, and the result is a vector

Leave a Comment