遍历文件列表并在 R 中计算它们之间的相关性

Iterate through list of files and calculate the correlation between them in R

我正在尝试遍历 R 中的许多光栅文件(使用光栅包),以 运行 方式计算它们之间的相关性。我需要迭代地做 3 件主要事情:

c <- cor(x,y)
sum <- x+y
deltacor <- 1-(cor([i],sum)) # where i = next raster in list

这是我必须设置的循环:

require(raster)

files = list.files(getwd(),pattern="*.asc") # get files
lsfiles <-lapply(files,function(x) raster(x)) # import them as rasters

for (x in lsfiles){
    x <- na.omit(getValues(i)) # cannot ignore NA in other attempted ways

我是否需要一个 j 循环来从列表中获取第二个文件,然后关联 i 和 j?有没有更简单的方法来遍历文件目录,计算其中两个文件之间的相关性,然后计算那些 2 个和下一个 1 个之间的相关性?理想情况下,我不会一次将所有栅格加载到内存中。

想法and/or 帮助非常感谢

更新了任何有类似问题的人的答案:

require(raster)
setwd ('/foobar')

x <- raster(foobar.asc)
solution <-raster(solution.asc)

for (file in list.files(getwd(),pattern="*.asc",full.names=TRUE)){
    file <- raster(file)
    file <- na.omit(getValues(file))
    rs <- file+x               # just uses first file in list (x) rolling sum
    deltac <- 1-(cor(rs,x))    # delta from current sum and previous sum
    tc <- cor(solution,rs)     # actual correlation with solution
    x <- rs                    # update x by making it the previous sum
print(tc)                      # actual correlation
print (deltac)                 # how correlated was last sum with new sum
}