这可以使用从栅格中提取的功能。或者也可以使用 sp 包中的 over 功能。我在下面采取的方法是使用提取函数完成的:
我首先使用您上面提供的数据制作数据框,然后获取巴西 shapefile,并使用它从提供的坐标中提取城市名称。这是我的 cmets 代码:
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
这是我们最后得到的:
> 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
希望这会有所帮助!