StirlingCodingClub / studyGroup

Gather together a group to skill-share, co-work, and create community
http://StirlingCodingClub.github.io/studyGroup/
Other
2 stars 1 forks source link

Question: Merge a Spatial object having attributes with a data.frame #15

Open anna-deasey opened 5 years ago

anna-deasey commented 5 years ago

I'm having problems merging a polygon spatial object with a dataframe. I think it might be an easy problem for someone who knows what they're doing :) any help is appreciated.

I have: 'bufpoly' = 'spatialpolygonsdataframe' with 768 elements (polygons of plots with attribute data) and 'dtm_buf_df' = dataframe of values extracted from a raster layer using raster : : extract(dtm_raster, bufpoly, byid = TRUE, df = TRUE, cellnumbers = TRUE) - then adding xy's for each cell This results in the df:

head(dtm_buf_df ) ID cell MNT1m x y 1 1 8811856 23.3025 285174 582934.5 2 1 8811857 23.6950 285175 582934.5 3 1 8811858 24.0550 285176 582934.5 4 1 8811859 24.4150 285177 582934.5 5 1 8811860 24.7600 285178 582934.5 6 1 8816174 23.1325 285173 582933.5

I want to merge 'bufpoly' with 'dtm_buf_df' by "ID"

I try the code below, but it results in an error:

sp::merge(bufpoly, dtm_buf_df , by.x = "ID", by.y = "ID" ) Error in fix.by(by.x, x) : 'by' must specify a uniquely valid column

I think the problems are -
I dont know how to specify 'by.x =' for the correct slot in 'bufpoly' and 'dtm_buf_df' has 768 unique "ID" 's corresponding to the elements in 'bufpoly', but in 'dtm_buf_df' there are ~50 or so rows corresponding to each "ID" which are the raster cell values extracted from inside each polygon ie. I need to merge the buf and df, so that each buf spatial object expands to hold the x,y's and values of all the cells

I've tried many different ways but nothing seems to result in what I really want.

anna-deasey commented 5 years ago

actually, nevermind...........I've just turned 'bufpoly' into a data.frame and done a normal merge, rather than an sp : : merge

It seems to have worked :)