Hi all, I'm having a little trouble here. Right now I have a data frame like so:
df <- data.frame(
a = letters[1:5],
b = LETTERS[1:5],
start = rep(sample(1:2), length.out = 5)
)
df
# a b start
# 1 a A 1
# 2 b B 2
# 3 c C 1
# 4 d D 2
# 5 e E 1
And for each row I need to grab the value from the nth column determined by start
, so my desired output would be:
# a b start result
# 1 a A 1 a
# 2 b B 2 B
# 3 c C 1 c
# 4 d D 2 D
# 5 e E 1 e
A solution using base R or data.table
would be best
Update: I think I've got it, something like this seems to work:
df <- data.frame(
a = letters[1:5],
b = LETTERS[1:5],
start = rep(sample(1:2), length.out = 5)
)
x <- 1:5
y <- df$start
mat <- as.matrix(df)
mat[cbind(x, y)]
# [1] "a" "B" "c" "D" "e"