问题
I am using lapply() to load 144 rasters as in my previous post: How do you load multiple rasters in [r] using a for loop?
library(raster)
rastlist <- list.files(path=path, pattern='tif$', full.names=TRUE)
allrasters <- lapply(rastlist, raster)
allrasters ends up being a large list with 144 elements, of which 'name' looks like one of the attributes, I pasted the last (144th) element output below.
[[144]] class : RasterLayer dimensions : 405, 345, 139725 (nrow, ncol, ncell) resolution : 30, 30 (x, y) extent : -971895, -961545, 1463535, 1475685 (xmin, xmax, ymin, ymax) crs : +proj=aea +lat_1=29.5 +lat_2=45.5 +lat_0=23 +lon_0=-96 +x_0=0 +y_0=0 +datum=NAD83 +units=m +no_defs +ellps=GRS80 +towgs84=0,0,0 source : T://abbreviatedpath/sample.tif names : wildcard1_name_wildcard2 values : -32768, 32767 (min, max)
I would like to do some processing on subsets of these rasters based on wildcards in the names. i.e., I would like to mask those with wildcard1=x and save that output as the input raster name appended with "_m". Later I would like to mosaic a subset of my allrasters list based on wildcard2=y.
My efforts to extract a list of rasters based on a pattern in the names from the already-loaded list of rasters (allrasters) failed.
rast.x<-grep("x",allrasters)
yeilds a vector of the 6 list numbers that correlate to the rasters I am trying to extract into a subset. Maybe this is a better approach?
The only work-around I have found is to approach with a different process/pipeline: First create subset lists, then load rasters in subset lists with lapply, then apply functions to rasters in subset lists with lapply, like here:
rastlist.HIGH <- list.files(path=path, pattern='HIGH', full.names=TRUE)
allrast.HIGH <- lapply(rastlist.HIGH, raster)
allrast.HIGH_m<-lapply(allrast.HIGH,mask,HIGH_mask,updatevalue=NA,updateNA=FALSE)
This process seems to be working, except now I am stuck on how to write the rasters in the list allrast.HIGH_m
The post https://gis.stackexchange.com/questions/301956/write-multiple-rasters-in-r never seemed to be resolved, and perhaps it didn't work because it of the using-a-for-loop-on-an-S4-object issue.
The lapply() approach to write all these rasters does not seem to be working:
lapply(allrast.HIGH_m, writeRaster(filename=paste0(path),"/masked/",names(allrast.HIGH_m),"_m"), format="GTiff"))
This code gives me the error: Error: unexpected ')' in "lapply(allrast.HIGH_m, writeRaster(filename=paste0(path),"/masked/",names(allrast.HIGH_m),"_m"), format="GTiff"))"
Any ideas on how to write multiple rasters that are not stacked, nor that are the same extent, from a list? And give them names which are the input name appended with something? Thank you!!
回答1:
Try with this code, it should work.
lapply(allrast.HIGH_m, function (x) writeRaster(filename=paste0(path,"/masked/",names(x),"_m"), format="GTiff"))
来源:https://stackoverflow.com/questions/59904916/how-do-you-write-multiple-rasters-in-r