How do I construct a vector of values from n
th column of some data frame, where n
is a per-row value defined in some vector? Example:
> df <- data.frame(a=c(100, 110, 120, 130, 140),
b=c(200, 210, 220, 230, 240),
c=c(300, 310, 320, 330, 340))
> df
a b c
1 100 200 300
2 110 210 310
3 120 220 320
4 130 230 330
5 140 240 340
> cl <- c(1, 3, 3, 2, 1)
> some.function(df, cl)
would result in:
[1] 100 310 320 230 140
You can index by a 2-column matrix -- the first column is the row number and the second is the column number.
This is a vectorized operation that should be quicker than looping through the rows with something like
sapply
and grabbing the appropriate value from that row: