Assume you have such a data.frame:
df <- data.frame(matrix(1:12, 4))
df
X1 X2 X3
1 1 5 9
2 2 6 10
3 3 7 11
4 4 8 12
which have to be filtered row-wise by these column indices:
b=c(2,1,3,2)
So the expected output should be this:
c(5, 2, 11, 8)
Using following approach is not the solution, obviously.
df[ 1:nrow(df), b]
So far I'm using an approach with mapply which is working:
mapply(function(x, y) x[y], as.data.frame(t(df)), b, USE.NAMES = F)
[1] 5 2 11 8
But I'm wondering whether there is a more elegant solution out there?