[R-sig-Geo] Error when I try to interpolate NA for each cell from Rasterstack

Vijay Lulla vijaylulla at gmail.com
Sat Jan 14 17:11:31 CET 2017


I think this is because interpNA returns a matrix of one column whereas
raster::setValues (used internally by calc) expects the values to be a
vector of elements.  Changing the last line in `fun_interp` from
`return(z)` to `return(c(z))` might do the trick.

HTH,
Vijay.

On Sat, Jan 14, 2017 at 7:45 AM, Zhang Tianyi <zhang_t_y at hotmail.com> wrote:

> Dear all,
>
> I need to substitute or interpolate the NA in a vector of each cell from a
> rasterstack data. I have two functions fun_sub for substituting NA and
> fun_interp for interpolating NA.
> I found fun_sub works very well. But fun_interp does not work but I cannot
> find a reason.
> Thank you very much
>
> Tianyi Zhang
>
> Below is a simple example:
> #------EXAMPLE
> library(timeSeries)
> library(raster)
> fun_sub <- function(x) {
>   # substitute the NA to the mean of vector for each cell
>   v=as.vector(x)
>   z<-substituteNA(v,type="mean")
>   return (z)
> }
>
> fun_interp <- function(x) {
>   # interpolate the NA to the the linear regression of vector for each cell
>   v=as.vector(x)
>   z=interpNA(v, method="linear")
>   return (z)
> }
>
> # create data
> r<-raster(ncols=2,nrows=2)
> r1<-r; r2<-r; r3<-r; r4<-r
> r1[]<-c(1,1,1,2)
> r2[]<-c(5,5,NA,5)
> r3[]<-c(3,3,4,2)
> r4[]<-c(6,5,5,2)
> s<-stack(r1,r2,r3,r4)
>
> # try the two functions; the task is change the NA in r2 to a number;
> res_sub<-calc(s,fun_sub) # works great! substitute the NA to the mean of
> c(1,NA,4,5); I got c(1,3.333,4,5)
> res_inter<-calc(s,fun_interp) # cannot interpolate; have an error, don't
> know the reason; I expected it is c(1, 2.5 ,4, 5). But it returns an error
>
> # try whether interpNA() can work or not
> interpNA(c(1,NA,4,5),method="linear") # but this function is OK.
>
>
>
>
>
>         [[alternative HTML version deleted]]
>
> _______________________________________________
> R-sig-Geo mailing list
> R-sig-Geo at r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
>

	[[alternative HTML version deleted]]



More information about the R-sig-Geo mailing list