I want to take values from one data frame into a second based on a common variable

StackOverflow https://stackoverflow.com/questions/21919053

  •  14-10-2022
  •  | 
  •  

Question

I have two data frames. One with several destinations and their latitude and longitude. The second has trip data which includes origin and destination names in the exact format as the first dataframe. I would like to get origin and destination in the second frame to have associated coordinates:

> df <- data.frame(location = c("White House", "Impound Lot", "Bush Garden", "Rayburn", "Robertson House", "Beers Elementary"), latitude = c(38.89710, 38.81289, 38.94178, 38.8867787, 38.9053894, 38.86466), longitude = c(-77.036545, -77.0171983, -77.073311, -77.0105317, -77.0616441, -76.95554))

> df2 <- data.frame(trip_id = c(1:8), trip_from = c("Impound Lot", "Bush Garden", "White House", "Robertson House", "Impound Lot", "Beers Elementary", "Bush Garden", "Rayburn"), trip_to = c("Bush Garden", "Impound Lot", "Rayburn", "Impound Lot", "Beers Elementary", "White House", "Impound Lot", "Bush Garden"))

> df
       location latitude longitude
1      White House 38.89710 -77.03655
2      Impound Lot 38.81289 -77.01720
3      Bush Garden 38.94178 -77.07331
4          Rayburn 38.88678 -77.01053
5  Robertson House 38.90539 -77.06164
6 Beers Elementary 38.86466 -76.95554

> df2
  trip_id        trip_from          trip_to
1       1      Impound Lot      Bush Garden
2       2      Bush Garden      Impound Lot
3       3      White House          Rayburn
4       4  Robertson House      Impound Lot
5       5      Impound Lot Beers Elementary
6       6 Beers Elementary      White House
7       7      Bush Garden      Impound Lot
8       8          Rayburn      Bush Garden

I would like to have a new data frame that takes the "latitude" and "longitude" values for each location in df and associates them with each location in df2. Thus I would like to have a table with four more columns (lat_from, lon_from, lat_to, lon_to) so I can map the flows between locations.

Was it helpful?

Solution

A solution with merge :

 df3 <- merge(df2, df, by.x = "trip_to", by.y = "location")
merge(df3, df, by.x = "trip_from", by.y = "location", suffixes = c(".to", ".from"))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top