Learn R Programming

terra (version 1.7-65)

princomp: SpatRaster PCA

Description

Compute principal components for SpatRaster layers. The benefit of this method is that it uses all values to compute the principal components, even for very large rasters. This is because it computes the covariance matrix by processing the data in chunks, if necessary, using layerCor. The population covariance is used (not the sample, with n-1 denominator, covariance).

Alternatively, you can use stats::princomp or stats::prcomp with a data.frame of the raster values, using a sample for very large rasters (see the examples below).

Usage

# S4 method for SpatRaster
princomp(x, cor=FALSE, fix_sign=TRUE, use="pairwise.complete.obs", maxcell=Inf)

Value

princomp object

Arguments

x

SpatRaster

cor

logical. If FALSE, the covariance matrix is used. Otherwise the correlation matrix is used

fix_sign

logical. If TRUE, the signs of the loadings and scores are chosen so that the first element of each loading is non-negative

use

character. To decide how to handle missing values. This must be (an abbreviation of) one of the strings "everything", "complete.obs", "pairwise.complete.obs", or "masked.complete". With "pairwise.complete.obs", the covariance between a pair of layers is computed for all cells that are not NA in that pair. Therefore, it may be that the (number of) cells used varies between pairs. The benefit of this approach is that all available data is used. Use "complete.obs", if you want to only use the values from cells that are not NA in any of the layers. By using "masked.complete" you indicate that all layers have NA values in the same cells

maxcell

positive integer. The maximum number of cells to be used. If this is smaller than ncell(x), a regular sample of x is used

Author

Alex Ilich and Robert Hijmans, based on a similar method by Benjamin Leutner

See Also

Examples

Run this code
f <- system.file("ex/logo.tif", package = "terra")
r <- rast(f)
pca <- princomp(r)
x <- predict(r, pca)

# use "index" to get a subset of the components
p <- predict(r, pca, index=1:2)

### use princomp directly
pca2 <- princomp(values(r),  fix_sign = TRUE)
p2 <- predict(r, pca2)

### may need to use sampling with a large raster 
### here with prcomp instead of princomp
sr <- spatSample(r, 100000, "regular")
pca3 <- prcomp(sr)
p3 <- predict(r, pca3)

Run the code above in your browser using DataLab