Filling in a new column based on a condition in a data frame

前端 未结 2 467
天命终不由人
天命终不由人 2020-12-12 01:31

I want to add a new column in my data frame so that for each row if LOC == 1 then V is equal to the value given for V1; if LOC==

2条回答
  •  独厮守ぢ
    2020-12-12 02:19

    Use matrix indexing:

    idx <- cbind(seq_len(nrow(dat)), dat$LOC)
    #      row  col
    #     [,1] [,2]
    #[1,]    1    1
    #[2,]    2    1
    #[3,]    3    2
    #[4,]    4    1
    
    dat[-1][idx]
    #[1] 0.5 0.5 0.7 0.6
    

提交回复
热议问题