Assume that we are dealing with the following data frame and we want to add another column that returns the values of the columns as noted at the selection
column:
set.seed(5) df<-as.data.frame(matrix(sample(1:100,12),ncol=3)) df$Selection<-c("V1","V3","V2","V3") df
V1 V2 V3 Selection
1 66 41 19 V1
2 57 85 3 V3
3 79 94 38 V2
4 75 71 58 V3
We apply the following trick:
df$Value<-as.numeric(df[cbind(seq_len(nrow(df)), match(df$Selection,names(df)))]) df
Output:
V1 V2 V3 Selection Value
1 66 41 19 V1 66
2 57 85 3 V3 3
3 79 94 38 V2 94
4 75 71 58 V3 58