Reputation: 401
Using the example provided below I need to use a if else statement with the following conditions:
Sample data:
df <- data.frame(
original = c(20,40,20,2,20,10,12),
corrected = c(25,43,22,1,25,7,NA),
flag = c(0,0,0,1,1,1,NA))
The output should be appended to the df (df$final) and should, for this example output this:
df$final = c(25,43,22,2,25,10,12)
Thanks for any suggestions.
Upvotes: 0
Views: 1045
Reputation: 70286
Although it is not the most efficient code on earth, you could use a nested ifelse
:
df$final <- with(df, ifelse(is.na(flag), original,
ifelse(flag, pmax(original, corrected), corrected)))
df
# original corrected flag final
#1 20 25 0 25
#2 40 43 0 43
#3 20 22 0 22
#4 2 1 1 2
#5 20 25 1 25
#6 10 7 1 10
#7 12 NA NA 12
You can make use of the fact that flag can be interpreted as a logical value.
Upvotes: 1