代码之家  ›  专栏  ›  技术社区  ›  Joke O.

使用R中的savitzky golay/sgolayflt(信号)平滑rasterstack

  •  0
  • Joke O.  · 技术社区  · 8 年前

    我一直试图在R的rasterstack上运行savitzky golar过滤器,但没有成功。示例如下:

    library (raster)
    library (zoo)
    library (signal)
    r <- raster(ncol=10, nrow=10)
    r[]=1:ncell(r)
    S <- stack(r,r,r,r,r,r,r,r,r,r,r,r)
    
    ##function for filter
    fun=function(x) { m = sgolayfilt(x,na.spline=T);m}
    s1<-calc(S, fun)
    ##This was an alternative function I used:
    fun <- function(x) {
     v=as.vector(x)
     z=substituteNA(v, type="mean")
     s1.ts2 = ts(z, start=c(2004,1), end=c(2004,12), frequency=12)
    x=sgolayfilt(s1.ts2)}
    

    我得到的错误如下:

    Error in .calcTest(x[1:5], fun, na.rm, forcefun, forceapply) : 
    cannot use this function
    

    这个函数可能缺少什么?

    1 回复  |  直到 8 年前
        1
  •  1
  •   Robert Hijmans    8 年前

    首先用一些示例数据检查函数。

    示例数据

    d <- S[1]
    d
    ##layer.1 layer.2 layer.3 layer.4 layer.5 layer.6 layer.7 layer.8 layer.9 layer.10 layer.11 layer.12
    ##[1,]       1       1       1       1       1       1       1       1       1        1        1        1
    

    现在测试

    fun=function(x) { sgolayfilt(x, na.spline=T) }
    fun(d)
    ##Error in sgolayfilt(x, na.spline = T) : unused argument (na.spline = T)
    

    然后修复

    fun=function(x) { sgolayfilt(x) }
    fun(d)
    ## [1] 1 1 1 1 1 1 1 1 1 1 1 1
    

    下一个

    fun2 <- function(x) {
       v=as.vector(x)
       z=substituteNA(v, type="mean")
       s1.ts2 = ts(z, start=c(2004,1), end=c(2004,12), frequency=12)
       sgolayfilt(s1.ts2)  
       # note that I removed the assignment to x
    }
    
    fun2(S)
    ## Error in fun2(S) : could not find function "substituteNA"
    

    我不知道你想在这里做什么,所以我无法解决。