迭代文件列表并计算它们之间的相关性

时间:2015-04-02 18:56:26

标签: r loops correlation raster

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

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?理想情况下,我不会立即将所有栅格加载到内存中。

想法和/或帮助非常感谢

1 个答案:

答案 0 :(得分:0)

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

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
}