O'Reilly logo

R Data Analysis Cookbook - Second Edition by Kuntal Ganguly

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

How to do it...

To add variables to an existing spatial data frame, follow these steps:

  1. Perform the following steps shown (from the Creating spatial data frames by combining regular data frames with spatial objects recipe in this chapter):
> library(maps) 
> library(maptools) 
> nj.map <- map("county", "new jersey", fill=T, plot=FALSE) 
> county_names <- sapply(strsplit(nj.map$names, ","),     function(x) x[2]) 
> nj.sp <- map2SpatialPolygons(nj.map, IDs = county_names, proj4string = CRS("+proj=longlat +ellps=WGS84")) 
> nj.dat <- read.csv("nj-county-data.csv") 
> rownames(nj.dat) <- nj.dat$name 
> nj.spdf <- SpatialPolygonsDataFrame(nj.sp, nj.dat) 
  1. Compute the population density for each county:
> pop_density <- nj.spdf@data$population/nj.spdf@data$area_sq_mi ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required