R data.frame get value from variable which is selected by another variable, vectorized

前端 未结 4 1648
眼角桃花
眼角桃花 2021-01-25 06:09

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

4条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-25 06:57

    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
    

提交回复
热议问题