【问题标题】:Iterate through list of files and calculate the correlation between them in R遍历文件列表并在 R 中计算它们之间的相关性
【发布时间】:2015-04-02 18:56:25
【问题描述】:

我正在尝试遍历 R 中的许多光栅文件(使用 raster 包),以运行方式计算它们之间的相关性。我需要迭代地做 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?是否有一些更简单的方法可以遍历文件目录,计算其中两个之间的相关性,然后计算这两个和下一个之间的相关性?理想情况下,我不会一次将所有栅格加载到内存中。

非常感谢您的想法和/或帮助

【问题讨论】:

  • 以跑步的方式(可能指定了一些顺序),还是成对的?在您在其他地方对此的评论中,您似乎对成对相关感兴趣。

标签: r loops correlation raster


【解决方案1】:

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

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
}

【讨论】:

  • 请注意,您的模式 *.asc 将匹配文件名,例如 mascot.jpg。您可能追求的模式是\\.asc$
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-16
  • 1970-01-01
  • 1970-01-01
  • 2020-03-07
  • 1970-01-01
相关资源
最近更新 更多