2
votes

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
1
Probably just indx <- (is.na(x$var1) & is.na(x$var2)) ; x[indx, "var3"] <- x[indx, "var4"]. Where x is your data frame.David Arenburg
@UmbertoMedicamento Your ifelse function can be aaa <- function(x) { x[,'var3'] <-with(x, ifelse(is.na(var1) & is.na(var2), var4, var3)); x}; aaa(df)akrun
@ David Arenburg Interesting, can you explain it? Anyhow, I tried but it doesn't work. My data are all numbers.Umberto Medicamento
What is exactly not working? It works fine with the provided data.David Arenburg

1 Answers

3
votes

No need in ifelse here because your "no" statement isn't doing anything. All you need to do is to find the correct rows and replace only them, while leaving all the rest untouched. Here's a simple base R approach

indx <- with(df, is.na(var1) & is.na(var2))
df[indx, "var3"] <- df[indx, "var4"]

Though, for efficiency and less key strokes, I'd recommend using the data.table package and update the values by reference

library(data.table)
setDT(df)[is.na(var1) & is.na(var2), var3 := var4]