Changing projection of a netcdf - r

I have netcdf files of daily temperature and precipitation data
How is it possible to Change projection of a netcdf?
I have tried to doing this using raster function to read the files
and reproject them with projectraster?
Code_used
a <-raster(file.nc)
cr1<-"+proj=longlat +datum=NAD83 +no_defs+ellps=GRS80 +towgs84=0,0,0"
projectRaster(a, cr1,res = 0.04166667)
ERROR_
Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘res’ for signature ‘"character"’
In addition: Warning message:
In min(dim(to)[1:2]) : no non-missing arguments to min; returning Inf

The help for projectRaster gives this usage:
Usage:
projectRaster(from, to, res, crs, method="bilinear",
alignOnly=FALSE, over=FALSE, filename="", ...)
if you call it with two unnamed arguments, they get matched to from and to, and to is:
to: Raster* object with the parameters to which 'from' should be
projected
if instead you name the second argument, this should work:
a_project = projectRaster(a, crs = cr1, res = 0.04166667)
because now the second argument is matched as the crs argument.
BUT if you just want to transform a gdal-compatible data set then you can use gdaltransform, either from the command line or via the function with the same name from the gdalUtils package.

Related

Resample and matching raster stack using loop in R

I aim to combine biodiversity data with land cover information (rasters and vectors).
However, I need to match the resolution, extent, CRS, and dimensions of each raster (predictor variables) with my biodiversity data (answer variables). I had succeed to do it individually but there are six rasters.
Although, when I try a loop for the raster stack. I got some errors.
 
library(terra)
library(raster)
#Create a raster stack with land cover predictors:
CDI_stack<-raster::stack(list.files(path = dir_Proj1, pattern='.tif', full.names=T))
#Convert to cylindrical equal area projection
equalareaproj<-"+proj=cea +lon_0=0 +lat_ts=30 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs"
crs(CDI_stack, warn=FALSE)<-equalareaproj
#Raster with standard dimension, resolution, extention and CRS
standard<-terra::subset(study_area, 2)
#Loop for the raster stack
for(i in 1:length(CDI_stack#layers)){
#Creating a single raster with each layer to maintain values
CDI_layer<-terra::rast(terra::subset(CDI_stack, i))
#Matching a raster extention individually
CDI_layer<-ext(standard)
#Cropping it with standard raster to reduce matching error
raster::crop(CDI_layer[i],standard)
#Resample resolution
terra::resample(CDI_layer[i], standard, method= "near", threads= T)
#Write the raster:
return(writeRaster(Resampled_layer,
filename=paste0("~/Land use/Chronic_Anthropogenic_Disturbance_Surface/", CDI_layer[i]),
format="GTiff", overwrite=TRUE))
}
I found these errors:
Error in h(simpleError(msg, call)) :
error evaluating argument 'x' in method selection for function 'crop': 'this S4 class is not subsettable
Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘crop’ for signature ‘"numeric"’
I would like to know if there's any complication to use raster stack or whether I am doing any code step wrongly. I expect to found the correction on the code or of the use of class object.
Please, I hope for your support. Thank you!
G.
Thank you for your advice, Mr. Hijimans.
I found too many errors.
When we do it directly with the raster stack the R returns that the method for the function 'resample' does not work on RasterStack class (see below).
As a stack can have multiple layers, the loop simplified the process rather to work on each one of them.
I preferred to work with a list from the raster stack than the stack, it worked better in the loop.
Also, I used a vector to crop the raster, it preserved raster values (avoiding return NA).
rc <- terra::resample(CDI_stack, standard, method= "bilinear", threads= T)
Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘resample’ for signature ‘"RasterStack", "SpatRaster"’
#Create a list from the stack with land cover predictors:
CDI_list<-terra::as.list(CDI_stack)
rm(study_area,CDI_stack)
#Create a list to store the results
results <- list()
#Loop for each SpatRaster from the list
for(i in 1:length(CDI_list)) {
r<-rast(CDI_list[[i]]) # create a raster for each layer
ext(r) <-ext(standard) # redefine extension for each layer
#Crop rasters using the vector to avoid 'NA' values
rc <- terra::crop(r, standard_vec)
#Resample rasters following standard parameters
rc <- terra::resample(rc, standard, method= "bilinear", threads= T)
#Rewrite the list layers with the result
results[[i]] <- rc
}
#Check the values
results[[4]]
#Rasterize the list to save it as a data frame
resampled<-rast(results)
df<-as.data.frame(resampled)
summary(df)
#Save the data frame in the project directory
data.table::fwrite(df, "~/Land use/DATASETS/resampled.csv")
It should be easy enough to find out what is going wrong when you run the code line by line; including inside the for-loop (set i to 1 or whatever the valye is when the error occurs).
You will see that this fails:
CDI_layer <- ext(standard)
raster::crop(CDI_layer[i],standard)
Because CDI_layer[i] is a single number.
There are other things that are awkward. Especially, just use "terra", do not also use "raster" at the same time to avoid confusion.
Seeing your answer it would seem that you can do all of this in two lines
CDI_stack <- terra::rast(files)
rc <- terra::resample(CDI_stack, standard, method= "bilinear", threads= T)
df <- as.data.frame(rc)

R 'automap' how to create prediction grid to use with AutoKrige (e.g. meuse.grid)?

I'm having a lot of difficulty creating a prediction grid (for the new_data argument) to use with the autoKrige function in the automap package.
I've already tried following the steps in this post (How to subset SpatialGrid using SpatialPolygon) but get the following error :
Error in x#coords[i, , drop = FALSE] :
(subscript) logical subscript too long
In addition: Warning messages:
1: In min(x) : no non-missing arguments to min; returning Inf
2: In max(x) : no non-missing arguments to max; returning -Inf
My (limited) understanding is the error relates to there being no non-missing arguments because it is an empty grid. This is fine - all I want is an empty grid constrained by a polygon from a shapefile.
Here is the code I'm working with:
shp <- shapefile("C://path/path/Tobay_Box2.shp")
shp <- spTransform (shp,"+proj=utm +ellps=WGS84 +datum=WGS84")
grid <- GridTopology(cellcentre.offset=c(731888.0,7457552.0),cellsize=c(2,2),cells.dim=c(122,106))
grid <- SpatialPixelsDataFrame(grid,
data=data.frame(id=1:prod(122,106)),
proj4string=CRS("+proj=utm +ellps=WGS84 + datum=WGS84"))
plot(grid)
[see dropbox folder 'Grid.png']
bound <- shp#polygons
bound <- SpatialPolygons(bound, proj4string=CRS("+proj=utm +ellps=WGS84 +datum=WGS84"))
plot(bound)
[see dropbox folder 'Boundary plot.png']
clip_grid <- grid[!is.na(over(grid, bound)),]
No errors or warnings up to this point. But then...
plot(clip_grid)
Error in x#coords[i, , drop = FALSE] :
(subscript) logical subscript too long
In addition: Warning messages:
1: In min(x) : no non-missing arguments to min; returning Inf
2: In max(x) : no non-missing arguments to max; returning -Inf
or attempting to pass the object clip_grid through autokrige for the new_data argument:
PerInkrg <- autoKrige (PerArIn~1, hs1, clip_grid)
Error in predict.gstat(g, newdata = newdata, block = block, nsim = nsim, :
value not allowed for: %s %s newdata empty or only NA's
I've had no issues using the non-clipped grid (object = grid).
In a nutshell, I require this [see dropbox folder 'Autokrig plot'] but with the interpolated surfaced constrained (clipped) to the boundary extent of 'Torbay_Box2.shp'
P.S. I attempted to insert images of my plots and links to other posts I've used before asking for help here and a link to my data but as a new user I don't have enough reputation to do this - sorry!
Data and plots can be found on Dropbox.com/sh/yqg20z1ibl3h4aa/AACJnHoEuP-S5fTvAXxsnY1za?dl=0
I've now managed to produce an autoKrige [plot] which is masked to the extent of the Torbay_Box2 boundary. However, I never achieved this in the 'conventional' way by creating a prediction grid like meuse.grid. The result is the same so for now I'm happy but I would still like to do it the conventional way eventually.
Here's how I cheated it:
# Load sample box extent
bx.data <- readOGR (".", "Tobay_Box2")
bx <- spTransform(bx.data,"+proj=utm +ellps=WGS84 +datum=WGS84") #transformsto UTM projection
str(bx)
# Set the boundary extent with that of sample box extent
hs1#bbox <- bx#bbox
#create an empty grid
grd <- as.data.frame(spsample(hs1, "regular", n=50000))
names(grd) <- c("X", "Y")
coordinates(grd) <- c("X", "Y")
gridded(grd) <- TRUE # Create SpatialPixel object
fullgrid(grd) <- TRUE # Create SpatialGrid object
plot(hs1)
plot(grd, pch = ".", add = T)
proj4string(grd) <- proj4string(hs1)
I then performed an IDW interpolation using the empty grid as the newdata, converted the output to raster, clipped this to the Torbay_Box2 boundary and then converted this to a SpatialPixelDataFrame which I passed through as the new_data argument for autoKrige:
# For PerArIn (% area inhabited)
#interpolate the grid cells using all points and a power value of 2
hs1.idw <- gstat::idw(PerArIn ~ 1, hs1, newdata=grd, idp=2.0)
# Convert to raster object then clip to Hollicombe sample box
r <- raster(hs1.idw)
r.m <- mask(r, bx)
#Convert and set as prediction grid for Kriging
grd<- rasterToPoints(r.m, spatial=TRUE)
gridded(grd) <- TRUE
grd <- as (grd, "SpatialPixels")
#en voila!
PerInkrg <- autoKrige (PerArIn~1, hs1,grd)

R - Crop for JPEG Impages

I'm trying to plot a image (a flag) on a map using raster layers and
# Load packages
library(maptools)
library(raster)
library(jpeg)
# Read in a jpeg and convert to raster
usa.flag <- as.raster(readJPEG(".../usa.jpg"))
# Get spacial image of map
data("wrld_simpl")
usa.map <- subset(wrld_simpl, NAME == "United States")
When I try to crop, I get an error:
usa.sub <- crop(usa.flag, extent(usa.map))
Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘crop’ for signature ‘"raster"’
But I can't figure out what I'm missing about the use of crop().

R load shapefile: "Error in plot.window(...) : need finite 'ylim' values"

I've created the following script to get the coastline of Denmark
# Get Shapefiles for Coastline
shpurl <- "http://download.geofabrik.de/europe/denmark-latest.shp.zip"
tmp <- tempfile(fileext=".zip")
download.file(shpurl, destfile = tmp)
files <- unzip(tmp, exdir=getwd())
# Load & plot shapefile
library(maptools)
shp <- readShapePoly(files[grep(".shp$", shpurl)])
plot(shp)
This should give me the outline of Denmark, however, I keep getting the following error:
Error in plot.window(...) : need finite 'ylim' values
In addition: Warning messages:
1: In xy.coords(x, y, xlabel, ylabel, log) : NAs introduced by coercion
2: In min(x) : no non-missing arguments to min; returning Inf
3: In max(x) : no non-missing arguments to max; returning -Inf
Any help or directions is appreciated.
Have a look at your files value:
> length(files)
[1] 41
The files you are downloading have number of shape files for various geographies. For instance the code:
require(rgdal)
shp <- readOGR(dsn = "whereIsavedyourStuff/Stacks", layer = "roads")
will execute properly. But you will need to specify, which of the sourced shape files you want to read.
As a side point, with respect to reading files from the net, I would suggest that you have a look at this code:
# Download an read US state shapefiles
tmp_shps <- tempfile(); tmp_dir <- tempdir()
download.file("http://www2.census.gov/geo/tiger/GENZ2014/shp/cb_2014_us_state_20m.zip",
tmp_shps)
unzip(tmp_shps, exdir = tmp_dir)
# Libs
require(rgdal)
# Read
us_shps <- readOGR(dsn = tmp_dir, layer = "cb_2014_us_state_20m")
Irrespectively, of what method to read shape files you decide to use you have to specify path and file name. In terms of the provided code in readOGR this is fulfilled by dns and layer options. In your code you used files[grep(".shp$", shpurl)], file names within your 195MB archive, do not corresponds to the URL. You have a few options here:
You can download this files and unpack as you did, list names of all the files that are *.shp, take the file names and pass them in the loop to a list where you would read all combinations (in effect you need a number of files to read each layer)
Better, specify the layer you want to read similarly to the code provided above.

How to convert a shapefile from geographical coordinates to UTM in R

I am trying to convert a global map shapefile from a geographical coordinate system (lat/long, WGS84) into UTM projection using the following code:
setwd = "~/Desktop/Maps"
wmap = readOGR(dsn="world_map", layer="world_map")
wmap_utm = spTransform(wmap, CRS("+proj=utm"))
Unfortunately, I keep getting the following error code:
non finite transformation detected:
[1] 111.01052 19.68381 Inf Inf
Error in .spTransform_Polygon(input[[i]], to_args = to_args, from_args = from_args, :
failure in Polygons 3 Polygon 1 points 1
In addition: Warning message:
In .spTransform_Polygon(input[[i]], to_args = to_args, from_args = from_args, :
686 projected point(s) not finite
I have read both of the following questions on this topic, but both are related to small data examples rather than shapefiles with lots of data points:
rgdal package lat/long -> UTM ;
"Non Finite Transformation Detected" in spTransform in rgdal R Package. I have some polygon files in UTM format that I wish to add to the map and I really need a UTM projection. Any advise on what I might be doing wrong or ways to rectify the problem would be greatly appreciated.

Resources