It seems like there should be a basic R-solution for this, but the best thing I could do with tidyr is to first convert the data to a wide form, and then filter out only the observations that match the desired key.
data %>% add_rownames("index") %>% gather(var, value, -index, -key) %>% filter(key == var)
A basic R solution that almost works:
data[cbind(seq_along(data$key), data$key)]
In the above data, it works, but since it uses a matrix, it has two serious problems. One of them is that the order of the factor matters, because it simply supplants it and selects the columns by the power level, and not by the column name. Another is that the resulting output is character , not numeric , because when converting to a matrix, the character type is selected because of the key column. The key problem is the lack of an analogue of data.frame with respect to matrix behavior
When indexing arrays using "[", one argument "i" can be a matrix with as many columns as dimensions "x"; the result is a vector with elements corresponding to the sets of indices in each row "i".
Given these problems, I will probably go with the tidyr solution, since the fact that the columns can be selected by choice means that they probably represent different observations for the same observed element.
source share