Creating spatial data frames from regular data frames containing spatial and other data

When you have a regular data frame that has spatial attributes in addition to other attributes, processing them becomes easier if you convert them to full-fledged spatial objects. This recipe shows how to accomplish this.

Getting ready

Install the sp package. Download the nj-wages.csv file and ensure that it is in your R working directory.

How to do it...

To process a a regular data frame with spatial attributes, follow these steps:

  1. Load the sp package:
    > library(sp)
  2. Read the data:
    > nj <- read.csv("nj-wages.csv")
    > class(nj)
    [1] "data.frame"
  3. Convert nj into a spatial object:
    > coordinates(nj) <- c("Long", "Lat") > class(nj) [1] "SpatialPointsDataFrame" attr(,"package") ...

Get R: Recipes for Analysis, Visualization and Machine Learning now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.