2017-10-19 50 views
1

我是R和編程的初學者。所以我覺得這個問題很簡單,但我不能找到答案或解決它。聚焦統計信息(聚焦,「光柵」包,R)的自身函數給出錯誤的輸出

我有柵格(100 * 100個單元格)。我需要在移動窗口處通過2D DFT獲得諧波幅值的中值(例如,窗口大小= 21)。 我發現了光柵包中的焦點功能。對於這個函數,我可以編寫自己的函數,它取值爲一系列值(窗口中的柵格值)並返回整個窗口的單個值。

r <- raster(matrix(rnorm(10000), nrow = 100, ncol = 100)) # creation of raster 
win <- 21 # setting the window size 
spectr <- function(d) { 
    return(median(abs(spec.fft(x = 1:win, y = 1:win, z = (d - mean(d)))$A))) 
} # i think "d" - the matrix of raster values in the window border 
focal(x = r, w = matrix(1, win, win), fun = spectr()) 

輸出:在spec.fft誤差(X = 1:勝利,Y = 1:勝,Z =(d - 平均(d))): 變量 「d」 是缺少的,沒有默認

我推測來自窗口的數據是在函數中自動發送的。我的代碼中有什麼錯誤?謝謝!

UPDATE。爲了測試是需要加載庫「譜」:

install.packages("spectral") 
library(spectral) 

回答

0

首先,要使用先前在focal()定義的功能,你只需要在函數名後以刪除括號()

其次,您的函數使用spectral::spec.fft,這需要參數z爲矩陣。然而,焦點轉發了一個向量值,我們從?focal得知:

函數fun應該帶多個數字,並返回一個數字。

因此,您必須自己生成所需的矩陣。

看到這個例子(但是,請檢查輸出的有效性):

spectr <- function(d) { 
    return(median(abs(spec.fft(x = 1:win, y = 1:win, 
          z = (matrix(d, ncol = win, nrow = win) - mean(d)))$A 
          # eventually you have to reorder or transpose the matrix 
          # if its order has some impact on spec.fft 
        ))) 
} 

讓我們使用功能focal()

focal(x = r, w = matrix(1, win, win), fun = spectr) 
# class  : RasterLayer 
# dimensions : 100, 100, 10000 (nrow, ncol, ncell) 
# resolution : 0.01, 0.01 (x, y) 
# extent  : 0, 1, 0, 1 (xmin, xmax, ymin, ymax) 
# coord. ref. : NA 
# data source : in memory 
# names  : layer 
# values  : 0.03341064, 0.04557778 (min, max) 
+0

謝謝,洛基!這非常簡單。但我認爲功能「光譜」的錯誤。您的代碼有效) –

+0

查看當前版本。我編輯了我的答案 – loki