autokrige and proj4string - r

I am using the R function autokrige from automap package, but I got an error and I do not know how to solve it. Do you have any hints?
Thank you!
sp.poidf <- SpatialPointsDataFrame(sp.poi,thresh.df)
proj4string(sp.poidf) <- CRS("+proj=longlat +datum=WGS84")
pro.df=spTransform(sp.poidf, CRS("+proj=merc +zone=32s +datum=WGS84"))
sp.new <- SpatialPoints(new.poi)
proj4string(sp.new) <- CRS("+proj=longlat +datum=WGS84")
pro.new <- spTransform(sp.new, CRS("+proj=merc +zone=32s +datum=WGS84"))
mykri <- autoKrige(mythresh~1,pro.df,newdata=pro.new)
Error in function (classes, fdef, mtable) :
unable to find an inherited method for function "proj4string", for signature "NULL"

The following code reproduces your problem:
require(automap)
require(rgdal)
loadMeuse()
proj4string(meuse) = CRS("+init=epsg:28992")
proj4string(meuse.grid) = CRS("+init=epsg:28992")
meuse = spTransform(meuse, CRS("+proj=merc +zone=32s +datum=WGS84"))
# Note that meuse.grid no longer is a grid due to the reprojection
meuse.grid = spTransform(meuse.grid, CRS("+proj=merc +zone=32s +datum=WGS84"))
kr = autoKrige(zinc~1, meuse, newdata = meuse.grid)
Error in function (classes, fdef, mtable) :
unable to find an inherited method for function "proj4string", for signature "NULL"
The problem is that you use newdata =, while you should be using new_data = (note the underscore). The following code runs fine:
kr = autoKrige(zinc~1, meuse, new_data = meuse.grid)
The documentation of autoKrige shows this, but krige (from gstat) uses newdata, so I understand the confusion.
What goes wrong is that newdata = is not recognized by autoKrige, and put in the ... part of the argument list. When autoKrige calls krige there is a conflict between new_data supplied by autoKrige, and newdata supplied via .... To prevent other users from ending up with the rather vague error message, I added a check to automap. The erroneous code now leads to an exception:
> kr = autoKrige(zinc~1, meuse, newdata = meuse.grid)
Error in autoKrige(zinc ~ 1, meuse, newdata = meuse.grid) :
The argument name for the prediction object is not 'newdata', but 'new_data'.

Related

Error in spTransform(xSP, CRSobj, ...) : source crs creation failed: generic error of unknown origin

I would like to transform my spatial coordinates to Longitude and Latitude coordinates using spTransform function and get this error which I cant figure out how to solve . Thaks for your help:
Error in spTransform(xSP, CRSobj, ...) : source crs creation failed: generic error of unknown origin
Stores_Postcode_matrix = cbind(Easting = Stores_Postcode$X,
Northing =Stores_Postcode$Y)
Stores_Postcode_SP = SpatialPointsDataFrame(Stores_Postcode_matrix, data = data.frame(Stores_Postcode$X, Stores_Postcode$Y), proj4string = CRS("+init=epsg:27700"))
Stores_Postcode_SP_LtLg <- spTransform(Stores_Postcode_SP, CRS("+init=epsg:4326"))

R - extract part of .nc file and convert into raster (similar to WorldClim format)

I have a netcdf file I made which contains percentage values.
The file has 1 variable, 5 dimensions and 0 NetCDF attributes.
The dimensions are
"lon" "lat" "month" "CR" "yearSumm"
They were created using
lon <- ncdim_def("lon", "modis_degrees", -179.5:179.5, unlim=FALSE,
create_dimvar=TRUE, calendar=NA, longname="Longitude")
lat <- ncdim_def("lat", "modis_degrees", -89.5:89.5, unlim=FALSE,
create_dimvar=TRUE, calendar=NA, longname="Latitude")
month <- ncdim_def("month", "month_name", 1:13, unlim=FALSE,
create_dimvar=TRUE, calendar=NA, longname="Month.and.Annual.Data")
CR <- ncdim_def("CR", "CR_numeric", 1:12, unlim=FALSE,
create_dimvar=TRUE, calendar=NA, longname="Cloud.Regime")
yearSumm <- ncdim_def("yearSumm", "yearOrSummType", 1:21, unlim=FALSE,
create_dimvar=TRUE, calendar=NA, longname="Year.and.Summary.Data")
I want to extract 13 layers (each latxlong with each cell a percentage value) from this and make them into a raster file like the bioclimatic data you can download from worldclim
I have tried extracting the data I want into an array, to then make a raster. I did that using
CR_RFO <- ncvar_get(CRnc, attributes(CRnc$var)$names[1])
CR_Ann <- as.array(CR_RFO[1:360, 1:180, 13, 1:12, 18])
This seems to have selected the data I want.
I then tried to make that into raster format.
raster(CR_Ann)
Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘raster’ for signature ‘"array"’
> CR_R <- as.raster(CR_Ann)
Error in array(if (d[3L] == 3L) rgb(t(x[, , 1L]), t(x[, , 2L]), t(x[, :
a raster array must have exactly 3 or 4 planes
> CR_R <- raster(CR_Ann)
Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘raster’ for signature ‘"array"’
> CR_R <- stack(CR_Ann)
Error in data.frame(values = unlist(unname(x)), ind, stringsAsFactors = FALSE) :
arguments imply differing number of rows: 777600, 0
> CR_R <- brick(CR_Ann)
Eventually brick worked, but I don't think that is actually what I want.
When I looked up the WorldClim files I downloaded, it is a zip file of .tifs
I also had tried
# set path and filename
ncpath <- "data/"
ncname <- "CR_RFO"
ncfname <- paste(ncpath, ncname, ".nc", sep="")
dname <- "Ann" # note: Ann means Annual
CR_raster <- brick(ncfname, varname="CR_RFO")
CR_raster; class(CR_raster)
which resulted in the error
CR_RFO has more than 4 dimensions, I do not know what to do with these data
I suspect I am going about it from the wrong angle, and maybe even have made my netcdf file incorrectly, as lat and long are not variables like in some of the examples I have read.
How can I extract these 13 lat x long layers and output them as .tif as per worldclim?
This is how I have ended up doing what I think I needed to. I haven't tested this in place of worldclim data yet, but I have successfully made the geotiff files.
CRnc <- nc_open("data/CR_RFO.nc")
CR_RFO <- ncvar_get(CRnc, attributes(CRnc$var)$names[1])
Repeat from here for each tif I want, selecting the correct number in the 4th place in the index, and changing the file names accordingly.
CR1_Ann <- as.matrix(CR_RFO[1:360, 1:180, 13, 1, 18])
CR1_Ann <- t(CR1_Ann)
CR1_Ann <- flipud(CR1_Ann)
CR1_Annr <- raster(CR1_Ann, ymn = -89.5, ymx = 89.5, xmn = -179.5, xmx = 179.5)
#plot(CR1_Annr)
writeRaster(CR1_Annr, "./data/CR_Ann/CR1_Ann", format = "GTiff")
This is not an elegant solution, so if anyone has a better way, please share.

Masking raster from data in SpatialGridDataFrame and SpatialPolygonsDataFrame

I am trying to mask a raster file by including only some specific area (‘Koeppen Geiger’ climatic zones) with several locations. I got an error message running the final line of code:
Error in (function (classes, fdef, mtable) : unable to find an
inherited method for function ‘mask’ for signature
‘"SpatialGridDataFrame", "SpatialPolygonsDataFrame"’
.
##Read Countries file
library(sp)
library(maptools)
library(rworldmap)
countries = readShapeSpatial("D:/Studies/PhD/SCI/modeling/ne_10m_admin_0_countries/ne_10m_admin_0_countries.shp") [enter link description here][1]
asia.zone = countries[countries$ADMIN=="South Korea"|
countries$ADMIN=="North Korea"|
countries$ADMIN=="Japan"|
countries$ADMIN=="China"|
countries$ADMIN=="Taiwan",]
##Read Koeppen Geiger’ climatic zones
tst <- read.csv('D:/Studies/PhD/SCI/modeling/Koeppen-Geiger-ASCII.csv',as.is=TRUE) [enter link description here][1]
tst.l <- tst [tst$Cls=="Cfc"|
tst$Cls=="Cfa"|
tst$Cls=="Cfb"|
tst$Cls=="Cwa"|
tst$Cls=="Cwb"|
tst$Cls=="Aw"|
tst$Cls=="As"|
tst$Cls=="Am"|
tst$Cls=="Dwd"|
tst$Cls=="Dwb"|
tst$Cls=="Dwa"|
tst$Cls=="Dwc",]
#convert to sp SpatialPointsDataFrame
coordinates(tst.l) = c("Lon", "Lat")
# promote to SpatialPixelsDataFrame
gridded(tst.l) <- TRUE
# promote to SpatialGridDataFrame
tst.lsGDF = as(tst.l, "SpatialGridDataFrame")
# mask the specific climate zone from some locations
asia.zone2 <- mask(tst.lsGDF,asia.zone)
If you look up ?mask you will see that it has been implemented for Raster* objects, not for SpatialGridDataFrame objects. So you need to coerce your data to a Raster object. Something like this might work:
library(raster)
setwd("D:/Studies/PhD/SCI/modeling/")
countries <- shapefile("vne_10m_admin_0_countries/ne_10m_admin_0_countries.shp")
asia.zone <- countries[countries$ADMIN %in% c("South Korea", "North Korea","Japan", "China", "Taiwan"), ]
tst <- read.csv("Koeppen-Geiger-ASCII.csv", stringsAsFactor=FALSE)
tst.l <- tst [tst$Cls %in% c("Cfc", "Cfa", "Cfb", "Cwa", "Cwb", "Aw", "As", "Am", "Dwd", "Dwb", "Dwa", "Dwc"),]
coordinates(tst.l) = c("Lon", "Lat")
# promote to SpatialPixelsDataFrame
gridded(tst.l) <- TRUE
r <- raster(tst.l)
asia.zone2 <- mask(r, asia.zone)

Create spatial objects in R useful for coordinates() and spsample()

I'm trying to use this code, adapted from dataset meuse
data<-list(var1,var2,x,y)
coordinates(data)=~x+y
grid = spsample(data, type = "regular", cellsize = c(0.05,0.05))
vt <- variogram(var1 ~ var2,data=data)
vt.fit <- fit.variogram(vt, vgm(0.2, "Sph", 800, 0.05))
gstatobj <- gstat(id = 'var1', formula = var1 ~ var2, model=vt.fit, set = list(gls=1))
My goal is creating a grid, like meuse.grid. But coordinates doesn't work... list isn't the right command.
What shall I use?
Is correct the way I'm using to create the grid?
the following reproducible example shows jlhoward's comment is right, and Darko's reply is wrong:
library(gstat)
var1 = 1:3; var2 = 1:3; x = 1:3; y = 1:3
data<-list(var1,var2,x,y)
coordinates(data) = ~x+y
Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘coordinates<-’ for signature ‘"list"’
data<-data.frame(var1,var2,x,y)
coordinates(data) = ~x+y
class(data)
[1] "SpatialPointsDataFrame"
attr(,"package")
[1] "sp"
you may have been confused by doing this again, which would give:
coordinates(data) = ~x+y
Error in `coordinates<-`(`*tmp*`, value = ~x + y) :
setting coordinates cannot be done on Spatial objects, where they have already been set
but leaves the existing (and correct) data in tact.

KDE to Raster conversion fails when eval.points are specified

I want to match a kernel density layer's {ks} raster dimensions to kriged surface {spatial} and have run into an error. The code demonstrates:
require(ks)
require(raster)
require(spatial)
data(topo, package="MASS")
topo.kr = surf.gls(2, expcov, topo, d=0.7)
krig_ras = raster(prmat(topo.kr, 0, 6.5, 0, 6.5, 50))
kd = kde(topo[,1:2])
kde_ras = raster(kd) # works ok
par(mfrow = c(1, 2))
plot(krig_ras); title('krig')
plot(kde_ras); title('kde')
As you can see the dimensions don't match as kde has added a border (see also setMinMax(krig_ras); setMinMax(kde_ras)). But we can specify eval.points:
pts = as.data.frame(krig_ras, xy=TRUE)
kd2 = kde(topo[,1:2], eval.points = pts[,1:2])
kde_ras2 = raster(kd2)
The last returns the error:
Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘raster’ for signature ‘"numeric"’
This R-sig-geo page seems to cover the same error, but I can't figure out if this is the same cause - numeric layerNames. Looking at the names/str for kd2 doesn't suggest anything. Grateful for assistance.
If I understand, you would like something like that:
kde_ras2 <- krig_ras
kde_ras2 <- setValues(kde_ras2, kd2$estimate)

Resources