views:

71

answers:

2

Hi R users,

This question is similar to the previous one.

I am providing this example data to get my question across.

id=c(1,2,3,4,5,6,7,8,9,10) 
var1=c(0,1,2,0,6,9,0,0,3,0) 
var2=c(0,0,2,3,0,0,0,5,0,0)
var3=c(0,1,4,3,6,9,0,5,3,0) 
data=data.frame(id,var1,var2, var3) 

What I need is: if values of var1==var2, then make var3==NA but if they are not then keep the value of var3. Would be glad to get it done using the ifelse function in R but other options are welcomed.

I hope that the question is clear enough.

Regards, Bazon

A: 

This should work as long as there are no NA's in the two vectors:

var3 <- ifelse(var1 == var2, NA, var3)
David
thanks david...it worked!
Bazon
this was the complete line i used: df$var3 <- ifelse(df$var1==df$var2,"NA",df$var3)
Bazon
+1  A: 

One thing to be aware of with ifelse is whether the condition could be NA. In your case, using David's example code, if either var1 or var2 is NA, then var3 will get set to NA.

I either set NAs to F in the condition, or do something like:

var3 <- replace(var3, which(var1 == var2), NA)

Compare:

data$var1[1] = NA
with(data, ifelse(var1 == var2, NA, var3))
# [1] NA  1 NA  3  6  9 NA  5  3 NA
with(data, replace(var3, which(var1 == var2), NA))
# [1]  0  1 NA  3  6  9 NA  5  3 NA
Charles
Hi Charles, you are totaly right. I had a quick check after applied David's code and it did what you said (if either var1 or var2 is NA, then var3 will get set to NA), which was not what I wanted in this case. I was just not clear in that area...my apology to you David and thank you (Charles) for the great help!
Bazon