1

I have two dataframes:

    DF1 <- data.frame (col1  = c("a", "b", "c"),
                      col2 = c("4", "3", "6")
    )
    
    DF2 <- data.frame (col3  = c("x", "y", "z"),
                       col4 = c("18", "3", "5")
    )

    


 DF1
     col2   col2
    1    a      4
    2    b      3
    3    c      6

     
    DF2
    col3 col4
    1    x   18
    2    y    3
    3    z    5

For each row I want to add DF2$col3 to DF1, if DF2$col4 has the same value as DF1$col2.

Same value <- copy x/y/z to new column in DF1

Different value <- write NA to new column in DF1

How can I do this?

user438383
  • 5,716
  • 8
  • 28
  • 43

3 Answers3

0

Is this what you need?

DF1$new <- ifelse(as.numeric(DF1$col2) == as.numeric(DF2$col4),
                  DF2$col3,
                  NA)

Result:

DF1
  col1 col2  new
1    a    4 <NA>
2    b    3    y
3    c    6 <NA>
Chris Ruehlemann
  • 20,321
  • 4
  • 12
  • 34
0

This is a merge operation.

merge(DF1, DF2, by.x="col2", by.y="col4", all.x = TRUE)
#   col2 col1 col3
# 1    3    b    y
# 2    4    a <NA>
# 3    6    c <NA>

Or a match operation:

DF1$col3 <- DF2$col3[match(DF2$col4, DF1$col2)]
DF1
#   col1 col2 col3
# 1    a    4 <NA>
# 2    b    3    y
# 3    c    6 <NA>
r2evans
  • 141,215
  • 6
  • 77
  • 149
  • can I use the match operation with 2 arguments? (copy x/y/z if if DF2$col4 has the same value as DF1$col2 AND if DF2$col5 has the same value as DF1$col6) (Of course I would need to add the columns 5 and 6 to both dataframes) –  Sep 25 '21 at 11:07
  • For two or more, the only reliable method is to use a merge or join operation. You might be able to work out code that does two or more, but you would be re-implementing `merge` and `dplyr::*_join` from scratch. I suggest you stick with the known-working functions that do that operation *very well*. – r2evans Sep 25 '21 at 23:57
0
library(tidyverse)
DF1 %>%
  left_join(., DF2, by = c('col2' = 'col4'))

which gives

#   col1 col2 col3
# 1    a    4 <NA>
# 2    b    3    y
# 3    c    6 <NA>
deschen
  • 10,012
  • 3
  • 27
  • 50