Skip to content

Instantly share code, notes, and snippets.

@mkborregaard
Created January 22, 2019 13:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mkborregaard/acd715b96e15fada440ed0b076dafc28 to your computer and use it in GitHub Desktop.
Save mkborregaard/acd715b96e15fada440ed0b076dafc28 to your computer and use it in GitHub Desktop.
library(raster)
#1 open a raster file as memory-mapped on-disk object
bio1 <- raster("bio1.bil") # the 1st bioclimatic variable from the Chelsa dataset
#2 get the projection
proj4string(bio1)
#3 plot it
plot(bio1)
#4 plot part of it
plot(bio1, xlim = c(-80,-35), ylim = c(-60, 15))
#5 extract part of the raster based on a rectangular window
samerica <- crop(bio1, extent(-80, -35, -60, 15))
plot(samerica)
#6 extract part of it based on a shapefile polygon
library(rgdal)
cnt <- readOGR("~/Documents/Courses/R data analysis/Data/Countries", "CNTRY92") # get all countries as polygons
braz <- subset(cnt, NAME == "Brazil") # extract brazil
plot(braz, add = T, border = "red")
brarast <- mask(samerica, braz)
#7 plot that newly extracted raster with some spatial points
plot(brarast)
ex <- extent(braz)
sp <- SpatialPoints(cbind(runif(50, ex[1], ex[2]), runif(50, ex[3], ex[4])))
plot(sp, add = T, col = "red")
#8 extract the raster's value under these points
values <- extract(brarast, sp)
#9 aggregate the raster to a coarser resolution
bra_coarse <- aggregate(brarast, 9, mean)
#10 use the raster as a standard matrix
brarast[100:120, 150:180] * 2 # doesn't quite work in R as this is now a Vector
#11 apply image windowing functions to the raster
window_mean <- focal(bra_coarse, matrix(rep(1,9), nrow = 3), mean)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment