I have data that comes to me with many similar variables, with an additional variable which indicates which one of those similar variables I really want. Using a loop I
One more vectorized option is to use a nested ifelse(). It has the benefit of being, at least in my opinion, relatively readable compared to other solutions. But the obvious downside of not scaling when the number of variables grows.
ifelse(df$var == "yr1", df$yr1,
ifelse(df$var == "yr2", df$yr2,
ifelse(df$var == "yr3", df$yr3,
ifelse(df$var == "yr4", df$yr4, NA))))
[1] 3050 2062 1036 4001 3075 4083 1085 3061