I have a dataframe:
df <- data.frame(\'a\'=c(1,2,3,4,5), \'b\'=c(1,20,3,4,50)) df a b 1 1 1 2 2 20 3 3 3 4 4 4 5 5 50
Here is a slightly more confusing algebraic method:
df$c <- with(df, b + ((-1)^((a==b)+1) * a)) df a b c 1 1 1 2 2 2 20 18 3 3 3 6 4 4 4 8 5 5 50 45
The idea is that the "minus" operator is turned on or off based on the test a==b.
a==b