Abdel
Abdel

Reputation: 6106

How do I replace missing value with values from another column in R

I have a data frame that looks something like this:

ID var1 var2 var3
per1 1 NA 3
per2 3 NA 5
per3 NA 4 6
per4 4 7 9
per5 7 NA NA
per6 NA 8 NA

I want to replace the missing values from column 2 (var1) with values from column 3 (var2), but only if the values from var1 are missing. So the output should look like this:

ID var1 var2 var3
per1 1 NA 3
per2 3 NA 5
per3 4 4 6
per4 4 7 9
per5 7 NA NA
per6 8 8 NA

I would think that something like this would work:

df$var1[is.na(df$var1)] <- df$var2

But unfortunately it doesn't, I get the following error message:

Warning message:
In df$var1[is.na(df$var1)] <- df$var2.2 :
  number of items to replace is not a multiple of replacement length

How do I achieve this?

Upvotes: 0

Views: 551

Answers (1)

Mel Sscn
Mel Sscn

Reputation: 96

You could do the following:

df$var1[is.na(df$var1)] <- df$var2[is.na(df$var1)]

Upvotes: 4

Related Questions