How can I clip a shapefile to my raster using R? - 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

Related

adehabitatHR: In proj4string(xy) : CRS object has comment, which is lost in output

I'm trying to create kernel density map from point data (available as .shp and .csv) for 5 different species,at global scale. For some individual, there is only one point locality, but for the others there are few to several points. I will use the output map of KDE to identify the hotspots. I'm using adehabitatHR to produce KDE map as below:
library("sp")
library("rgdal")
library("rgeos")
# load the data layer
data.Points <- readOGR("D:/FGH/merged","data")
#Defining a CRS with sp cause coordinate reference systems are represented differently when PROJ < 6 and PROJ >= 6.
crs_wgs84 <- CRS(SRS_string = "EPSG:4326") # WGS 84 has EPSG code 4326
class(crs_wgs84)
wkt_wgs84 <- wkt(crs_wgs84)
cat(wkt_wgs84)
#Set the CRS of a Spatial* object in sp
data.Points2 <- data.Points
coordinates(data.Points2) <- ~ x + y
slot(data.Points2, "proj4string") <- crs_wgs84
library(raster)
library(adehabitatHR)
# Define the Domain
x <- seq(-179.8300, 179.2461, by=0.083333333) # resolution is the pixel size you desire
y <- seq(-42, 52, by=0.083333333)
xy <- expand.grid(x=x,y=y)
coordinates(xy) <- ~x+y
gridded(xy) <- TRUE
class(xy)
# runs the kernel density estimation
kde.output <- kernelUD(data.Points2, h="href", grid = xy)
However, I got this error when either using .shp or .csv input file:
In proj4string(xy) : CRS object has comment, which is lost in output
I went through https://cran.r-project.org/web/packages/sp/vignettes/CRS_warnings.html and https://inbo.github.io/tutorials/tutorials/spatial_crs_coding/, and did some modifies as above but the warning message is remained!
So, how can I get rid of this warning message? Is there any wrong command used?
Thanks for your help.

R raster function will not accept crs in WKT format

I'm trying to generate a raster and assign it a CRS projection. However, my CRS is in the new WKT format, and the raster() function is requiring me to provide a proj4string. Here's my code so far:
library(sf)
library(raster)
crs_dem <- st_crs(
'PROJCS["NAD_1983_2011_StatePlane_California_II_FIPS_0402",
GEOGCS["GCS_NAD_1983_2011",
DATUM["D_NAD_1983_2011",
SPHEROID["GRS_1980",6378137.0,298.257222101]],
PRIMEM["Greenwich",0.0],
UNIT["Degree",0.0174532925199433]],
PROJECTION["Lambert_Conformal_Conic"],
PARAMETER["False_Easting",2000000.0],
PARAMETER["False_Northing",500000.0],
PARAMETER["Central_Meridian",-122.0],
PARAMETER["Standard_Parallel_1",38.33333333333334],
PARAMETER["Standard_Parallel_2",39.83333333333334],
PARAMETER["Latitude_Of_Origin",37.66666666666666],
UNIT["Meter",1.0]]')
ext <- extent(1895000, 1935000, 579500, 616500)
grid <- raster(ext, resolution = c(40,40), crs = crs(dem))
The code above generates a raster with crs = NA. I've also tried assigning it with crs(grid)<- and projection(grid)<- with no luck. How can I get my specific CRS file to associate with this raster??
#slamballais's answer did the trick! I also found another (slightly less clean) method through trial and error last night, so here are both solutions.
Option 1:
test <- sp::CRS(crs_dem$input)
grid <- raster(ext, resolution = c(40,40), crs = test)
Option 2:
library(dplyr)
aoi <- ext %>%
as('SpatialPolygons') %>%
st_as_sf %>%
st_set_crs(crs_dem)
grid <- raster(ext, resolution = c(40,40), crs = projection(aoi))
raster expects text, so if you have a wkt format crs, you can use that directly. There is no need to create a more complex object.
crs_dem <- 'PROJCS["NAD_1983_2011_StatePlane_California_II_FIPS_0402",
GEOGCS["GCS_NAD_1983_2011", DATUM["D_NAD_1983_2011", SPHEROID["GRS_1980",6378137.0,298.257222101]],
PRIMEM["Greenwich",0.0], UNIT["Degree",0.0174532925199433]],
PROJECTION["Lambert_Conformal_Conic"], PARAMETER["False_Easting",2000000.0],
PARAMETER["False_Northing",500000.0], PARAMETER["Central_Meridian",-122.0],
PARAMETER["Standard_Parallel_1",38.33333333333334], PARAMETER["Standard_Parallel_2",39.83333333333334],
PARAMETER["Latitude_Of_Origin",37.66666666666666], UNIT["Meter",1.0]]'
library(raster)
r <- raster(crs=crs_dem)
or, if you start with an sf object
r <- raster(crs=crs_dem$input)

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

r sp/maps/maptools libraries: Map of annual solar irradiation in R

I am trying to plot annual solar irradiation data with different color on a world map. I am using R programming for the purpose.
The data I am using is from http://eosweb.larc.nasa.gov/sse/global/text/global_radiation
First, I am converting this data to a spatial dataframe and also the world map that is obtained using map(world) function to a spatial form.
I am following an example for practice from https://www.r-bloggers.com/maps-of-solar-radiation/
for plotting my code is as follows. I believe the code is completely correct but I am getting some errors
library(sp)
library(maps)
library(mapdata)
library(maptools)
library(RColorBrewer)
nasafile <- 'http://eosweb.larc.nasa.gov/sse/global/text/global_radiation'
nasa <- read.table(file=nasafile, skip=13, header=TRUE)
proj <- CRS('+proj=latlon +ellps=WGS84')
coords = nasa[,2:1]
datos = nasa[,3:15]
nasaSP <- SpatialPixelsDataFrame(points=coords, data=datos, proj4string=proj)
world <- map("world", plot=FALSE)
llCRS <- CRS("+proj=latlong +ellps=WGS84")
world_sp <- map2SpatialLines(world, proj4string=llCRS)
colar_sp = colorRampPalette(c("snow1", "thistle1", "plum2", "red4"))
map_sp <- list('sp.lines', world_sp)
spplot(nasaSP["Ann"], col.regions=color_sp, sp.layout=map_sp)
The main errors I'm getting are related to projections. I believe the way I have added them in code is correct and have seen many examples in which they have been written the same way. Please have a look at these errors and lemme know how can I make this code work.
Thanks in Advance!
Errors:
Error in CRS("+proj=latlon +ellps=WGS84") :
northings must follow eastings: +proj=latlon +ellps=WGS84
Error in checkSlotAssignment(object, name, value) :
assignment of an object of class “function” is not valid for slot ‘proj4string’ in an object of class “Spatial”; is(value, "CRS") is not TRUE
Error in CRS("+proj=latlong +ellps=WGS84") :
northings must follow eastings: +proj=latlong +ellps=WGS84
Error in initialize(value, ...) : object 'llCRS' not found
I found two problems with your code:
1) you're using CRS wrongly. In CRS("+proj=latlong...) instead of latlong you must use longlat (see ?CRS);
2) When you plot your map, your color_sp is called colar_sp.
Here is your code with the corrections:
library(sp)
library(maps)
library(mapdata)
library(maptools)
library(RColorBrewer)
nasafile <- 'http://eosweb.larc.nasa.gov/sse/global/text/global_radiation'
nasa <- read.table(file=nasafile, skip=13, header=TRUE)
proj <- CRS("+proj=longlat + datum=WGS84")
coords = nasa[,2:1]
datos = nasa[,3:15]
nasaSP <- SpatialPixelsDataFrame(points=coords, data=datos, proj4string=proj)
world <- map("world", plot=FALSE)
llCRS <- CRS("+proj=longlat + datum=WGS84")
world_sp <- map2SpatialLines(world, proj4string=llCRS)
color_sp = colorRampPalette(c("snow1", "thistle1", "plum2", "red4"))
map_sp <- list('sp.lines', world_sp)
spplot(nasaSP["Ann"], col.regions=color_sp, sp.layout=map_sp)

Resources