How to mask a raster using SpatialPolygonsDataFrame object? - polygon

I would like to mask a raster using all the polygons contained in a "SpatialPolygonsDataFrame" object.
Up until now i tried this:
r=raster("myraster.asc")
Then I got my SpatialPolygonsDataFrame (called "vor_spdf") object with a list of 6 Polygons, so I runned:
typeof(vor_spdf) # It results in [1] "S4"
r1=crop(r,extent(vor_spdf))
r2=mask(r1,vor_spdf#polygons[[1]]) #Trying to mask the raster on the geometry of the first polygon
This is the error... Error in (function (classes, fdef, mtable) : unable to find an inherited method for function ‘mask’ for signature ‘"RasterLayer", "Polygons"’
Do you have any suggestion on how to handle this?
Thank you

Example data
library(raster)
library(terra)
p <- shapefile(system.file("external/lux.shp", package="raster"))
r <- rast(system.file("ex/elev.tif", package="terra")) |> raster()
Solution
m <- mask(r, p[1,])
But you are using outdated packages. You might be better off using "terra" instead.
library(terra)
v <- vect(system.file("ex/lux.shp", package="terra"))
r <- rast(system.file("ex/elev.tif", package="terra"))
m <- mask(r, v[1,])

Related

How to extract rasters and points?

I am working on R and creating prediction maps. In my data, I have the location coordinates.
How to extract my rasters and points?
library(randomForest)
library(caret)
library(raster)
library(raster)
library(rgdal)
##-----load data
data <- read.csv("0.10.coordinates.csv",sep=";", header = TRUE)
raster(swi.tif)
rsp.1<-raster("rsp.tif")
twi.1<-raster("twi.tif")
swi.1<-raster("swi.tif")
###load csv of 0-10cm sand,silt and clay %'s and lat/long (x,y) (in E: drive RF folder)
xy<-read.csv("0.10.coordinates.csv")
plot(swi.1)
plot(twi.1)
plot(swi.1)
plot(rsp.1)
stack(swi.1,rsp.1,twi.1,xy)
topo.brick<-brick(rsp.1,swi.1,twi.1,xy)
brick(rsp.1,twi.1,swi.1,data)
df<-extract(data,rsp.1,twi.1,swi.1)`
Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘extract’ for signature ‘"data.frame", "RasterLayer"’
take a look at?raster::extract to see what inputs are required and in what order. In any case, you should create a reproducible example..
However, here an example with dummy data:
library(raster)
# with raster -------------------------------------------------------------
r <- s <- t <- raster()
r[] <- 1:ncell(r)
s[] <- sample(1:10,ncell(s),replace = T)
t[] <- runif(ncell(t))
stacked <- stack(r,s,t)
#points
xy <- cbind(-50, seq(-80, 80, by=20))
#extract
ex <- extract(stacked,xy, df=TRUE)
If the extraction takes too long, check out the terra::extract or even better a exactextractr::exact_extract.
See Elia's example, but from what I gather from your code you should be able to do
library(raster)
xy <- read.csv("0.10.coordinates.csv")
s <- stack("rsp.tif", "twi.tif", "swi.tif")
d <- extract(s, xy)`

How to select one point per raster grid cell?

I have a point shapefile ("search_effort.shp") that is highly clustered and an NDVI raster (resolution in m: 30.94948, 30.77829). I would like to subset my search_effort.shp by selecting 1 point per raster grid cell and create a new search_effort shapefile. I am using R version 4.0.3
I think I could have used Package ‘gridsample’ (in 'raster' v1.3-1), but it was removed from the CRAN repository and I would prefer not to use the archived version. Is there another way to do this in R?
I have also tried sample.grid but I do not know how to specify my raster as the grid, and have tried the following:
# NDVI raster to be used as the reference extent
NDVI_extent <-readGDAL('C:/Model_layers/NDVI.tif')
# Load the file names
layername <- "SearchEffort"
# Read in the shapefile
search_effort <- readOGR(dsn= ".", layer = layername)
plot(search_effort)
# Set the reference extent
r <- raster(NDVI_extent)
# Extract coordinates from the shapefile
search_effort#coords <- search_effort#coords[, 1:2]
#Subset points
sample.grid(search_effort, cell.size = c(30.94948, 30.77829), n = 1)
I get the following error:
"Error in validObject(.Object) : invalid class “GridTopology” object: cellsize has incorrect dimension."
I get the same error regardless of the cell.size I specify.
Example data
library(raster)
r <- raster(res=30)
values(r) <- 1:ncell(r)
x <- runif(1000,-180,180)
y <- runif(1000,-90,90)
xy <- cbind(x, y)
Solution
library(dismo)
s <- gridSample(xy, r, n=1)
Illustration
plot(as(r, "SpatialPolygons"))
points(s, col="red")
points(xy, cex=.1, col="blue")

Extract WORLDCLIM data using R for a single country

I want to extract world climate data for minimum and maximum temperature for only one country India using R and save it as a data set (to use with my own data-set that contains crop yields at the district level).
I have gone through several posts and can see that this can be done easily in R, however the posts that I have tried to follow are a bit different in terms of the commands or sequences and I am getting confused.
(https://gis.stackexchange.com/questions/259478/worldclim-data-na-for-my-coordinates, https://gis.stackexchange.com/questions/227585/using-r-to-extract-data-from-worldclim
What I have tried to use is as follows.
library(raster)
library(sp)
r<- getData('CMIP5', var='tmin', res=10, rcp=45, model='HE', year=70)
r <- r[[c(1,12)]]
values <- extract(r,points)
df <- cbind.data.frame(coordinates(points),values)
head(df)
However, I can run only the first two lines and the line values
<- extract(r,points) gives the error Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘extract’ for signature ‘"RasterStack", "function"’
Any suggestions?
Here is the solution for it
library(raster)
library(sp)
library(rgeos)
library(rgdal)
library(sf)
r<- getData('CMIP5', var='tmin', res=10, rcp=45, model='HE', year=70)
#Using Zonal statistics
poly <- shapefile("Provide_your_drive_name" e.g. "F:\\Kriging in R\\India Shape files\\2011_Dist.shp")
plot(poly)
#This will take considerable time
ex <- extract(r, poly, fun='mean', na.rm=TRUE, df=TRUE, weights = TRUE)
write.csv(cbind(poly$DISTRICT,ex),"Worldclim.csv", row.names = F)
# using centroids
nc <- st_read(dsn="Provide_your_drive_name" e.g. "F:\\Kriging in R\\India Shape files", layer="2011_Dist")
# just view the attributes & first 6 attribute values of the data
head(nc)
sp_cent <- gCentroid(as(nc, "Spatial"), byid = TRUE)
values <- extract(r,sp_cent)
write.csv(cbind(as.data.frame(nc$DISTRICT),as.data.frame(values)),"Worldclim_centroids.csv", row.names = F)

Convert raster to im object

I would like to convert a raster to an im object but have so far been unable to do so.
Here is a reproducible example:
Create raster layer and add data to it:
r.toy <- raster(ncol=40, nrow=20)
r.toy[] <- rnorm(n=ncell(r.toy))
Plot the raster:
plot(r.toy)
Convert to image:
r.toy.im <- as.im(r.toy)
I receive the following error:
Error in as.im.default(r.toy) : Can't convert X to a pixel image
You just need to load the maptools package which can convert many spatial
formats in R:
library(raster)
library(spatstat)
library(maptools)
r.toy <- raster(ncol=40, nrow=20)
r.toy[] <- rnorm(n=ncell(r.toy))
r.toy.im <- as.im(r.toy)
plot(r.toy.im)
Created on 2018-11-11 by the reprex package (v0.2.1)

R - Crop for JPEG Impages

I'm trying to plot a image (a flag) on a map using raster layers and
# Load packages
library(maptools)
library(raster)
library(jpeg)
# Read in a jpeg and convert to raster
usa.flag <- as.raster(readJPEG(".../usa.jpg"))
# Get spacial image of map
data("wrld_simpl")
usa.map <- subset(wrld_simpl, NAME == "United States")
When I try to crop, I get an error:
usa.sub <- crop(usa.flag, extent(usa.map))
Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘crop’ for signature ‘"raster"’
But I can't figure out what I'm missing about the use of crop().

Resources