Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I transfer NA's from one data frame into another data frame of the same size in R

I want to update my main data frame so that I can copy the NA entries at the exact position as in my reference data frame ref. Here is an example:

main <- data.frame(Q1 = 1:5,
                   Q2 = rev(1:5),
                   Q3 = c(4, 5, 1, 2, 3))

ref <- data.frame(Q1 = c(0.4, NA, 1.6, 1.1, 0.9),
                  Q2 = c(NA, 2.7, 1.8, 1.5, 0.8),
                  Q3 = c(1.3, 0.9, NA, NA, 2.6))

> main
  Q1 Q2 Q3
1  1  5  4
2  2  4  5
3  3  3  1
4  4  2  2
5  5  1  3

> ref
   Q1  Q2  Q3
1 0.4  NA 1.3
2  NA 2.7 0.9
3 1.6 1.8  NA
4 1.1 1.5  NA
5 0.9 0.8 2.6

How do I create a data frame that is the same as main, but contains NAs at the same positions as in ref? The result should look like this:

> res
  Q1 Q2 Q3
1  1 NA  4
2 NA  4  5
3  3  3 NA
4  4  2 NA
5  5  1  3

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The simplest way:

main[is.na(ref)] <- NA
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading