wraymond
wraymond

Reputation: 325

Attribute values to polygons in SpatialPolygonsDataFrame

I have a SpatialPolygonsDataFrame (poly) what I would like to attribute values from another dataframe (df). In the poly@polygons slot are a hole bunch of polygons that have a unique ID. This ID corresponds to ID values in df. df has two types of columns. df$ID are unique IDs (that correspond to poly@polygons ID) and df$1988:df$2014 are columns designating the year. Below each year is the value in question.

Any thoughts on how to get that value, and really all the values for all years for a certain ID, into poly? The end goal is to visualize the polygons colored by the value, one for all years combined, and then a GIF showing the change in values from year to year.

Upvotes: 0

Views: 3287

Answers (1)

admccurdy
admccurdy

Reputation: 724

If I'm understanding the question correctly you want something like this:

newPoly <- merge(poly, df, by.x = 0, by.y = "ID")

sp has a merge method which should join the the spatial data.frame and the normal one as long as the spatial one is first. by.x = 0 specifies to join by row names which should correspond to the ID slots in the spatial polygon. After you've done this you can plot the the values for the various different years

using eithernewPoly$1998ornewPoly@data$1998`

I've never tried merging a spatial polygon using row names so I'm not positive it works, if it doesn't I would create a new column in the data slot of the spatial polygon like so:

poly@data$ID <- row.names(poly@data)

You can create new columns in data slot just be very careful about sorting or removing rows because it will mess up the plotting.

Upvotes: 1

Related Questions