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==
LOC == 1
V
V1
LOC==
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
If LOC only contains 1 or 2 then this will work
LOC
df$V <- ifelse(df$LOC == 1, df$V1, df$V2)