When joining attributes by location with the
over function in
R from the
sp package, only the values for one of the polygons that intersects is retained. Is there a way in R that allows to take attributes of more than located feature? That is, to get ALL qualitative values the polygons that intersect/overlap. With an attribute column for the value of the first located feature, another for the second located feature, etc.
I have also asked about performing this operation in QGIS but have kept it as a separate request due to previous instructions/guidance from a moderator.
Sample code to perform simple spatial joins
#set up sample data install.packages('tmap')#use this library to upload sample spatial polygons library(tmap) data(Europe) # countries data(metro) # cities #transform sample data of points into polygons with same crs/projection for this example (trivial example because point.in.poly suited to this problem but just for the sake of an example metro.pts=spTransform(metro, crs(Europe)) metro.poly=gBuffer(metro.pts, width=50000, byid=TRUE) #load libraries for spatial join library(rgdal) library(sp) #spatial join of the two polygon shapefiles #"find the cities in each country" joined_one=cbind(over(Europe, metro.poly), as.data.frame(Europe)) #but this only joins one of the cities in each country even when more than one city is present #if we check for spain, we only have Barcelona and not Madrid even though it is part of the city file na.omit(joined_first[joined_first$iso_a3=="ESP",]) metro.poly[metro.poly$name=="Madrid"|metro.poly$name=="Barcelona",] #using the `fn` option (function) we can calculate arithmetic for quantitative variables as to get values for more than one polygon that intersects joined_qn=cbind(over(Europe, metro.poly[,5:8], fn=mean), as.data.frame(Europe))