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

R: merge two tables when one table is a special case of the another one

I want to merge two table with different row numbers by the specific way.
I have the next:


df1 <- data.frame(num = c(1,1,1,2,2,2),
                  lab = c("A", "B", "C", "A", "B", "C"),
                  val = c(0,0,0,0,0,0))
df1
  num lab val
1   1   A   0
2   1   B   0
3   1   C   0
4   2   A   0
5   2   B   0
6   2   C   0

df2 <- data.frame(num = c(1,1,2),
                  lab = c("A", "B", "A"),
                  val = c(10,10,10))
df2
  num lab val
1   1   A  10
2   1   B  10
3   2   A  10

I want to merge df1 and df2 to get df3:

df3 <- data.frame(num = c(1,1,1,2,2,2),
                  lab = c("A", "B", "C", "A", "B", "C"),
                  val = c(10,10,0,10,0,0))
df3
  num lab val
1   1   A  10
2   1   B  10
3   1   C   0
4   2   A  10
5   2   B   0
6   2   C   0

How to do that?

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 :

You can do it with one line:

dplyr::rows_update(df1, df2, by = c("num", "lab"))
#   num lab val
# 1   1   A  10
# 2   1   B  10
# 3   1   C   0
# 4   2   A  10
# 5   2   B   0
# 6   2   C   0
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