Skip to content
Prev 23544 / 29559 Next

Convert rasters to data frame with time stamp

Thank you Dominik, Vijay and Robers for all the valuable inputs.

Robert, the function you devised is really convenient. However, it fails when the observed and modelled raster objects have different number of layers.

Please notice that the obs and model objects on the example from the qmap packages have different lengths:

library(qmap)
data(obsprecip)
data(modprecip)

dim(obsprecip);dim(modprecip) # notice the difference in the lengths

#Fit a quantile mapping function to observed and modeled data
qm.fit <- fitQmap(obsprecip,modprecip,
method="QUANT",qstep=0.01)

#Perform bias correction on modeled data 
qm <- doQmap(modprecip, qm.fit, type="tricub")



Now, an error is displayed when trying to apply your function on rasters with different "lengths" (number of layers):

library(raster)
library(qmap)

#Create a rasterStack similar to my data - same dimensions and layer names
r <- raster(ncol=60, nrow=60)
obs <- stack(lapply(1:408, function(x) setValues(r, runif(ncell(r)))))
mod <- stack(lapply(1:800, function(x) setValues(r, runif(ncell(r)))))

#Define bias-correction function
f <- function(obs, mod, ...) {
obs <- t(obs)
qm.fit <- fitQmap(obs, t(mod), method="QUANT",qstep=1/15)
t( doQmap(mod, qm.fit, type="tricub") )
}

# Test function on rasters with different # of layers
x <- f(head(obs), head(mod))


Error in t(doQmap(mod, qm.fit, type = "tricub")) : 
error in evaluating the argument 'x' in selecting a method for function 't': Error in doQmapQUANT.matrix(x, fobj, ...) : 
'ncol(x)' and 'nrow(fobj$par$modq)' should be eaqual


Any way to circumvent this?
 
Greetings,
 -- Thiago V. dos Santos

PhD student
Land and Atmospheric Science
University of Minnesota
On Saturday, October 17, 2015 1:59 AM, Robert J. Hijmans <r.hijmans at gmail.com> wrote:
Thiago,
That would be easy enough by using, e.g., as.data.frame, as Dominik
and Vijay suggested, but I do not think that you _need_ to do that.
The manual says that you can use a matrix (no need for data.frame).
The dates are row.names, but I do not think they are used by the
algorithm, so you do not need to supply them (it would be possible).
In most cases like this, you can wrap the functions you need into a
short new function that can be passed to a raster function (calc or
overlay). In this case perhaps something like:

f <- function(obs, mod, ...) {
  obs <- t(obs)
  qm.fit <- fitQmap(obs, t(mod), method="QUANT",qstep=0.01)
  t( doQmap(obs, qm.fit, type="tricub") )
}

try it

x <- f(head(s), head(s * 10))
x[, 1:5]

model <- s * 10
x <- overlay(s, model, fun=f)


Robert


On Fri, Oct 16, 2015 at 1:39 PM, Thiago V. dos Santos
<thi_veloso at yahoo.com.br> wrote: