Converting a raster object to an im object in R - r

I am trying to convert a raster object to an .im object for use with a point process model in the spatstat package in R. I begin by creating the raster from a tiff file using the raster() package. No problems there. I then proceed by cropping the raster according to a given extent. Again, no problem there. I then specify a spatial window (owin) defined using the same extent. Still no problems. When I then proceed to the final step of converting the raster to the im object using as.im(), the function runs and the new im object is created, but it has somehow lost the pixel information that was contained in the original raster such that each pixel now has the same value in the im object. Any help or suggestions would be most appreciated. Thanks very much.
The date file used is at this link: https://www.dropbox.com/s/n67djm3n0tfa6sx/MGVF_2001_30_arc_sec.tif?dl=0
And the R code is as follows:
library(raster)
library(spatstat)
# First set the geographic extent we'll be using
e <- extent(-20, 60, -40, 35)
# Then read in the Maximum Green Vegetation Fraction tiff and crop it
mgvf <- raster("MGVF_2001_30_arc_sec.tif")
mgvf.2001.africa <- crop(mgvf, e)
# Now let's create a window for in spatstat
SP.win <- as(e, "SpatialPolygons")
W <- as(SP.win, "owin")
# Finally, we create the .im object
mgvf.img <- as.im(X = "mgvf.2001.africa", W = W)
# Notice, there are no errors thrown. However, compare the plots below and see the loss of information:
plot(mgvf.2001.africa)
plot(mgvf.img)
Incidentally, I have tried the above as shown as well as trying to replace the NAs in the raster prior to converting to im. The result is the same. Thanks.

Related

vector shp point to ppp spatstat with polygon windows

I always get error to this
# polygon that to be window
neighborhoods <- st_read("neighborhoods/neighborhoods.shp")
# convert CRS to planar projection as recommended by (https://stackoverflow.com/questions/59597078/use-sf-polygon-object-as-window-in-spatstat)
neighborhoods_3857 <- st_transform(neighborhoods, crs = 3857)
# point that to be PPP spatstat
trees <- st_read("trees/trees.shp")
# convert to planar projection
trees_3857 <- st_transform(trees, crs = 3857)
The problems, the "trees_3857" doesn't have dataframe columns that represent in EPSG3857 coordinates, so Feature column of "trees_3857" doesn't have x and y columns that respect to EPSG 3857
q <- ppp(x=?, y=?, win=neighborhoods_3857)
what I have done but error
z <- as.ppp(trees_3857, win=neighborhoods_3857)
Error in as.ppp.sf(trees_3857, win = neighborhoods_3857): unused argument (win = neighborhoods_3857)
Traceback:
You can get the data freely from datacamp.
https://assets.datacamp.com/production/repositories/738/datasets/96a72364e69d872645038b3a6dc7c0dbcb1114d6/neighborhoods.zip
https://assets.datacamp.com/production/repositories/738/datasets/08a3684dc4d538d59ba051a64a834166883ab5d1/trees.zip
Although you're wanting to transform your data into an object of class "ppp" from the spatstat package, the error message indicates that the problem originated in the function as.ppp.sf which is part of the sf package.
The error message says unused argument: win which means that the function did not recognise or accept the argument win.
Just to make it more challenging, the function as.ppp.sf is not documented and is not visible... By typing sf:::as.ppp.sf we can see the function body and figure out that the function has only one argument, so it does not accept any window information.
This is not the way the generic function as.ppp is designed to work in the spatstat package, so if you looked for help(as.ppp) in spatstat, it's not surprising that you got confused.
The best solution is (as Ege Rubak suggests) to convert the point coordinates and then add the window information:
z <- as.ppp(trees_3857)
Window(z) <- as.owin(neighborhoods_3857)
The conversions as.ppp and as.owin will be executed using code in sf so I can't guarantee they will work. The assignment Window(z) <- will be executed in spatstat code, see help("Window<-.ppp").

How can I overlay Sentinal 2 data with shapefiles in R?

I need to extract Sentinal 2 data for NDVI for specific study sites. I used RGIS tools and followed the reference manual https://cran.r-project.org/web/packages/RGISTools/RGISTools.pdf . I was able to obtain and plot the time series for NDVI.
Now I have to do the same procedure for my study area. I have a shapefile for my area which is accessible here, https://gis.utah.gov/data/boundaries/zip-codes/. It looks like that the shapefile needs to be converted into raster or sf type object before using it. I used st_as_sf to convert shapefile to sf but I receive the following error in senSearch function,
Error in if (as.integer(json$feed$opensearch:totalResults) > 0) { :
argument is of length zero
It is my first time working with such data, any help is appreciated.
It looks like you try to search using the extent argument. This argument only accepts spatial objects projected as lonlat projections. You can use the region argument with any spatial obj (sp, sf, or raster).
Here you have an example with your region:
library(RGISTools)
library(rgdal)
shp<-readOGR("ZipCodes_shp/ZipCodes")
plot(shp)
senres<-senSearch(startDate = as.Date("2018210", "%Y%j"),
endDate = as.Date("2018215", "%Y%j"),
platform = "Sentinel-2",
region = shp,
product = "S2MSI1C",
username="user",
password="pass")

How to create moving window filter of semivariogram outputs in R using focal area function?

I'm trying to create a raster filled with semivariogram outputs such as the sill and range of an area which describes the spatial autocorrelation. I wanted to try using the focal function in R as a way to scan an area, and the variogram function from gstat package to calculate sill and range.
I've tried the following code, but there are issues with the function.
library(raster)
library(gstat)
r <- raster()
r[] <- 1:ncell(r)
ra <- aggregate(r, 5)
plot(ra)
v<-variogram(layer~1,as(ra,"SpatialPixelsDataFrame"))
plot(v)
f = fit.variogram(v, vgm("Sph"))
f$psill[2]
f$range
var.sill<-function(x){
names(x)<-c("layer")
v<-variogram(layer~1,as(x,"SpatialPixelsDataFrame"))
f = fit.variogram(v, vgm("Sph"))
f$psill[2]
}
var.sill(ra)
# 374758092
## in a window surrounding each focal cell
rpsill <- focal(ra, w=matrix(1/225, ncol=15, nrow=15), fun=var.sill)
plot(rpsill)
The error states," Error in as(x, "SpatialPixelsDataFrame") :
no method or default for coercing “numeric” to “SpatialPixelsDataFrame” "
I would appreciate any help with this or if there is another way to potential create these new rasters please let me know too.
Thank you.

Query raster brick layer based on another raster in R

I have a NetCDF file of global oceanographic (OmegaA) data at relatively coarse spatial resolution with 33 depth levels. I also have a global bathymetry raster at much finer resolution. My goal is to use get the seabed OmegaA data from the NetCDF file, using the bathymetry data to determine the desired depth. My code so far;
library(raster)
library(rgdal)
library(ncdf4)
# Aragonite data. Defaults to CRS WGS84
ncin <- nc_open("C:/..../GLODAPv2.2016b.OmegaA.nc")
ncin.depth <- ncvar_get(ncin, "Depth")# 33 depth levels
omegaA.brk <- brick("C:/.../GLODAPv2.2016b.OmegaA.nc")
omegaA.brk <-rotate(omegaA.bkr)# because netCDF is in Lon 0-360.
# depth raster. CRS WGS84
r<-raster("C:/....GEBCO.tif")
# resample the raster brick to the resolution that matches the bathymetry raster
omegaA.brk <-resample(omegaA.brk, r, method="bilinear")
# create blank final raster
omegaA.rast <- raster(ncol = r#ncols, nrow = r#nrows)
extent(omegaA.rast) <- extent(r)
omegaA.rast[] <- NA_real_
# create vector of indices of desired depth values
depth.values<-getValues(r)
depth.values.index<-which(!is.na(depth.values))
# loop to find appropriate raster brick layer, and extract the value at the desired index, and insert into blank raster
for (p in depth.values.index) {
dep.index <-which(abs(ncin.depth+depth.values[p]) == min(abs(ncin.depth+depth.values[p]))) ## this sometimes results in multiple levels being selected
brk.level <-omegaA.brk[[dep.index]] # can be more than on level if multiple layers selected above.
omegaA.rast[p] <-omegaA.brk[[1]][p] ## here I choose the first level if multiple levels have been selected above
print(paste(p, "of", length(depth.values.index))) # counter to look at progress.
}
The problem: The result is a raster with massive gaps (NAs) in it where there should be data. The gaps often take a distinctive shape - eg, follow a contour, or along a long straight line. I've pasted a cropped example.
enter image description here
I think this could be because either 1) for some reason the 'which' statement in the loop is not finding a match or 2) a misalignment of the projections is created which I've read can happen when using 'Rotate'.
I've tried to make sure all the extents, resolutions, number of cells, and CRS's are all the same, which they seem to be.
To speed up the process I've cropped the global brick and bathy raster to my area of interest, again checking that all the spatial resolutions, etc etc match - I've not included those steps here for simplicity.
At a loss. Any help welcome!
Without a reproducible example, this kind of problems is hard to solve. I can't tell where your problem is but I'll present to you the approach I would try. Maybe it's good, maybe it's bad, I don't know but it may inspire you to find a way to go around your problem.
To my understanding, you have a brick of OmegaA (33 layers/depth) and a bathymetry raster. You want to get the OmegaA value at the bottom of the sea. Here is how I would do:
Make OmegaA raster to the same resolution and extent to the bathymetry one
Transforme the bathymetry raster into a raster brick of 33 three layers of 0-1. e.g. If the sea bottom is at 200m for one particular pixel, than this pixel on all depth layer other than 200 is 0 and 1 for the 200. To program this, I would go the long way, something like
:
r_1 <- r
values(r_1) <- values(r)==10 # where 10 is the depth (it could be a range with < or >)
r_2 <- r
values(r_2) <- values(r)==20
...
r_33 <- r
values(r_33) <- values(r)==250
r_brick <- brick(r_1, r_2, ..., r_33)
then you multiple both your raster bricks. They have the same dimension, it should be easy. The output should be a raster brick of 33 layers with 0 everywhere where it isn't the bottom of the sea and the value of OmegaA anywhere else.
Combine all the layer of the brick obtained previously into a simple raster with a sum.
This should work. If you have problem with dealing with raster brick, you could make the data into base R arrays, it could be simpler.
Good luck.

How to do the raster package identify all bands (layers) of a image?

i'm trying to use de raster package to read a multilayer (multiband) image (ENVI format [.hdr]) that have 160 values of refletance and 160 values of wavelength per pixel, but when i use the code that i developed, the program returns only 1 band and the refletance value associated.section1=raster("./x")
getValuesBlock(section1, row=1, nrows=1, col=1, ncol=1 )
Well, from the looks of it , it seems to me that you want to read a particular band of a raster file into the R environment ,
require("raster")
dir.file<-"dir/file.hdf"
#Reading the first band of the raster image
band1<-raster(dir.file,band=1)
Change the values of theband parameter of the raster() method to control the band id of your raster.
Hope this helps
To create a multi-layer Raster object, you should use the brick function if they layers are in one file, or the stack function if they are in multiple files.
library(raster)
# example file name
f <- system.file("external/rlogo.grd", package="raster")
b <- brick(f)
b
# a single cell value
b[1]

Resources