OverFlow Police
OverFlow Police

Reputation: 861

map values of a data frame to another in R, possibly without plyr

I have two data frames, df and counties. I would like to replace the coordinates that are in columns 3 and afterward column of df with the column fips in the counties data frame.

df = 
year            location       location_NN_1      location_NN_2      location_NN_3
2076 43.59375_-116.78125  41.15625_-90.65625  41.21875_-90.65625 41.15625_-90.65625
2077 43.59375_-116.78125  43.34375_-78.15625  43.34375_-78.21875 43.28125_-78.15625
2078 43.59375_-116.78125  41.34375_-90.78125  41.21875_-90.65625 41.53125_-73.96875
2079 43.59375_-116.78125  43.53125_-116.78125 41.34375_-90.78125               <NA>
2080 43.59375_-116.78125                <NA>               <NA>                <NA>

counties = 
fips   location
36073  43.34375_-78.15625
17161  41.34375_-90.78125

I expect the output to look like:

output 
year            location       location_NN_1      location_NN_2      location_NN_3
2076 43.59375_-116.78125               17131             so_on             so_on
2077 43.59375_-116.78125               36073             so_on             so_on
2078 43.59375_-116.78125               17161             so_on             so_on
2079 43.59375_-116.78125      so_on, so_forth            so_on               <NA>
2080 43.59375_-116.78125                <NA>               <NA>              <NA>

Perhaps something like this solution would work. Which I do not want to use, since it uses plyr, and I do not have good experience with plyr. Loading it messes up other libraries.

any solution would be appreciated.

Upvotes: 1

Views: 212

Answers (1)

akrun
akrun

Reputation: 887971

We can select the columns of interest, loop through the columns with lapply, match with the 'location' column of 'counties' to get the numeric index of matches, then based on that get the corresponding 'fips' values, and update the dataset columns ([])

df[3:5] <- lapply(df[3:5], function(x) counties$fips[match(x, counties$location)])

Upvotes: 2

Related Questions