Q:

What is an efficient way to perform calculations which depend on selecting various columns which are indexed by another column

I am trying to subtract one column from another column, but the column changes based on the row. This sounds confusing but an example below makes more sense:
If I have the below dataframe (df)
    a  b  c  d
    2  56 14 16
    3  89 17 13
    2  47 14 19
I want to calculate e, where e is equal to column b - the column indexed by a.
I did this using a for loop for each row but it is very slow:
for(i in 1:nrow(df)){
  df$e <- df$b[i] - df[i, (as.integer(df$a[i]))]
}

df

a  b  c  d  e
2  56 14 16 42
3  89 17 13 76
2  47 14 19 33

A:

We can use row/column indexing to vectorize this
df$e <- df$b - df[-1][cbind(seq_len(nrow(df)), df$a)]
df$e

data
df <- structure(list(a = c(2L, 3L, 2L), b = c(56L, 89L, 47L), c = c(14L, 
17L, 14L), d = c(16L, 13L, 19L)), class = "data.frame", 
   row.names = c(NA, 
-3L))

