-2

If I have two data frames, data1 which is a key, and data2 is a very long data set.

data1

type    type2    contact
a       1        alex
a       2        jim
a       3        alex
b       1        john
b       2        bart
b       3        jim

and data2

type    type2    
a       1        
a       1        
a       1        
a       2        
a       3       
a       3      
b       1        
b       2       
b       2       
b       3       

I would like to get a formula to lookup the contact info on data2 using data1 to get the result below.

type    type2    contact
a       1        alex 
a       1        alex
a       1        alex
a       2        jim
a       3        alex
a       3        alex
b       1        john
b       2        bart 
b       2        bart
b       3        jim

I tried something along the lines of:

data2$contact <- data1$contact[data1$type == data2$type & data1$type2 == data2$type2]

However, that doesn't work, and I'm not sure of the right approach to take in R

ajamess
  • 141
  • 2
  • 12

1 Answers1

0

We can use left_join

library(dplyr)
left_join(data1, data2)
#   type type2 contact
#1     a     1    alex
#2     a     1    alex
#3     a     1    alex
#4     a     2     jim
#5     a     3    alex
#6     a     3    alex
#7     b     1    john
#8     b     2    bart
#9     b     2    bart
#10    b     3     jim

Or a base R option would be match

data1$contact[match(do.call(paste0, data2), do.call(paste0, data1[-3]))]
#[1] "alex" "alex" "alex" "jim"  "alex" "alex" "john" "bart" "bart" "jim" 
akrun
  • 874,273
  • 37
  • 540
  • 662