R中的镶嵌栅格?


10

我正在尝试将多个栅格镶嵌到R中的单个大栅格中。使用在/programming/15287807/how-can-i-create-raster-mosaic-using-list-of-rasters中发布的脚本 但是,我收到了警告消息和错误消息。

rasters1 <- list.files("F:\\MOD15A2_LAI_1km\\MOD15A2_LAI_2009", 
                      pattern = "mod15a2.a2009001.*.005.*.img$", 
                      full.names = TRUE, recursive = TRUE)

mos1 <-mosaic(rasters1, fun=mean)

它报告错误如下

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

然后我尝试了另一个版本。

rasters1.mosaicargs <- rasters1
rasters1.mosaicargs$fun <- mean

但是这里有一些警告信息如下

Warning message:
In rasters1.mosaicargs$fun <- mean : Coercing LHS to a list

我忽略了该消息,然后继续

mos2 <- do.call(mosaic, rasters1.mosaicargs)

但是这里有与上面提到的相同的错误

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

我也找到了以下脚本,但是它不起作用 nceas.ucsb.edu/scicomp/usecases/createrasterimagemosaic
Vandka

Answers:


17

这里的问题是,mosaic和do.call期望列表中有一个栅格对象,而不仅仅是“ rasters1”向量中包含的栅格的字符名称。实际上,您是在要求将名称镶嵌在矢量中,而不是在栅格对象中。

# Create some example data
require(raster)
    r <- raster(ncol=100, nrow=100)
      r1 <- crop(r, extent(-10, 11, -10, 11))
        r1[] <- 1:ncell(r1)
          r2 <- crop(r, extent(0, 20, 0, 20))
          r2[] <- 1:ncell(r2)
      r3 <- crop(r, extent(9, 30, 9, 30))
    r3[] <- 1:ncell(r3)

# If I create a list object of the raster names, as your are doing with list.files, 
#    do.call will fail with a character signature error 
rast.list <- list("r1","r2","r3")   
  rast.list$fun <- mean     
    rast.mosaic <- do.call(mosaic,rast.list)

# However, if I create a list contaning raster objects, the do.call function 
#   will work when mosaic is passed to it.      
rast.list <- list(r1, r2, r3)     
  rast.list$fun <- mean
    rast.mosaic <- do.call(mosaic,rast.list)
      plot(rast.mosaic)

# You could specify a for loop to create a list object, 
#   contaning raster objects
rasters1 <- list.files("F:/MOD15A2_LAI_1km/MOD15A2_LAI_2009", 
                       pattern="mod15a2.a2009001.*.005.*.img$", 
                       full.names=TRUE, recursive=TRUE)
rast.list <- list()
  for(i in 1:length(rasters1)) { rast.list[i] <- raster(rasters1[i]) }

# And then use do.call on the list of raster objects
rast.list$fun <- mean
  rast.mosaic <- do.call(mosaic,rast.list)
    plot(rast.mosaic)

1

只是主题上的微小变化。您可以避免创建空白列表for循环 ...

    rast.list <- list()

    for(i in 1:length(rasters1)) { 
rast.list[i] <- raster(rasters1[i])
}

...使用命令lapply

    rast.list <- lapply(1:length(rasters1),
 function(x) {
raster(rasters1[x])
})
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.