First- that is a brilliant question. Some sort of two-dimensional index is a fundamental question.
I'd be very interested to know if there is a direct (already in R, such as base::diag()) solution.
Here is one solution.
df = data.frame(x = c(1,2,3),
y = c(4,5,6),
columnIndicator = c("x","x","y"),
stringsAsFactors = FALSE)
# direct solution
sapply(
seq_len(nrow(df)),
function(i) {
df[i, df$columnIndicator[[i]], drop = TRUE ]
})
# [1] 1 2 6
# wrapped as a re-usable function solution
two_dim_index <- function(d, idx1, idx2) {
sapply(
seq_len(nrow(d)),
function(i) {
d[idx1[[i]], idx2[[i]], drop = TRUE ]
})
}
df$newValue <- two_dim_index(df,
seq_len(nrow(df)),
df$columnIndicator)
print(df)
# x y columnIndicator newValue
# 1 1 4 x 1
# 2 2 5 x 2
# 3 3 6 y 6
@nwerth's idea of building a composite key to join is also quite sound.