Skip to content

Instantly share code, notes, and snippets.

@alfcrisci
Last active December 15, 2020 08:53
Show Gist options
  • Save alfcrisci/4f27f2714885ff94a2dcf3017d23f131 to your computer and use it in GitHub Desktop.
Save alfcrisci/4f27f2714885ff94a2dcf3017d23f131 to your computer and use it in GitHub Desktop.
library(raster)
library(sp)
library(spatialEco)
library(XLConnect)
###############################################################################
setwd("")
ras1<-raster('fileA')
ras2<-raster('fileB')
###############################################################################
# funzione package SpatialEco
comb=spatialEco::combine(stack(ras1,ras2))
tablecombine=comb@data@attributes
XLConnect::writeWorksheetToFile("table_combine_ES_A.xls",tablecombine,"tabella")
writeRaster(comb,filename="conbination_A.tif",format="GTiff")
###############################################################################
# procedura
# We coerce the rasters to an sp class pixels object. Note that I am stacking the rasters so they will be combined into a single object. The columns represent the pixel values of each raster in the stack and each row is a pixel.
r <- as(stack(ras1,ras2), "SpatialPixelsDataFrame")
head(r@data)
# Now, we simply use something like paste to combine all possible combinations at the pixel level. You can check the unique combinations by using unique.
r@data <- data.frame(value=as.numeric(factor(paste(r@data[,1],r@data[,2], sep=""))), r@data)
head(r@data)
sort(unique(r@data$value))
# Subset to a value to validate single combinations
r@data[r$value == unique(r$value)[1],]
# This is how to structure the data in R for analytical purposes. However, if you would like a summary that resembles the
# ESRI table that results from combine you can operate on the data.frame in the sp object.
tablecombine=subset(as.data.frame(table(r@data)), Freq != 0)
XLConnect::writeWorksheetToFile("table_combine_ES_B.xls",tablecombine,"tabella")
# This sp object can also be coerced back to raster by simply using stack.
rfin <- stack(r)
writeRaster(rfin,filename="conbination_ES_B.tif",format="GTiff")
#######################################################################################
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment