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