You can use raster::union
Example data:
library(tmap)
library(rgeos)
library(rgdal)
library(raster)
data(Europe)
# simplifying a bit
Eu <- Europe[Europe$iso_a3 %in% c('ESP', 'PRT', 'FRA'),1:2]
data(metro)
metro.pts <- spTransform(metro[, 'name'], crs(Europe))
metro.poly <- gBuffer(metro.pts, width=50000, byid=TRUE)
Original solution
u <- union(Eu, metro.poly)
or
i <- intersect(Eu, metro.poly)
**Update, now I understand the question better **
You can returnList = TRUE
in over:
v <- over(Eu, metro.poly, returnList=TRUE)
You could now do:
a <- lapply(1:length(v), function(i) cbind(iso_a3=Eu$iso_a3[i], v[[i]]))
b <- do.call(rbind, a)
m <- merge(Eu, b, by="iso_a3", all.x=TRUE, duplicateGeoms=TRUE)
In merge
, the argument duplicateGeoms=TRUE
is necessary because otherwise merge cannot handle having more than one (i.e. duplicate) value to assign to each feature.
To get the following:
data.frame(m)
# iso_a3 name.x name.y
#1 ESP Spain Barcelona
#2 ESP Spain Madrid
#3 FRA France Lille
#4 FRA France Lyon
#5 FRA France Marseille
#6 FRA France Paris
#7 PRT Portugal Lisbon
#8 PRT Portugal Porto
I think that this is the same as what Tiernan showed in perhaps more elegant sf code, but I do not think that this is what you asked for.
For what you want, we need to create a data.frame from a list with varying number of elements. There might be a better way, but here is one:
m <- max(sapply(v, nrow))
iso <- as.character(Eu$iso_a3)
x <- sapply(1:length(v),
function(i) c(iso[i], c(v[[i]][,1], rep(NA, m))[1:m])
)
x <- data.frame(t(x), stringsAsFactors=FALSE)
colnames(x) <- c("iso_a3", paste0("metro_", 1:m))
Merge with the original polygons:
r <- merge(Eu, x, by="iso_a3", all.x=TRUE)
data.frame(r)
# iso_a3 name metro_1 metro_2 metro_3 metro_4
#1 ESP Spain Barcelona Madrid <NA> <NA>
#2 FRA France Lille Lyon Marseille Paris
#3 PRT Portugal Lisbon Porto <NA> <NA>
Best Answer
You can simply index the rasters. In this example we will subset the (1, 3-4, 10) rasters. Note the double brackets.
For your needs you can use
Unlike the raster package, to add a raster you can simply use concatenate.
There are also some formal methods in terra, see;
subset
,selectRange
and,add