I have this df:
data <- structure(list(location = c("bern", "bern", "zurich", "zurich",
"basel", "basel", "basel"), location_latitude = c(4.1, 4.1, 6.2,
6.2, 7.3, 7.3, 7.3), location_longitude = c(2.1, 2.1, 3.2, 3.2,
5.6, 5.6, 5.6), location_population = c(38, 38, 72, 72, 46, 46,
46), origin = c("zurich", "basel", "bern", "basel", "bern", "zurich",
"locarno"), origin_temperature = c(12, 20, 21, 20, 21, 12, 27
)), row.names = c(NA, 7L), class = "data.frame")
I have latitude and longitude for location, but I don’t have latitude and longitude for origin.
I want to insert two columns and populate them with latitude and longitude for origin, based on corresponding coordinates of column location, like this:
data_needed <- structure(list(location = c("bern", "bern", "zurich", "zurich",
"basel", "basel", "basel"), location_latitude = c(4.1, 4.1, 6.2,
6.2, 7.3, 7.3, 7.3), location_longitude = c(2.1, 2.1, 3.2, 3.2,
5.6, 5.6, 5.6), location_population = c(38, 38, 72, 72, 46, 46,
46), origin = c("zurich", "basel", "bern", "basel", "bern", "zurich",
"locarno"), origin_latitude = c("6.2", "7.3", "4.1",
"7.3", "4.1", "6.2", "NA"), origin_longitude = c("3.2",
"5.6", "2.1", "5.6", "2.1", "3.2", "NA"), origin_temperature = c(12,
20, 21, 20, 21, 12, 27)), row.names = c(NA, 7L), class = "data.frame")
I assume it needs to be done column wise, but I don’t know how to do it.
Also I don’t want to have to add conditions that specify locations (e.g., if “zurich”), because the dataset has thousands of locations and origins. I need this to be done ‘automatically’.
Also note that origins that have no matching coordinates in locations (such as Locarno) should return NAs.
Please help!