我有几个大的栅格,我想在PCA中进行处理(以生成摘要栅格)。我见过几个例子,人们似乎只是简单地调用prcomp或princomp。但是,当我这样做时,我得到以下错误消息:
Error in as.vector(data): no method for coercing this S4 class to a vector
示例代码:
files<-list.files() # a set of rasters
layers<-stack(files) # using the raster package
pca<-prcomp(layers)我已经尝试使用光栅砖而不是堆栈,但这似乎不是问题。我需要提供什么方法来提供命令才能将栅格数据转换为矢量格式?我知道有一些方法可以采样栅格并从中运行PCA,但我真的很想了解为什么上面的方法不起作用。
谢谢!
发布于 2014-01-25 23:01:08
我自己的问题的答案:我最终做了一些略有不同的事情:我没有使用每个栅格像元作为输入(非常大的数据集),而是采样点,运行主成分分析,然后保存输出模型,以便可以对每个格网像元…进行预测也许不是最好的解决方案,但它是有效的:
rasters <- stack(myRasters)
sr <- sampleRandom(rasters, 5000) # sample 5000 random grid cells
# run PCA on random sample with correlation matrix
# retx=FALSE means don't save PCA scores
pca <- prcomp(sr, scale=TRUE, retx=FALSE)
# write PCA model to file
dput(pca, file=paste("./climate/", name, "/", name, "_pca.csv", sep=""))
x <- predict(rasters, pca, index=1:6) # create new rasters based on PCA predictions发布于 2016-02-11 02:23:56
RStoolbox包http://bleutner.github.io/RStoolbox/rstbx-docu/rasterPCA.html中有rasterPCA函数
例如:
library('raster')
library('RStoolbox')
rasters <- stack(myRasters)
pca1 <- rasterPCA(rasters)
pca2 <- rasterPCA(rasters, nSamples = 5000) # sample 5000 random grid cells
pca3 <- rasterPCA(rasters, norm = FALSE) # without normalization发布于 2013-11-09 03:38:48
上面的方法不起作用只是因为prcomp不知道如何处理光栅对象。它只知道如何处理向量,而强制向量不起作用,因此出现了错误。
您需要做的是将每个文件读取到一个矢量中,并将每个栅格放入矩阵的一列中。然后,每一行将是单个空间位置上的值的时间序列,而每一列将是特定时间步长上的所有像素。请注意,这种方法不需要精确的空间坐标。此矩阵用作prcomp的输入。
可以使用readGDAL读取文件,并使用as.data.frame将空间数据转换为data.frame。
https://stackoverflow.com/questions/19866009
复制相似问题