我有一个文件数据框,其中包含有关巴西一些河流的生化需氧量的信息。我想将我拥有的数据(在地理坐标中)转换为城市的名称。我怎样才能做到这一点?我知道有一个名为“ ggmap”的软件包可以为我提供帮助,但是请注意,确定它是否正确]
这里是数据的链接: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
这可以使用栅格中的提取功能。或者也可以使用sp包中的over函数。我下面采用的方法是使用提取功能完成的:
我首先使用上面提供的数据制作一个数据框,然后获取了巴西shapefile,并使用它从提供的坐标中提取城市名称。这是我的注释代码:
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
希望这会有所帮助!