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

前端 未结 2 460
天命终不由人
天命终不由人 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
    
    0 讨论(0)
  • 2020-12-12 02:26

    If LOC only contains 1 or 2 then this will work

     df$V <- ifelse(df$LOC == 1, df$V1, df$V2)
    
    0 讨论(0)
提交回复
热议问题