given a data.frame, I'm trying to assign to a var3 the value of var4 if both var1 and var2 are simultaneously (meaning on the same row) missing values, otherwise var3 keeps its own value.
I tried this, but it does not work, any suggestions? Thanks a lot.
aaa<-function(x) {
ifelse((is.na(x$var1)&is.na(x$var2)),
x$var3<-x$var4, x$var3<-x$var3)
return(x)
}
For example:
var1 var2 var3 var4
NA NA NA 1.610
5 NA 4 6
2 1 3.5 NA
1 1.5 2.5 3
I would expect:
var1 var2 var3 var4
NA NA 1.610 1.610
5 NA 4 6
2 1 3.5 NA
1 1.5 2.5 3
indx <- (is.na(x$var1) & is.na(x$var2)) ; x[indx, "var3"] <- x[indx, "var4"]
. Wherex
is your data frame. – David Arenburgaaa <- function(x) { x[,'var3'] <-with(x, ifelse(is.na(var1) & is.na(var2), var4, var3)); x}; aaa(df)
– akrun