0

I have a problem with a data frame and hope to find help here. The initial data frame (let's call it df1) contains an ID number, that might be repeated several times and might not be in order.

>df1
      ID
1   5468
2   5468
3   8896
4   8896

I would like to use this ID, to look up the corresponding country in another data frame (df2), that looks something like that:

>df2
    ID     country
1   5468   USA
2   8896   Canada

and add the country in the initial data frame. Note that every ID only appears once in the second data frame but can have multiple appearances in the first data frame. Basically I am looking for something similar to the Excel "vlookup" function, just for R.

I would appreciate any help very much!

3 Answers 3

4

Use merge:

df1 <- data.frame(ID=rep(c(5468,8896), each=2))
df2 <- data.frame(ID=c(5468,8896), country=c("USA","Canada"))

merge(df1, df2)
    ID country
1 5468     USA
2 5468     USA
3 8896  Canada
4 8896  Canada
3

You can use match().

Like if the first one is dataset1$ID[n], and the second is dataset2$ID

Then dataset2[match(dataset1$ID[n],dataset2$ID,2]

But for most purposes the answer James gave is way better, but match is more analogous to vlookup if you really want that.

1

This uses an environment lookup and so on larger data sets this may be much faster than any other solution:

df1 <- data.frame(ID=rep(c(5468,8896), each=2))
df2 <- data.frame(ID=c(5468,8896), country=c("USA","Canada"))

library(qdap)
df1$country <- lookup(df1[, 1], df2)

## binary operator for lookup
##  df1$country <- df1[, 1] %l% df2  

## > df1
##     ID country
## 1 5468     USA
## 2 5468     USA
## 3 8896  Canada
## 4 8896  Canada

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.