【问题标题】:Error when creating a raster brick in a loop在循环中创建光栅砖时出错
【发布时间】:2017-09-19 14:21:06
【问题描述】:

我正在处理时间序列的栅格,我需要分析 17 个日期的 ts。对于每个日期,我导入了带 5 和带 7。我制作了 17 个带 5 的列表和 17 个带 7 的列表,分别称为 list_B5 和 list_B7。 我想将同一日期的波段堆叠在一起,所以:list_B5 的第一个栅格与 list_B7 的第一个栅格; list_B5 的第二个栅格与 list_B7 的第二个栅格;等等。

我是循环新手,但我试着写一个:

    for (i in seq_along(length(list_B5)) [1]) {
      for (j in seq_along(length(list_B7)) [2]) {
        B5 <- raster(list_B5[[i]]) #extract the raster of interest
        B7 <- raster(list_B7[[j]]) #extract the raster of interest
        test[i,j] <- brick(B5, B7) #stack them together
      }
    }

“测试”是:

test <- brick(nrows=5490, ncol=5490, nl=17)

不幸的是,我收到以下错误:

Error in (function (classes, fdef, mtable)  : 
unable to find an inherited method for function ‘raster’ for signature ‘"NULL"’

我不明白为什么它不接受我尝试提取感兴趣的栅格的行,因为通常仅此行就可以:

> raster(list_B5[[3]])
class       : RasterLayer 
dimensions  : 5490, 5490, 30140100  (nrow, ncol, ncell)
resolution  : 20, 20  (x, y)
extent      : 6e+05, 709800, 5590200, 5700000  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=utm +zone=31 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0 

有人可以向我解释为什么会出现上述错误吗?

【问题讨论】:

  • 如果你想从同一天开始堆叠 B5 和 B7,为什么要使用 ij?另外,你为什么使用i[1]j[2]?我建议您删除j 循环并仅使用i。如果test 是一个列表,请使用test[[i]] &lt;- brick(B5, B7)

标签: r loops for-loop stack raster


【解决方案1】:

为什么你的代码被破坏了

seq_along(length(list_B5)) 没有按照您的预期进行。相反,它只返回1。您需要使用seq_along(list_B5)seq_len(length(list_B5))。查看文档以获取信息。

稍后,您将1 子集到它的第二个元素:seq_along(length(list_B7))[2]。这引入了NA,这会在以后引起问题。

您可以自行调试这些问题,方法是测试部分代码以查看它们是否产生预期结果。例如,运行 seq_along(length(list_B5))[1]seq_along(length(list_B7))[2] 并查看它们是否生成了您希望的序列。


更简单的方法

使用mapply 可能最容易做到这一点。

list_b5 <- replicate(17, raster(matrix(runif(12), ncol=3)))
list_b7 <- replicate(17, raster(matrix(runif(12), ncol=3)))

mapply(stack, list_b5, list_b7)

在这里,mapply 同时循环遍历list_b5list_b7 的元素,并应用stack 函数(如果您愿意,可以替换为brick)。

如果您的列表实际上是文件路径,那么您可以这样做:

list_b5 <- replicate(17, raster(matrix(runif(12), ncol=3)))
list_b7 <- replicate(17, raster(matrix(runif(12), ncol=3)))

mapply(function(x, y) stack(raster(x), raster(y)), list_b5, list_b7)

修正你的方法

下面是使用for 循环的方法:

test <- list(length=17)
for (i in seq_along(list_b5)) {
    b5 <- list_b5[[i]]
    b7 <- list_b7[[i]]
    test[[i]] <- stack(b5, b7)
}

或者如果你的列表是文件路径,

test <- list(length=17)
for (i in seq_along(list_b5)) {
    b5 <- raster(list_b5[[i]])
    b7 <- raster(list_b7[[i]])
    test[[i]] <- stack(b5, b7)
}

【讨论】:

    猜你喜欢
    • 2017-07-20
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 2016-12-25
    • 2015-01-28
    • 2017-02-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多