Convert latitude and longitude coordinates to country name in R - r

I have a list of latitude and longitude coordinates, and wish to find out which country they all reside in.
I modified an answer from this question about lat-long to US states, and have a working function, but I run into the problem that the worldHires map (from the mapdata package) is hideously out of date and contains a lot of obsolete countries such as Yugoslavia and the USSR.
How would I modify this function to use a more modern package, such as rworldmap? I have only managed to frustrate myself so far...
library(sp)
library(maps)
library(rgeos)
library(maptools)
# The single argument to this function, points, is a data.frame in which:
# - column 1 contains the longitude in degrees
# - column 2 contains the latitude in degrees
coords2country = function(points)
{
# prepare a SpatialPolygons object with one poly per country
countries = map('worldHires', fill=TRUE, col="transparent", plot=FALSE)
names = sapply(strsplit(countries$names, ":"), function(x) x[1])
# clean up polygons that are out of bounds
filter = countries$x < -180 & !is.na(countries$x)
countries$x[filter] = -180
filter = countries$x > 180 & !is.na(countries$x)
countries$x[filter] = 180
countriesSP = map2SpatialPolygons(countries, IDs=ids, proj4string=CRS("+proj=longlat +datum=wgs84"))
# convert our list of points to a SpatialPoints object
pointsSP = SpatialPoints(points, proj4string=CRS("+proj=longlat +datum=wgs84"))
# use 'over' to get indices of the Polygons object containing each point
indices = over(pointsSP, countriesSP)
# Return the state names of the Polygons object containing each point
myNames = sapply(countriesSP#polygons, function(x) x#ID)
myNames[indices]
}
##
## this works... but it has obsolete countries in it
##
# set up some points to test
points = data.frame(lon=c(0, 5, 10, 15, 20), lat=c(51.5, 50, 48.5, 47, 44.5))
# plot them on a map
map("worldHires", xlim=c(-10, 30), ylim=c(30, 60))
points(points$lon, points$lat, col="red")
# get a list of country names
coords2country(points)
# returns [1] "UK" "Belgium" "Germany" "Austria" "Yugoslavia"
# number 5 should probably be in Serbia...

Thanks for the carefully constructed question.
It required just a couple of line changes to be able to use rworldmap (containing up-to-date countries) see below. I'm not an expert on CRS but I don't think the change I had to make to the proj4string makes any difference. Others might like to comment on that.
This worked for me & gave :
> coords2country(points)
[1] United Kingdom Belgium Germany Austria
[5] Republic of Serbia
All the best,
Andy
library(sp)
library(rworldmap)
# The single argument to this function, points, is a data.frame in which:
# - column 1 contains the longitude in degrees
# - column 2 contains the latitude in degrees
coords2country = function(points)
{
countriesSP <- getMap(resolution='low')
#countriesSP <- getMap(resolution='high') #you could use high res map from rworldxtra if you were concerned about detail
# convert our list of points to a SpatialPoints object
# pointsSP = SpatialPoints(points, proj4string=CRS(" +proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs +towgs84=0,0,0"))
#setting CRS directly to that from rworldmap
pointsSP = SpatialPoints(points, proj4string=CRS(proj4string(countriesSP)))
# use 'over' to get indices of the Polygons object containing each point
indices = over(pointsSP, countriesSP)
# return the ADMIN names of each country
indices$ADMIN
#indices$ISO3 # returns the ISO3 code
#indices$continent # returns the continent (6 continent model)
#indices$REGION # returns the continent (7 continent model)
}

You can use my geonames package to lookup from the http://geonames.org/ service:
> GNcountryCode(51.5,0)
$languages
[1] "en-GB,cy-GB,gd"
$distance
[1] "0"
$countryName
[1] "United Kingdom of Great Britain and Northern Ireland"
$countryCode
[1] "GB"
> GNcountryCode(44.5,20)
$languages
[1] "sr,hu,bs,rom"
$distance
[1] "0"
$countryName
[1] "Serbia"
$countryCode
[1] "RS"
Get it from r-forge because I'm not sure I bothered to release it to CRAN:
https://r-forge.r-project.org/projects/geonames/
Yes, it depends on an external service, but at least it knows what happened to communism... :)

Related

Unable to project simple features or change projection

I am trying to convert a csv to an sf spatial data file, however I'm getting errors that I cant' figure out.
Example:
library(tidyverse)
library(sf)
#> Linking to GEOS 3.8.0, GDAL 3.0.4, PROJ 6.3.1
point_df <- tibble::tribble(
~city_name, ~longitude, ~latitude,
"Akron", -81.5190053, 41.0814447,
"Albany", -73.7562317, 42.6525793,
"Schenectady", -73.9395687, 42.8142432,
"Albuquerque", -106.650422, 35.0843859,
"Allentown", -75.4714098, 40.6022939,
"Bethlehem", -75.3704579, 40.6259316,
"Atlanta", -84.3879824, 33.7489954,
"Augusta", -82.0105148, 33.4734978,
"Austin", -97.7430608, 30.267153,
"Bakersfield", -119.0187125, 35.3732921
)
point_sf <- st_as_sf(point_df, coords = c("longitude", "latitude"))
point_sf <- st_set_crs(point_sf, 4326)
st_transform(point_sf, 102003)
#> Warning in CPL_crs_from_input(x): GDAL Error 1: PROJ: proj_create_from_database:
#> crs not found
#> Error in CPL_transform(x, crs, aoi, pipeline, reverse): crs not found: is it missing?
Any help would be greatly appreciated.
EDIT
I found a kludgy solution which I adapted from this github page, but I am stil looking for a more systematic solution if possible. https://github.com/r-spatial/sf/issues/1419
The solution here is to convert the sf object into sp then change back to sf.
reProject <- function (sf, proj_in = "+init=epsg:4326",
proj_out = "+proj=aea +lat_1=20 +lat_2=60 +lat_0=40 +lon_0=-96 +x_0=0 +y_0=0 +datum=NAD83 +units=m +no_defs") {
require(sp)
data_sp <- as(sf, "Spatial")
proj4string(data_sp) <- CRS(proj_in)
sf_out <- st_as_sf(spTransform(data_sp, CRS(proj_out)))
}
dat_out <- reProject(point_sf)
It appears something was expected to happen with the following line of code. But that something is not happening.
point_sf <- st_as_sf(point_df, coords = c("longitude", "latitude"))
While this line of code creates the simple feature geometric point objects, this code does not create the simple feature geometry column (sfc) object. And since there is no sfc object, the next line of code does not work.
point_sf <- st_set_crs(point_sf, 4326)
In this other line of code, the function, st_set_crs(), retrieves a coordinate reference system from sf or sfc objects. But neither the sf or the sfc objects currently exist.
Therefore, the sfc object must be first created before using the function: st_set_crs().
It really helps to follow the following steps whenever doing these types of simple feature projects.
x.sfg <- st_multipoint(c(lon,lat), dim = "XY") # create sf geometry from lon/lat
x.sfc <- st_sfc(x.sfg, crs = 4326) # create sfc from geometry
x.sf <- st_sf(df, x.sfc) # create sf object from sfc
First convert the log and lat to vectors, then create the matrix, and then create the simple feature objects in the correct progression.
lon <- c(-81.5190053, -73.7562317, -73.9395687, -106.650422, -75.4714098, -75.3704579, -84.3879824, -82.0105148, -97.7430608, -119.0187125)
lat <- c(41.0814447, 42.6525793, 42.8142432, 35.0843859, 40.6022939, 40.6259316, 33.7489954, 33.4734978, 30.267153, 35.3732921)
m <- matrix(data = c(lon, lat), nrow = 10, ncol = 2, byrow = FALSE)
m.sfg <- st_multipoint(m, dim = "XY")
m.sfc <- st_sfc(m.sfg, crs = 4326)
m.sf <- st_sf(df, m.sfc)
head(m.sf, 3)
Then create a base plot of the continental US, and then plot the simple feature object onto the base map.
plot(US_48, axes = TRUE)
plot(m.sf, add= TRUE, pch = 19, col = "red")
The link shown above with the question does not seem to have anything related to this question. The answer shown here does not convert the sf object into sp then change back to sf.
The plot is shown at link:

Reverse geocode search (country names) for many locations, output to dataframe issues when country is missing

I am using the geonames package in R to do a reverse geocode search (GNcountryCode) to find the nearest country to my inputs. My inputs are not very precise and are located in water near land. geonames allows for a search within a buffer (km) of the input location.
I was trying to use mapply to expedite retrieving country names from a long list of input locations. However, the limits on buffer size still leave some input locations without a country. To permit mapply to continue running I used tryCatch to prevent mapply from stopping.
However, this results in a non-list entry ("Error") in the overall list of lists (output below). As such, when trying to use data.table::rbindlist I get the following error: "Item n of list input is not a data.frame, data.table or list"
How can I otherwise loop or vectorize GNcountryCode to get the nearest country name to the input location and then add this name back (cbind) to the original data frame (with the understanding that some locations will not be matched to a country)?
library(geonames)# requires a username for some functionality
Latitude <- c("32.75", "33.75", "33.75", "34.25", "34.25", "36.75")
Longitude <- c("-17.25", "-52.25", "-51.75", "-52.25", "-51.75", "-25.25")
# df <- cbind.data.frame(Latitude, Longitude)
MyFun <- function(x,y) {
MyRes <- tryCatch(GNcountryCode(lat=x, lng=y, radius=250), error = function(e) paste("Error"))
#print(MyRes)
return(MyRes)
}
MyResult <- mapply(MyFun, Latitude, Longitude)
data.table::rbindlist(MyResult, fill = TRUE)
#cbind(df, data.table::rbindlist(MyResult, fill = TRUE))
#Ouput
$`32.75`
$`32.75`$`languages`
[1] "pt-PT,mwl"
$`32.75`$distance
[1] "1.96436"
$`32.75`$countryCode
[1] "PT"
$`32.75`$countryName
[1] "Portuguese Republic"
$`33.75`
[1] "Error"
$`33.75`
[1] "Error"
$`34.25`
[1] "Error"
$`34.25`
[1] "Error"
$`36.75`
$`36.75`$`languages`
[1] "pt-PT,mwl"
$`36.75`$distance
[1] "22.63538"
$`36.75`$countryCode
[1] "PT"
$`36.75`$countryName
[1] "Portuguese Republic"
set the error parameter to return NA (and you might also want to pull out just the country name from the return of results that work)...
library(geonames)# requires a username for some functionality
Latitude <- c("32.75", "33.75", "33.75", "34.25", "34.25", "36.75")
Longitude <- c("-17.25", "-52.25", "-51.75", "-52.25", "-51.75", "-25.25")
df <- cbind.data.frame(Latitude, Longitude)
MyFun <- function(x,y) {
tryCatch(GNcountryCode(lat = x, lng = y, radius = 250)$countryName, error = function(e) NA_character_)
}
df$countryname <- mapply(MyFun, Latitude, Longitude)
df
# Latitude Longitude countryname
# 1 32.75 -17.25 Portuguese Republic
# 2 33.75 -52.25 <NA>
# 3 33.75 -51.75 <NA>
# 4 34.25 -52.25 <NA>
# 5 34.25 -51.75 <NA>
# 6 36.75 -25.25 Portuguese Republic

Finding the nearest distance between two SpatialPointsDataframes using gDistance rgeos?

I have two separate but related questions.
First, I would like to determine the distance to the nearest construction site (construction_layer.csv) for every data point within the subset_original_data.csv file. I am trying to use the gDistance() function to calculate the nearest neighbor, but I am open to other ideas as well.
I want to append my subset_original_data.csv dataframe with this new vector of nearest neighbor distances from the construction_layer.csv. That is, for every row of my subset_original_data.csv dataframe, I want the minimum distance to the nearest construction site.
The second goal is to determine the nearest distance from each subset_original_data.csv row to a freeway shapefile (fwy.shp). I would also like to append this new vector back onto the subset_original.csv dataframe.
I have successfully converted the construction_layer.csv and subset_original_data.csv into SpatialPointsDataFrame. I have also converted the fwy.shp file into a SpatialLinesDataFrame by reading in the shape file with the readOGR() function. I am not sure where to go next. Your input is greatly appreciated!
~ $ spacedSparking
Here's my data:
construction_layer.csv, fwy.shp, subset_original_data.csv
Here's my code:
#requiring necessary packages:
library(rgeos)
library(sp)
library(rgdal)
#reading in the files:
mydata <- read.csv("subset_original_data.csv", header = T)
con <- read.csv("construction_layer.csv", header = T)
fwy <- readOGR(dsn = "fwy.shp")
#for those who prefer not to download any files:
data.lat <- c(45.53244, 45.53244, 45.53244, 45.53244, 45.53245, 45.53246)
data.lon <- c(-122.7034, -122.7034, -122.7034, -122.7033, -122.7033, -122.7032)
data.black.carbon <- c(187, 980, 466, 826, 637, 758)
mydata <- data.frame(data.lat, data.lon, data.black.carbon)
con.lat <- c(45.53287, 45.53293, 45.53299, 45.53259, 45.53263, 45.53263)
con.lon <- c(-122.6972, -122.6963, -122.6952, -122.6929, -122.6918, -122.6918)
con <- data.frame(con.lat, con.lon)
#I am not sure how to include the `fwy.shp` in a similar way,
#so don't worry about trying to solve that problem if you would prefer not to download the file.
#convert each file to SpatialPoints or SpatialLines Dataframes:
mydata.coords <- data.frame(lon = mydata[,2], lat = mydata[,1], data = mydata)
mydata.sp <- sp::SpatialPointsDataFrame(mydata.coords, data = data.frame(BlackCarbon = mydata[,3])) #appending a vector containing air pollution data
con.coords <- data.frame(lon = con[,2], lat = con[,1])
con.sp <- sp:SpatialPointsDataFrame(con.coords, data = con)
str(fwy) #already a SpatialLinesDataFrame
#Calculate the minimum distance (in meters) between each observation between mydata.sp and con.sp and between mydata.sp and fwy objects.
#Create a new dataframe appending these two nearest distance vectors back to the original mydata file.
#Desired output:
head(mydata.appended)
LATITUDE LONGITUDE BC6. NEAREST_CON (m) NEAREST_FWY (m)
1 45.53244 -122.7034 187 ??? ???
2 45.53244 -122.7034 980 ??? ???
3 45.53244 -122.7034 466 ??? ???
4 45.53244 -122.7033 826 ??? ???
5 45.53245 -122.7033 637 ??? ???
6 45.53246 -122.7032 758 ??? ???
EDIT:
SOLUTION:
When in doubt, ask a friend who is an R wizard! He even made a map.
library(rgeos)
library(rgdal)
library(leaflet)
library(magrittr)
#Define Projections
wgs84<-CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs +towgs84=0,0,0")
utm10n<-CRS("+proj=utm +zone=10 +ellps=GRS80 +datum=NAD83 +units=m +no_defs +towgs84=0,0,0")
#creating example black carbon data by hand:
lat <- c(45.5324, 45.5325, 45.53159, 45.5321, 45.53103, 45.53123)
lon <- c(-122.6972, -122.6963, -122.6951, -122.6919, -122.6878, -122.6908)
BlackCarbon <- c(187, 980, 466, 826, 637, 758)
bc.coords <- data.frame(lat, lon, BlackCarbon)
bc<-SpatialPointsDataFrame(data.frame(x=lon,y =lat),data=data.frame(BlackCarbon),proj4string = wgs84)
# Project into something - Decimal degrees are no fun to work with when measuring distance!
bcProj<-spTransform(bc,utm10n)
#creating example construction data layer:
con.lat <- c(45.53287, 45.53293, 45.53299, 45.53259, 45.53263, 45.53263)
con.lon <- c(-122.6972, -122.6963, -122.6952, -122.6929, -122.6918, -122.6910)
con.coords <- data.frame(con.lat, con.lon)
con<-SpatialPointsDataFrame(data.frame(x=con.lon,y =con.lat),data=data.frame(ID=1:6),proj4string = wgs84)
conProj<-spTransform(con,utm10n)
#All at once (black carbon points on top, construction on the y-axis)
dist<-gDistance(bcProj,conProj,byid=T)
min_constructionDistance<-apply(dist, 2, min)
# make a new column in the WGS84 data, set it to the distance
# The distance vector will stay in order, so just stick it on!
bc#data$Nearest_Con<-min_constructionDistance
bc#data$Near_ID<-as.vector(apply(dist, 2, function(x) which(x==min(x))))
#Map the original WGS84 data
pop1<-paste0("<b>Distance</b>: ",round(bc$Nearest_Con,2),"<br><b>Near ID</b>: ",bc$Near_ID)
pop2<-paste0("<b>ID</b>: ",con$ID)
m<-leaflet()%>%
addTiles()%>%
addCircleMarkers(data=bc,radius=8,fillColor = 'red',fillOpacity=0.8,weight=1,color='black',popup=pop1)%>%
addCircleMarkers(data=con,radius=8,fillColor = 'blue',fillOpacity=0.8,weight=1,color='black',popup=pop2)
m
You can use the a haversine distance function and use functional programming to achieve the desired result.
library(geosphere)
find_min_dist <- function(site, sites) {
min(distHaversine(site, sites))
}
#X is the data id, split into a list so you can iterate through each site point
data <- split(mydata[ , 3:2], mydata$X)
sapply(data, find_min_dist, sites = con.coords)

Applying revgeocode to a list of longitude-latitude coordinates

I'm trying to get the Zip codes of a (long) list of Longitude Latitude coordinates by using the revgeodcode function in the ggmap library.
My question & data are the same as here: Using revgeocode function in a FOR loop. Help required but the accepted answer does not work for me.
My data (.csv):
ID, Longitude, Latitude
311175, 41.298437, -72.929179
292058, 41.936943, -87.669838
12979, 37.580956, -77.471439
I follow the same steps:
data <- read.csv(file.choose())
dset <- as.data.frame(data[,2:3])
location = dset
locaddr <- lapply(seq(nrow(location)), function(i){
revgeocode(location[i,],
output = c("address"),
messaging = FALSE,
sensor = FALSE,
override_limit = FALSE)
})
... and get the error message: "Error: is.numeric(location) && length(location) == 2 is not TRUE"
Specifically, is.numeric(location) is FALSE, which seems strange because I can multiply by 2 and get the expected answer.
Any help would be appreciated.
There are lots of things wrong here.
First, you have latitude and longitude reversed. All the locations in your dataset, as specified, are in Antarctica.
Second, revgeocode(...) expects a numeric vector of length 2 containing the longitude and latitude in that order. You are passing a data.frame object (this is the reason for the error), and as per (1) it's in the wrong order.
Third, revgeocode(...) uses the google maps api, which limits you to 2500 queries a day. So if you really do have a large dataset, good luck with that.
This code works with your sample:
data <- read.csv(text="ID, Longitude, Latitude
311175, 41.298437, -72.929179
292058, 41.936943, -87.669838
12979, 37.580956, -77.471439")
library(ggmap)
result <- do.call(rbind,
lapply(1:nrow(data),
function(i)revgeocode(as.numeric(data[i,3:2]))))
data <- cbind(data,result)
data
# ID Longitude Latitude result
# 1 311175 41.29844 -72.92918 16 Church Street South, New Haven, CT 06519, USA
# 2 292058 41.93694 -87.66984 1632 West Nelson Street, Chicago, IL 60657, USA
# 3 12979 37.58096 -77.47144 2077-2199 Seddon Way, Richmond, VA 23230, USA
This extracts the zipcodes:
library(stringr)
data$zipcode <- substr(str_extract(data$result," [0-9]{5}, .+"),2,6)
data[,-4]
# ID Longitude Latitude zipcode
# 1 311175 41.29844 -72.92918 06519
# 2 292058 41.93694 -87.66984 60657
# 3 12979 37.58096 -77.47144 23230
I've written the package googleway to access google maps API with a valid API key. So if your data is greater than 2,500 items you can pay for an API key, and then use googleway::google_reverse_geocode()
For example
data <- read.csv(text="ID, Longitude, Latitude
311175, 41.298437, -72.929179
292058, 41.936943, -87.669838
12979, 37.580956, -77.471439")
library(googleway)
key <- "your_api_key"
res <- apply(data, 1, function(x){
google_reverse_geocode(location = c(x["Latitude"], x["Longitude"]),
key = key)
})
## Everything contained in 'res' is all the data returnd from Google Maps API
## for example, the geometry section of the first lat/lon coordiantes
res[[1]]$results$geometry
bounds.northeast.lat bounds.northeast.lng bounds.southwest.lat bounds.southwest.lng location.lat location.lng
1 -61.04904 180 -90 -180 -75.25097 -0.071389
location_type viewport.northeast.lat viewport.northeast.lng viewport.southwest.lat viewport.southwest.lng
1 APPROXIMATE -61.04904 180 -90 -180
To extract the zip code just write down:
>data$postal_code

plotting colored grid over shapefile perhaps with SpatialPolygons

I am attempting to plot a colored grid of attributes over a base map. Similar questions have been asked here, including one recent question I asked myself, but earlier solutions have usually involved ggplot2. I am hoping to find a solution ideally without using ggplot2 if only because my final actual map will be quite complex and I have made substantial progress so far using plot.
Below is code that plots Colorado and creates a grid of fake attribute data. I can convert the grid into spatial points using SpatialPoints and plot those points. However, I suspect I need to convert to spatial polygons, perhaps using SpatialPolygons. When I attempt to use SpatialPolygons I obtain the error shown below.
Once I get the grid cell layer added to the map I would like to crop the grid to only be displayed within Colorado (or, for example, within Colorado and Wyoming if I added another state to the map and used a larger attribute grid). However, that perhaps is a follow-up question.
Here is an earlier question with an answer using plot, but requesting additional information from the poster: R Plot Filled Longitude-Latitude Grid Cells on Map
Here is a similar earlier question from myself that only has a ggplot2 solution: color grid cells in the United States and Canada
My approach below is based off of a solution to another of my earlier questions: R: creating a map of selected Canadian provinces and U.S. states
Thank you for any help.
library(rgdal)
library(maptools)
library(ggplot2)
library(plyr)
library(RColorBrewer)
library(classInt)
library(raster)
# NW(long,lat) SE(long,lat)
mapExtent <- rbind(c(-115, 43), c( -97, 35))
# assign projection
newProj <- CRS("+proj=longlat +datum=NAD83 +no_defs +ellps=GRS80 +towgs84=0,0,0")
## Project map extent
mapExtentPr <- spTransform(SpatialPoints(mapExtent,
proj4string=CRS("+proj=longlat")), newProj)
us1 <- getData('GADM', country="USA", level=1)
colorado <- us1[(us1$NAME_1 %in% c('Colorado')),]
## Project Colorada layer
coloradoPr <- spTransform( colorado, newProj)
# Create grid cells containing fake attribute data
# using approach found here:
# http://www.numbertheory.nl/2011/11/08/drawing-polar-centered-spatial-maps-using-ggplot2/
set.seed(1234)
xlim = c(-113, -99)
ylim = c( 35, 45)
dat.grid = expand.grid(x = xlim[1]:xlim[2], y = ylim[1]:ylim[2])
dat.grid$z = runif(nrow(dat.grid))
## Project grid layer
dat.gridPr <- spTransform(SpatialPoints( dat.grid, proj4string=CRS("+proj=longlat")), newProj)
dat.gridPr2 <- spTransform(SpatialPolygons(dat.grid, proj4string=CRS("+proj=longlat")), newProj)
#Error in spTransform(SpatialPolygons(dat.grid, proj4string = CRS("+proj=longlat")), :
# error in evaluating the argument 'x' in selecting a method for function 'spTransform': Error in SpatialPolygons(dat.grid, proj4string = CRS("+proj=longlat")) :
# cannot get a slot ("area") from an object of type "integer"
## Plot each projected layer, beginning with the projected extent
plot(mapExtentPr, pch=NA)
plot(coloradoPr , border="white", col="lightgrey", add=TRUE)
plot(dat.gridPr , border="white", col="lightgrey", add=TRUE)
plot(dat.gridPr , fill=dat.grid$z, add=TRUE)
plot(dat.gridPr , fill=dat.gridPr$z, add=TRUE)
EDIT
This post describes how to add grid cells one at a time, which I could do if need be:
https://gis.stackexchange.com/questions/18311/instantiating-spatial-polygon-without-using-a-shape-file-in-r
Here is code to create a color-coded grid using the sp package. I have not included the code to create the map of Colorado since that code is presented above. Also, I have not yet tried to crop the grid to fill Colorado only. That may be a separate question.
library(rgdal)
library(maptools)
library(ggplot2)
library(plyr)
library(RColorBrewer)
library(classInt)
library(raster)
setwd('c:/users/mark w miller/gis_in_R')
# create grid of polygons
grd <- GridTopology(c(1,1), c(1,1), c(10,10))
polys <- as(grd, "SpatialPolygons")
row.names(polys)
# [1] "g1" "g2" "g3" "g4" "g5" "g6" "g7" "g8" "g9" "g10" "g11" "g12" "g13" "g14" "g15" "g16" "g17" "g18" "g19"
# [20] "g20" "g21" "g22" "g23" "g24" "g25" "g26" "g27" "g28" "g29" "g30" "g31" "g32" "g33" "g34" "g35" "g36" "g37" "g38"
# [39] "g39" "g40" "g41" "g42" "g43" "g44" "g45" "g46" "g47" "g48" "g49" "g50" "g51" "g52" "g53" "g54" "g55" "g56" "g57"
# [58] "g58" "g59" "g60" "g61" "g62" "g63" "g64" "g65" "g66" "g67" "g68" "g69" "g70" "g71" "g72" "g73" "g74" "g75" "g76"
# [77] "g77" "g78" "g79" "g80" "g81" "g82" "g83" "g84" "g85" "g86" "g87" "g88" "g89" "g90" "g91" "g92" "g93" "g94" "g95"
# [96] "g96" "g97" "g98" "g99" "g100"
length(row.names(polys))
# [1] 100
class(polys)
# [1] "SpatialPolygons"
# attr(,"package")
# [1] "sp"
# assign projection to grid
proj4string(polys) = CRS("+proj=longlat +datum=NAD83 +no_defs +ellps=GRS80 +towgs84=0,0,0")
# create fake atttribute data for each grid cell
poly.data = data.frame(f=runif(length(row.names(polys)), 0, 14))
row.names(poly.data) <- paste0('g', 1:length(row.names(polys)))
# convert grid to a SpatialPolygonsDataFrame:
poly.df = SpatialPolygonsDataFrame(polys, poly.data)
# assign colors to grid cells
plotvar <- poly.df$f
nclr <- 8
plotclr <- brewer.pal(nclr,"BuPu")
colcode <- ifelse(( plotvar <= 2), plotclr[1],
ifelse((plotvar > 2 & plotvar <= 4), plotclr[2],
ifelse((plotvar > 4 & plotvar <= 6), plotclr[3],
ifelse((plotvar > 6 & plotvar <= 8), plotclr[4],
ifelse((plotvar > 8 & plotvar <= 10), plotclr[5],
ifelse((plotvar > 10 & plotvar <= 12), plotclr[6],
ifelse((plotvar > 12 & plotvar <= 14), plotclr[7],
plotclr[8])))))))
jpeg(filename = "grid.plot.jpeg")
plot(poly.df, , col=colcode)
text(coordinates(poly.df), labels=row.names(poly.df))
dev.off()

Resources