Reputation: 161
I have a file data frame with informations about biochemical oxygen demand of some rivers, in Brazil. I'd like to transform the data that I have (in geographic coordinates) to the name of the city. How can I do that? I know there is a package called "ggmap" that could help me, but I'm note sure if it's the right one
Here is the link for the data: https://www.dropbox.com/s/rgkkqw50qqymil6/dbo.xls?dl=0
state river lat long year contagem mean
<chr> <chr> <dbl> <dbl> <dbl> <dbl> <dbl>
1 AL Rio Mundaú -9.60 -35.8 2007 5 3
2 AL Rio Mundaú -9.60 -35.8 2010 5 2
3 AL Rio Mundaú -9.60 -35.8 2011 9 3.78
4 AL Zona dos Canais -9.71 -35.8 2007 5 2.2
5 AL Zona dos Canais -9.71 -35.8 2010 7 2
6 AL Zona dos Canais -9.71 -35.8 2011 9 2.11
Upvotes: 0
Views: 1451
Reputation: 312
This is possible using the extract function from raster. Or also possible with the over function from the sp package. The approach I have taken below is done using the extract function:
I first used your data provided above to make a data frame, and then got the Brazil shapefile, and used it to extract the city name from the coordinates provided. Here is my code with comments:
library(raster)
library(sp)
#### Coordinates that will be used to search ###
state = c('AL','AL','AL','AL','AL','AL')
river = c('Rio Mundaú', 'Rio Mundaú', 'Rio Mundaú' , 'Zona dos Can', 'Zona dos Can', 'Zona dos Canais')
lat = c(-9.60, -9.60, -9.60, -9.71, -9.71, -9.71)
long = c(-35.8, -35.8, -35.8, -35.8, -35.8, -35.8)
year = c(2007, 2010, 2011, 2007, 2010, 2011)
contagem = c(5, 5, 9, 5, 7, 9)
mean = c(3, 2, 3.78, 2.2, 2, 2.11)
brazil_data = data.frame(state, river, lat, long, year, contagem, mean)
### Getting the brazil shapefile
brazil = getData('GADM', country = 'Brazil', level = 3, type = "sp")
### Extracting the attributes from the shapefile for the given points
city_names = extract(brazil, brazil_data[, c("long", "lat")])[,12]
### Adding the city names to the Brazil data frame, with the coordinates
brazil_data$City = city_names
This is what we get at the end:
> brazil_data
state river lat long year contagem mean City
1 AL Rio Mundaú -9.60 -35.8 2007 5 3.00 Santa Luzia do Norte
2 AL Rio Mundaú -9.60 -35.8 2010 5 2.00 Santa Luzia do Norte
3 AL Rio Mundaú -9.60 -35.8 2011 9 3.78 Santa Luzia do Norte
4 AL Zona dos Can -9.71 -35.8 2007 5 2.20 Marechal deodoro
5 AL Zona dos Can -9.71 -35.8 2010 7 2.00 Marechal deodoro
6 AL Zona dos Canais -9.71 -35.8 2011 9 2.11 Marechal deodoro
Hope this helps!
Upvotes: 2