I have a data frame (df) with three columns as below:
A B C
1 15 -1.60
15 17 -1.49
3 13 2.59
17 18 3.34
I want to make a new column, "D" in which each row is a copy of a value in column "C," which in its row the column "A" has an equal value to the value of column "B", and if there is not an equal value put "NA"; something like below:
A B C D
1 15 -1.6 -1.49
15 17 -1.49 3.34
3 13 2.59 NA
17 1 3.34 -1.6
I tried to write a loop to make "D" column from "C" column, but it does not work:
for(i in 1:nrow(df)) {
if (df$B==df$A){
df$D==df$C
}else{
df$D==NA}
}
Is there any way rather than looping to make this column? If not, how can I use loops?