Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

prcomp function does not work #60

Copy link
Copy link
@prisilveira

Description

@prisilveira
Issue body actions

Dear Dr. Fitzpatrick,

I am working with the gdm package and encountered an issue when trying to run PCA on raster data. Initially, I attempted:

terra::prcomp(transRasts, maxcell = 5e5)

but received the errors:

Error: 'prcomp' is not an exported object from 'namespace:terra'

Then I ran simply prcomp() on the SpatRaster object (transRast) like in the tutorial, and I got the error below:

Error in svd(x, nu = 0, nv = k) : infinite or missing values in 'x'
In addition: Warning message:
In prcomp.default(transRasts, maxcell = 5e+05) :
extra argument ‘maxcell’ will be disregarded

I realized this might be due to the class of the object I was passing — prcomp expects a numeric matrix or data frame, not a SpatRaster.

To work around this, I extracted only the PC axis bands from the raster (excluding xCoord and yCoord), converted them into a matrix with values(), cleaned NAs, and then ran stats::prcomp successfully:

names(transRasts)

bands <- c("PC1","PC2","PC3","PC5") # exclude XCoord and YCoord to perform PCA

rts <- transRasts[[bands]]

M <- values(rts, mat = TRUE)
M <- M[complete.cases(M), , drop = FALSE]

pca_model <- stats::prcomp(M, center = TRUE, scale. = TRUE)

pcaRast <- terra::predict(transRasts, pca_model, index = 1:3)

This works, and I got the final dissimilarity map. However, I wanted to confirm whether this approach makes sense in the context of gdm. In particular, by excluding the XCoord and YCoord layers from the PCA, am I ignoring geographic distance effects in the dissimilarity map? Or is it correct to leave coordinates out of the PCA?

Are there any alternative to circumvent the error with prcomp? I tried other pca functions, but then they do not work with terra::predict() or they do not accept SpatRaster**

Any clarification or guidance you can provide would be greatly appreciated.

Best regards,

Reactions are currently unavailable

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      Morty Proxy This is a proxified and sanitized view of the page, visit original site.