Beardedant
Beardedant

Reputation: 150

Impose NA values of one data frame on identically formatted second data frame

I have two data frames, formatted the same, whereby the NA values in DF1 should be imposed on DF2, leaving all other values in DF2 intact.

Example below, with code to reproduce the two DFs and desired resulting DF underneath:

enter image description here

structure(list(ID = c(100, 101, 102, 103), c1 = c(NA, NA, NA, 
"Y"), c2 = c("Y", NA, NA, "Y"), c3 = c("Y", "Y", "Y", NA), c4 = c(NA, 
NA, NA, NA), c5 = c(NA, NA, NA, NA)), class = "data.frame", row.names = c(NA, 
-4L))

structure(list(ID = c(100, 101, 102, 103), c1 = c(0, 0, 0, NA
), c2 = c(1, 0, 0, 0), c3 = c(0, 0, 0, 1), c4 = c(0, 0, NA, 0
), c5 = c(1, 0, NA, 0)), class = "data.frame", row.names = c(NA, 
-4L))

structure(list(ID = c(100, 101, 102, 103), c1 = c(NA, NA, NA, 
NA), c2 = c(1, NA, NA, 0), c3 = c(0, 0, 0, NA), c4 = c(NA, NA, 
NA, NA), c5 = c(NA, NA, NA, NA)), class = "data.frame", row.names = c(NA, 
-4L))

Upvotes: 1

Views: 27

Answers (1)

akrun
akrun

Reputation: 886948

Just do an assignment (if the dimensions are the same)

DF3 <- DF2
DF3[is.na(DF1)] <- NA

-output

> DF3
   ID c1 c2 c3 c4 c5
1 100 NA  1  0 NA NA
2 101 NA NA  0 NA NA
3 102 NA NA  0 NA NA
4 103 NA  0 NA NA NA

Upvotes: 5

Related Questions