Spatial operations with curvilinear data in program stars for R - r

I'm new to the package stars for R and am trying to do basic spatial operations with curvilinear data. I am using netCDF climate data. I am able to read the netcdf into r along with a shapefile I would like to use to specify the area in which I want to conduct analyses. I have tried to crop the file directly using st_crop() but receive the following error:
Warning message:
In st_crop.stars(test, wrst) : crop only crops regular grids
I then tried to warp the stars object using code like this:
warp <- test %>% st_set_crs(3338) %>% st_warp(st_as_stars(st_bbox(), dx = 2))
but I get this error:
Error in colrow_from_xy(pts, x, NA_outside = TRUE) :
colrow_from_xy not supported for curvilinear objects
Do I need to 'flatten' my curvilinear grid in order to conduct analyses in a given region? If so, how do I do that? Or, conversely, if I am able to conduct operations like st_crop() or the equivalent of raster operations calc() or stackApply() using a curvilinear grid, can someone point me in the right direction? Thanks so much.

Well I figured it out and it was quite simple. I was able to subset the stars object using the shapefile with this simple code: test[wrst]. No warping or resampling necessary.

Related

How to get raster file from a nested raster list produced by landscapemetrics package in R?

Package landscapemetrics can calculate area of each patch for a given raster file, shape of that patch and so on. I want to have not only tibble-frame with patch metrics calculated, but a new raster where each pixel within specific patch will have a value of the area of that patch, shape indicator and so on. We can do it with function spatialize_lsm() (it produces a Large list nested object with probably RasterObject objects within):
library(landscapemetrics)
plot(podlasie_ccilc) # this raster data is provided with package
podlasie.metrics.area <- spatialize_lsm(podlasie_ccilc, what = 'lsm_p_area') # creates a list
plot(podlasie.metrics.area) # produces an error...
How to get a desirable raster file with patch metrics from that list? I guess it is a question of raster package or something else, since landscapemetrics documentation tells nothing about this step.
I not that this data and new raster do not have resolution of the pixel like in meters (30, 30 for Landsat satellite image, for example). So we cannot plot the new raster produced:
podlasie.metrics.area[[1]]
plot(podlasie.metrics.area[[1]])
So I guess landscapemetrics cannot deal with such rasters, we can even use its function to check a suitability of the prior raster for patch discovering:
check_landscape(podlasie_ccilc)
Upd. I did it for the Landsat dataset with resolution 30, 30 and it produced patch area raster, but again I cannot open/show/save as raster it, because of the same error.
Package maintainer helps to solve a problem (yes, it is just related to the structure of list):
plot(podlasie.metrics.area[[1]]$lsm_p_area)

R: Clip a shapefile boundary out of a generated image

I generated an image of ordinary kriged predictions. I have a shapefile of a boundary line and I'd like to crop the ordinary kriged predictions in the shape of that shapefile.
This is the code I use to generate the image:
image(OK.pred,loc=grid,axes=F,useRaster=TRUE). I just want to clip an object out of the image -- when I plot them, they overlay perfectly.
It's almost identical to the issue here, https://gis.stackexchange.com/questions/167170/is-it-possible-to-clip-a-shapefile-to-an-image-in-r, but I'm relatively new to R and got totally lost with the netcdf file part.
I found a bunch of code on how to clip rasters, but I just can't figure out how to even save an image into a variable let alone transform it to a raster in order to clip it. Any help would be much appreciated!
OK.pred<-krige.conv(gambling.geo,coords = gambling.geo$coords, data=gambling.geo$data, locations=grid,krige=krige.control(obj.model=gambling.vario.wls))
ordinarykrig = image(OK.pred,loc=grid,axes=F,useRaster=TRUE)
Macau <- readOGR("MAC_adm0.shp")
x <- crop(?...)
Taken from http://leg.ufpr.br/geoR/tutorials/kc2sp.R:
You need to convert the kriging output to a Spatial object before you can pass it to mask(). The following should do it:
OK.pred<-krige.conv(gambling.geo,coords = gambling.geo$coords, data=gambling.geo$data, locations=grid,krige=krige.control(obj.model=gambling.vario.wls))
GT.s <- points2grid(SpatialPoints(as.matrix(grid)))
reorder <- as.vector(matrix(1:nrow(grid), nc=slot(GT.s, "cells.dim")[2])[,slot(GT.s, "cells.dim")[2]:1])
SGDF.s <- SpatialGridDataFrame(grid=GT.s, data=as.data.frame(OK.pred[1:2])[reorder,])
r<-raster(SGDF.s)
x<-mask(r, Macau)

Convert Spatial Lines to Spatial Polygons

Is there an easy way to convert a Spatial Lines into a Spatial Polygon object within R?
Reproducible Example
I have put together a reusable dataset here, which is downloaded from OpenStreetMaps through the overpass package. This extracts the locations of a few airports in South England:
devtools::install_github("hrbrmstr/overpass")
library(overpass)
library(raster)
library(sp)
# Write Query
query_airport <- '
(node["aeroway"="aerodrome"](50.8, -1.6,51.1, -1.1);
way["aeroway"="aerodrome"](50.8, -1.6,51.1, -1.1);
relation["aeroway"="aerodrome"](50.8, -1.6,51.1, -1.1);
);
out body;
>;
out skel qt;
'
# Run query
shp_airports <- overpass::overpass_query(query_airport, quiet = TRUE)
crs(shp_airports) <- CRS("+init=epsg:4326") # Add coordinates
shp_airports <- shp_airports[,1]
# Plot Results
plot(shp_airports, axes = T)
However, the data is of the class "SpatialLinesDataFrame". This really messes things up if you want to do any form of spatial joins or intersections, as it only acknowledges the edge of the region.
Potential Leads
I was exploring the use of SpatialLines2PolySet within the maptools package, but in my time exploring I produced nothing but error codes, so I didn't think there would be any worth including these within the question. There is some guidance about these functions here: https://rdrr.io/rforge/maptools/man/SpatialLines2PolySet.html
Notes
I have searched the web and SO to see find similar questions and struggled to find any questions directly referring to this. A lot seem to reference converting SpatialPoints -> SpatialLineDataFrames , but not SpatialLineDataFrames -> SpatialPolygonDataFrames. This question is similar but lacks any answers (or a reproducible dataset): Close a spatial line into a polygon using a shapefile
In addition, it seems strange that this would be difficult as it is something which can be done so easily in ArcGIS using the "Feature to Polygon" tool. This function requires no additional arguments specified and it works perfectly.
A way to solve the problem would be to use the library sf. After your query
library(sp)
library(raster)
library(sf)
sf_airports <- st_as_sf(shp_airports)
sf_airports_polygons <- st_polygonize(sf_airports)
shp_airports <- as(sf_airports_polygons, "Spatial") # If you want sp
class(shp_airports)

Google Maps vs. ggplot2/MarMap

Below is a JavaScript page I have created that allows me add and freely move markers on the map. From this map I can figure out the regions I am interested in.
Basically what I want to do is show the same map using ggplot2/MarMap with coastline indicators + bathymetry data. I am really just interested in getting bathymetry data per GPS location, basically getting negative/positive elevation per Lat+Long, so I was thinking if I can plot it then I should be able to export data to a Database. I am also interested in coastline data, so I want to know how close I am (Lat/Long) to coastline, so with plot data I was also going to augment in DB.
Here is the R script that I am using:
library(marmap);
library(ggplot2);
a_lon1 = -79.89836596313478;
a_lon2 = -79.97179329675288;
a_lat1 = 32.76506070891712;
a_lat2 = 32.803624214389615;
dat <- getNOAA.bathy(a_lon1,a_lon2,a_lat1,a_lat2, keep=FALSE);
autoplot(dat, geom=c("r", "c"), colour="white", size=0.1) + scale_fill_etopo();
Here is the output of above R script:
Questions:
Why do both images not match?
In google-maps I am using zoom value 13. How does that translate in ggplot2/MarMap?
Is it possible to zoom in ggplot2/MarMap into a (Lat/Long)-(Lat/Long) region?
Is it possible to plot what I am asking for?
I don't know how you got this result. When I use your script, I get an error since the area your are trying to fetch from the ETOPO1 database using getNOAA.bathy() is too small. However, adding resolution=1 (this gives the highest possible resolution for the ETOPO1 database), here is what I get:
To answer your questions:
Why do both images not match?
Probably because getNOAA.bathy() returned an error and the object dat you're using has been created before, using another set of coordinates
In google-maps I am using zoom value 13. How does that translate in ggplot2/MarMap?
I have no clue!
Is it possible to zoom in ggplot2/MarMap into a (Lat/Long)-(Lat/Long) region?
I urge you to take a look at section 4 of the marmap-DataAnalysis vignette. This section is dedicated to working with big files. You will find there that you can zoom in any area of a bathy object by using (for instance) the subsetBathy() function that will allow you to click on a map to define the desired area
Is it possible to plot what I am asking for? Yes, but it would be much easier to use base graphics and not ggplot2. Once again, you should read the package vignettes.
Finally, regarding the coastline data, you can use the dist2isobath() function to compute the distance between any gps point and any isobath, including the coastline. Guess where you can learn more about this function and how to use it...

Autokriging spatial data

I'm trying to use a kriging function to create vertical maps of chemical parameters in an ocean transect, and I'm having a hard time getting started.
My data look like this:
horiz=rep(1:5, 5)
depth=runif(25)
value = horiz+runif(25)/5
df <- data.frame(horiz, depth, value)
The autoKrige function in the automap package looks like it should do the job for me but it takes an object of class SpatialPointsDataFrame. As far as I can tell, the function spTransform in package rgdal creates SpatialPointsDataFrame objects, but there are two problems:
OSX binaries of this aren't available from CRAN, and my copy of RStudio running on OXS 10.7 doesn't seem to be able to install it, and
This function seems to work on lat/long data and correct distance values for the curvature of the Earth. Since I'm dealing with a vertical plane (and short distances, scale of hundreds of meters) I don't want to correct my distances.
There's an excellent discussion of kriging in R here, but due to the issues listed above I don't quite understand how to apply it to my specific problem.
I want a matrix or dataframe describing a grid of points with interpolated values for my chemical parameters, which I can then plot (ideally using ggplot2). I suspect that the solution to my problem is considerably easier than I'm making it out to be.
So there a a few question you want answered:
The spTransform function does not create SPDF's, but transforms between projections. To create a SPDF you can use a simple data.frame as a start. To transform df to a SPDF:
coordinates(df) = c("horiz", "depth")
OS X binaries of rgdal can be found at http://www.kyngchaos.com. But I doubt if you need rgdal.
spTransform can operate on latlong data, but also on projected data. But I do not think you need rgdal, or spTransform, see also point 1.
After you create the SPDF using point 1, you can use the info at the post you mentioned to go on.

Resources