How to extract rasters and points? - r

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)`

Related

How to mask a raster using SpatialPolygonsDataFrame object?

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,])

How can I clip a shapefile to my raster using R?

I am trying to mask a raster to a shapefile boundary, but I am getting an error. How can I correctly perform this mask?
The raw data can be found here, entitled "data_for_question.txt." It is formatted so that users can copy and paste (from the web app) the text directly into an R window and generate a data frame. Otherwise, if one doesn't want to generate the data, the output raster (example_raster.tif) and shapefile (field_boundary.shp) can both also be found in the same link.
Here is what I have tried:
#Import necessary libraries
library(pacman)
p_load(sf,
spatstat,
maptools,
tidyverse,
ggplot2,
gstat,
sp,
rgdal,
raster,
spdep)
#Read shapefile
shp <- st_read("field_boundary.shp")
#Generate data to run interpolation on and project it to the desired CRS
data_sp <- SpatialPointsDataFrame(coords,
data[, c("OM", "data2")],
proj4string = CRS('+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs'))
#Perform an IDW interpolation:
grd <- SpatialPixels(SpatialPoints(makegrid(data_sp, n=10000)), proj4string = proj4string(data_sp)) #Generate grid for interpolation
plot(grd)
interp <- idw(formula = OM ~ 1, data_sp, grd, idp = 0.5, nmax = 12)
plot(interp) #Makes for a very pretty picture!
#Convert to raster
rast <- raster(interp)
plot(rast)
shp <- st_transform(shp, crs(rast))
#Crop and mask the raster
crop_rast <- crop(rast, shp)
crop_om <- mask(crop_rast, mask = shp)
The error occurs here:
Error in h(simpleError(msg, call)) :
error in evaluating the argument 'x' in selecting a method for function 'addAttrToGeom': sp supports Z dimension only for POINT and MULTIPOINT.
use `st_zm(...)` to coerce to XY dimensions

Get Adjacency matrix for Polygons in GeoJSON using R

I've got a set of polygons in the GeoJSON file. They're neighborhoods in Boston. I would like to produce an adjacency matrix in CSV format, where element j,j is 1 if district i is adjacent to district j (i.e. they are touching).
I found a code in R on the internet and used for my data set (Uber Movement Dataset) as folows:
library(rgeos)
library(rgdal)
polys <- readOGR("D:/boston_taz.json")
adj <- gTouches(polys, byid = TRUE)
and got the following error:
> library(rgeos)
> library(rgdal)
> polys <- readOGR("D:/boston_taz.json")
OGR data source with driver: GeoJSON
Source: "D:\boston_taz.json", layer: "boston_taz"
with 2728 features
It has 7 fields
> adj <- gTouches(polys, byid = TRUE)
Error in RGEOSBinPredFunc(spgeom1, spgeom2, byid, "rgeos_touches") :
rgeos_binpredfunc: comparison failed
As I'm new to R, what's the issue and how do I export the resulting matrix to .csv format?
I used a zero-width buffer to clean up the topology problems in R and my problem is solved.
library(rgeos)
library(rgdal)
polys <- readOGR("D:/boston_taz.json")
polys2 <- gBuffer(polys , byid=TRUE, width=0)
adj <- gTouches(polys2, byid = TRUE, returnDense=TRUE, checkValidity=TRUE)
write.csv(adj ,"adj.csv")

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)

Resources