if values of two columns are equal, change the value of resultant column to NA and if not keep to original value of resultant column - using R

StackOverflow https://stackoverflow.com/questions/3783582

  •  04-10-2019
  •  | 
  •  

Question

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

Was it helpful?

Solution

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

OTHER TIPS

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

var3 <- ifelse(var1 == var2, NA, var3)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top