Grab value from nth column per row given another column

datatable
base-r

#1

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 :blush:

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"

#2

Like so? :slightly_smiling_face:

set.seed(796692)
df = data.frame(
  a = letters[1:5],
  b = LETTERS[1:5],
  start = rep(sample(1:2), length.out = 5),
  stringsAsFactors = FALSE
)
df$new_var = apply(df, 1, function(x){ return(x[as.numeric(x[3])]) })
df
  a b start new_var
1 a A     2       A
2 b B     1       b
3 c C     2       C
4 d D     1       d
5 e E     2       E

#3

Nice, thank you @Leon !


#4

NP - YW @tyluRp :+1:

Depending on your scope, this is also an option:

df$new_new_var = ifelse(df$start==1, df$a, df$b)
df
  a b start new_var new_new_var
1 a A     2       A           A
2 b B     1       b           b
3 c C     2       C           C
4 d D     1       d           d
5 e E     2       E           E