Compute correlation, (weighted) covariance, or similar summary statistics that compare the values of all pairs of the layers of a SpatRaster.

# S4 method for SpatRaster
layerCor(x, fun, w, asSample=TRUE, na.rm=FALSE, maxcell=Inf, ...)

Arguments

x

SpatRaster

fun

character. The statistic to compute: either "cov" (covariance), "weighted.cov" (weighted covariance), or "pearson" (correlation coefficient) or your own function that takes two vectors as argument to compute a single number

w

SpatRaster with the weights to compute the weighted covariance. It should have a single layer and the same geometry as x

asSample

logical. If TRUE, the statistic for a sample (denominator is n-1) is computed, rather than for the population (denominator is n). Only for the standard functions

na.rm

logical. Should missing values be removed?

maxcell

postive integer. The number of cells to be regularly sampled. Only used when fun is a function

...

additional arguments for fun (if it is a proper function)

Value

If fun is one of the three standard statistics, you get a list with two items: the correlation or (weighted) covariance matrix, and the (weighted) means.

If fun is a function, you get a matrix.

References

For the weighted covariance:

  • Canty, M.J. and A.A. Nielsen, 2008. Automatic radiometric normalization of multitemporal satellite imagery with the iteratively re-weighted MAD transformation. Remote Sensing of Environment 112:1025-1036.

  • Nielsen, A.A., 2007. The regularized iteratively reweighted MAD method for change detection in multi- and hyperspectral data. IEEE Transactions on Image Processing 16(2):463-478.

Examples

b <- rast(system.file("ex/logo.tif", package="terra"))   
layerCor(b, "pearson")
#> $pearson
#>           [,1]      [,2]      [,3]
#> [1,] 1.0000000 0.9980961 0.9501633
#> [2,] 0.9980961 1.0000000 0.9658011
#> [3,] 0.9501633 0.9658011 1.0000000
#> 
#> $mean
#>          [,1]     [,2]     [,3]
#> [1,]      NaN 182.2855 182.2855
#> [2,] 185.3509      NaN 185.3509
#> [3,] 192.8046 192.8046      NaN
#> 

layerCor(b, "cov")
#> $covariance
#>            red    green     blue
#> red   5564.371 5443.405 4993.165
#> green 5443.405 5345.403 4974.478
#> blue  4993.165 4974.478 4962.942
#> 
#> $mean
#>      red    green     blue 
#> 182.2855 185.3509 192.8046 
#> 

# weigh by column number
w <- init(b, fun="col")
layerCor(b, "weighted.cov", w=w)
#> $weighted_covariance
#>            red    green     blue
#> red   5670.750 5536.351 5009.851
#> green 5536.351 5427.161 4987.092
#> blue  5009.851 4987.092 4937.007
#> 
#> $weighted_mean
#>      red    green     blue 
#> 177.5983 181.3521 191.5236 
#>