How to attach a simple data.frame to a SpatialPolygonDataFrame in R?

Viewed 19206

I have (again) a problem with combining data frames in R. But this time, one is a SpatialPolygonDataFrame (SPDF) and the other one is usual data.frame (DF). The SPDF has around 1000 rows the DF only 400. Both have a common column, QDGC

Now, I tried

oo <- merge(SPDF,DF, by="QDGC", all=T)

but this only results in a normal data.frame, not a spatial polygon data frame any more. I read somewhere else, that this does not work, but I did not understand what to do in such a case (has to do something with the ID columns, merge uses)

oooh such a hard question, I quess...

Thanks! Jens

6 Answers

One more solution is to use append_data function from the tmaptools package. It is called with these arguments:

append_data(shp, data, key.shp = NULL, key.data = NULL,
  ignore.duplicates = FALSE, ignore.na = FALSE,
  fixed.order = is.null(key.data) && is.null(key.shp))

It's a bit unfortunate that it's called append since I'd understand append more ina sense of rbind and we want to have something like join or merge here.

Ignoring that fact, function is really useful in making sure you got your joins correct and if some rows are present only on one side of join. From the docs:

Under coverage (shape items that do not correspond to data records), over coverage (data records that do not correspond to shape items respectively) as well as the existence of duplicated key values are automatically checked and reported via console messages. With under_coverage and over_coverage the under and over coverage key values from the last append_data call can be retrieved,

If it is two shapefiles that are needed to be merged to a single object, just use rbind().

When using rbind(), just make sure that both the arguments you use are SpatialDataFrames. You can check this using class(sf). If it is not a dataframe, then use st_as_sf() to convert them to a SpatialDataFrame before you rbind them.

Note : You can also use this to append to NULLs, especially when you are using a result from a loop and you want to cumulate the results.

Related