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

前端 未结 4 1592
眼角桃花
眼角桃花 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 07:11

    We can use the row/column indexing. It should be fast compared to the loop.

     df[-ncol(df)][cbind(1:nrow(df),match(df$var,head(names(df),-1)))]
     #[1] 3050 2062 1036 4001 3075 4083 1085 3061
    

    Just for some diversity, a data.table solution would be (should be slow compared to the indexing above). Convert the 'data.frame' to 'data.table' (setDT(df)), grouped by the sequence of rows, we get the value of 'var' after converting to character class.

    library(data.table)
    setDT(df)[, ycode := get(as.character(var)) , 1:nrow(df)]
    df
    #    yr1  yr2  yr3  yr4 var ycode
    #1: 1090 2066 3050 4012 yr3  3050
    #2: 1026 2062 3071 4026 yr2  2062
    #3: 1036 2006 3098 4038 yr1  1036
    #4: 1056 2020 3037 4001 yr4  4001
    #5: 1088 2017 3075 4037 yr3  3075
    #6: 1019 2065 3089 4083 yr4  4083
    #7: 1085 2036 3020 4032 yr1  1085
    #8: 1096 2072 3061 4045 yr3  3061
    

提交回复
热议问题