Adding a column into data slot of SpatialPolygonsDataFrame by assignment operator shapefilecomb$wardturnout <- wardturnout
works, but it is not the safest way to do the job. It relies only on position (first data item goes to first polygon, second to second and so on). It can get messy.
It is best reserved for calculated fields - the shapefile$valuepercapita <- shapefile$value / shapefile$population
kind of assignment.
For data from external sources it is much better idea to assign value by key. Function append_data
from tmap
package does it very nicely, and gives you a message not only when error occurs, but also confirmation when all data was matched perfectly (which I found as a nice touch when working with large sets of imperfect data).
outShape <- append_data(srcShape, frmData, key.shp = "KOD_LAU1", key.data = "LAU1")
Edit (as of 9/2019): This answer seems to be still going strong... The world has changed though.
tmap::append_data()
has been moved to tmaptools::append_data()
and is by now deprecated
sf
has replaced sp
as the go-to package in spatial data in R
In
the sf
world spatial data are stored in modified data.frames
, and the
most appropriate way to assign data items by key is one of the
*_join()
functions from dplyr
- either dplyr::left_join()
to be
on safe side, or dplyr::inner_join()
if filtering on both sides is actually desired behavior.