If the values โ€‹โ€‹of the two columns are equal, change the value of the resulting column to NA and if you do not save the original value of the resulting column - using R

This question is similar to the previous one.

I provide data from this example to ask a question.

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) 

I need: if the values โ€‹โ€‹are var1==var2 , then do var3==NA , but if they do not store the value of var3 . Would be happy to do this with the ifelse function in R, but other options are welcome.

Hope the question is clear enough.

Regards, Bazon

+4
source share
2 answers

One thing to know with ifelse is whether the condition can be NA. In your case, using the David code example, if var1 or var2 is NA, then var3 will be set to NA.

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

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

For comparison:

 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 
+1
source

This should work as long as there is no NA in the two vectors:

 var3 <- ifelse(var1 == var2, NA, var3) 
+1
source

All Articles