【发布时间】:2014-02-12 09:44:23
【问题描述】:
我有一个简单的函数,可以从带有名称的列表中创建光栅文件列表(采用 .grd 格式,在下面的示例中称为 list_names):
ListRasters <- function(list_names) {
raster_list <- list() # initialise the list of rasters
for (i in 1:(length(list_names))){
grd_name <- list_names[i] # list_names contains all the names of the images in .grd format
raster_file <- raster(grd_name)
}
raster_list <- append(raster_list, raster_file) # update raster_list at each iteration
}
# Apply the function
raster_list <-lapply(list_names, FUN = ListRasters)
所需的结果应采用以下格式:
[[1]]
class : RasterLayer
# etc
[[2]]
class : RasterLayer
# etc
但是我得到它们的格式是:
[[1]]
[[1]][[1]]
class : RasterLayer
# etc
[[2]]
[[2]][[1]]
class : RasterLayer
# etc
这是一个问题,因为后来我无法访问栅格列表中的项目。 我找不到解决方案,因为我不明白为什么迭代会给出这种格式的结果。您能否就如何修复该功能给我一些解释或一些建议,或者您能看出我在哪里犯了错误吗?
非常欢迎任何帮助!
谢谢!!
【问题讨论】:
-
不需要使用
lapply,因为这会给你一个列表列表(在你的情况下)。请改用raster_list <- ListRasters(list_names)。在旁注中,您是否知道您仅在for-loop 之后附加到列表,而不是在代码注释中描述的每个迭代步骤? -
raster函数的输出是什么?