0

I have a dataframe named mydata, which includes the information of hundreds county name and their corresponding state name. The dataframe looks like this:

      County.code   State.code   County.name   State.name
    1.    1           1           Autauga       Alabama
    2.    2           1           Baldwin       Alabama
    3.    3           1           Barbour       Alabama
    4.    1           2           Bethel        Alaska
    5.    2           2           Dillingham    Alaska
    6.    1           3           Apache        Arizona
    7.    2           3           Cochise       Arizona

Now I have another dataframe named df, which includes two columns of county code and state code data without order:

         County.code     State.code
    1.      5               3
    2.      3               11
    3.      9               8
    4.      1               5
           ...             ...

My question is how can I replace those number in df with its corresponding county name and state name?

user3353820
  • 83
  • 1
  • 1
  • 6
  • `merge(df, mydata, all.x = T)` Remove the key columns if you don't need them. Moreover, let me know if the marked duplicate doesn't solve your problem. – Ronak Shah Aug 01 '18 at 02:40

1 Answers1

0

The following code will "look up" the county and state name from mydata into df. The by argument is not required given your example; however, I have included it in case the variable names for the county and state codes are different in different datasets.

library(dplyr)
df2 <- df %>%
  left_join(mydata, by = c("County.code" = "County.code", "State.code" = "State.code"))
Anindya Mozumdar
  • 483
  • 2
  • 11