Convert raster to im object - raster

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)

Related

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

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: Handling of sf objects in raster package

Previously I was using raster::crop and raster::mask with shapefiles of class Spatial*, read in using rgal::readOGR.
I am just "upgrading" my scripts to use sf for reading and manipulating polygons.
raster::crop
raster::crop expects an 'extent' object as second argument. Up to now, this was automatically extracted from a Spatial* object. So I could just do raster::crop(raster, polygon).
To get this working with an sf object, I can call raster::crop(raster, as.vector(st_bbox(polygon))) as an ugly workaround.
raster::mask
Since raster::mask clearly expects a Raster* object or a Spatial* object the only solution was to coerce the sf object back to a Spatial* object using as("Spatial").
I assume this problem generalized to all raster functions? Did I overlook something or is it just the case that the raster package does not (yet) work with sf objects?
For future reference, it works now! Here's some slightly modified example code from ?crop, tested with raster version 2.6-7 which has been released on 2017-11-13.
library(raster)
library(sf)
r <- raster(nrow=45, ncol=90)
r[] <- 1:ncell(r)
# crop Raster* with sf object
b <- as(extent(0, 8, 42, 50), 'SpatialPolygons')
crs(b) <- crs(r)
b <- st_as_sf(b) # convert polygons to 'sf' object
rb <- crop(r, b)
# mask Raster* with sf object
mb <- mask(r, b)

Add curves to raster map?

would it be possible to add isoclines or something like "filled.contour" to a raster map?
E.g. to a Bioclim variable? (RasterLayer)
# Download Bioclim data
library(dismo)
tmin_06<-getData("worldclim", var="tmin", res=0.5, lon=10, lat=70)
# plot tmin
plot(tmin$tmin1_06)
And then add e.g. filled.contour {graphics}
I can’t seem to extract the correct values from the RasterLayer and get an error massage:
"cannot coerce type 'S4' to vector of type 'double'"
Or what would you use to illustrate the direction of change in a map like this for temperature, or for equidistance in an elevation map?
Thank you!
Daniel
Here are two approaches:
# example data
f <- system.file("external/test.grd", package="raster")
r <- raster(f)
plot(r)
contour(r, add=TRUE)
# or
filledContour(r)

how to run savitzkey Golay filter on time series NDVI image

Is there any way to run savitzky golay filter on time series NDVI image in R. I had already tried with the following code given in the package 'signal';
sg <- sgolayfilt(timeseries,3,5).
But it returns following error;
Error in if (all(is.na(x))) return(x) :
argument is not interpretable as logical
The file "timeseries" here is a stacked raster NDVI image. Can anybody help me in this regard.
Thank you for your kind help.
I have 12 raster layers, then I stack them into raster stack
###### Load needed package
library(raster)
library(sp)
library(rgdal)
library(tiff)
library(ggplot2)
library(maptools)
library (zoo)
library (signal)
library(timeSeries)
NDVI_STACK <- stack (jan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec)
fun <- function(x) {
v=as.vector(x)
z=substituteNA(v, type="mean") # from package timeSeries
NDVI.ts2 = ts(z, start=c(2005,1), end=c(2005,12), frequency=12)
x=sgolayfilt(NDVI.ts2, p=2, n=5, ts=30)
NDVI.filtered <- calc(NDVI_STACK, fun, progress='text') #raster calculation process ......
You may need to adjust p and n depending on your data. BTW, n must be odd dimension and, from my experience, p is less than n
: This link is very useful
I hope it could help:)

Resources