You're doing some unnecessary work. If you want a stack
then just call rstk <- stack(files)
. If the data doesn't share extents then call agg <- sapply(files, raster)
. Some people always use stack
--if that's you're intent fine--but just don't make a function that only calls another function.
It's not clear what your intent is with putting the rasters in dataframes. I don't think you should put a raster object in a dataframe, or if that's even possible. If all rasters have the same number of cells then you could go with dfr <- do.call(rbind, lapply(agg, raster::values))
or cbind
if you want them to be columns. If they're not the same number of cells then your best option depends on what you'll be doing with this afterwards. Can you tell us a little more about what you're trying to do?
I see raster
has an as.data.frame
method. If you give it a raster::stack
object it will return a dataframe with raster layer values in columns, but all rasters need to share extents. Oherwise you could make each individual raster into a matrix. It should be something like as.data.frame(stack(files))
or lapply(lstRasters, as.data.frame)
; R uses generic functions that will fetch the object's as.data.frame
method for you.
If you want to reshape the raster data into long form (x, y, value) data frame, then an option is raster
's xyFromCell
: cbind(xyFromCell(myRaster), raster::values(myRaster))