2
votes

I am a beginner in R and programming. So I think than the question is simple, but I can't to find the answer or solve it solus.

I have the raster (100*100 cells). I need to get the median value of harmonic's magnitudes by 2D DFT at the moving window (for example, size of window = 21). I finded the focal function in the raster package. For this function I can code own function which take seria of values (raster values in window) and return individual value for the whole window.

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())

The output: Error in spec.fft(x = 1:win, y = 1:win, z = (d - mean(d))) : argument "d" is missing, with no default

I presumed that data from window is transmitted in the function automatically. What the mistake in my code? Thank you!

UPDATE. For testing is need to load the library "spectral":

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

1 Answers

1
votes

First, To use the function you defined previously in focal(), you just need to remove the parentheses () after the function name.

Second, your function using spectral::spec.fft which requires the z argument to be a matrix. However, focal forwards a vector of values, as we learn from ?focal:

The function fun should take multiple numbers, and return a single number.

Therefore, you have to generate the required matrix yourself.

See this example (however, please check for validity of the output):

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
                    )))
} 

Let's use the function in 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)