Stelios M
Stelios M

Reputation: 160

Update/merge dataframe row only with non NA values in R

Let's say I have these data frames:

original = data.frame(id = 1, paramA = 12, paramB=30)
update = data.frame(id=1 , paramA = NA , paramB = 22)

How can I produce this data frame:

result_df = data.frame(id = 1, paramA = 12, paramB=22)

In essence, the update data frame must update the original data frame, but only on the columns that are not NA. That's why paramA remained 12 and only paramB got updated to 22 from 30. The data frames will always have only 1 row. I tried searching for similar questions but I did not find something that fits this.

Upvotes: 0

Views: 211

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389295

We could update original at non-NA places from update like

original[!is.na(update)] <- update[!is.na(update)] 

original
#  id paramA paramB
#1  1     12     22

Upvotes: 1

Related Questions