You want to take a mean of a set of raster files. Package raster
has built-in object types for handling situations such as this. It is much more efficient to create a rasterStack and use calc
to find the mean:
days<-formatC(1:31, width=2, flag="0")
files <- list( paste("2004" , "01" , days , "1.nc" , sep="" ) )
## First 3 filenames:
files[[1]][1:3]
# [1] "200401011.nc" "200401021.nc" "200401031.nc"
sms <- stack( files )
smMean <- calc( sms , mean , na.rm = TRUE )
Edit based on OP comment
You cannot pass a list of filenames directly to raster. From the manual, it states:
x: filename (character), Extent, Raster*, SpatialPixels*, SpatialGrid*, object, 'image', matrix, im, or missing.
Therefore if you must have individual raster objects (and I strongly advise against it in this case) then you could use your loop as originally planned, or you could use:
smRaster <- lapply( files , raster , varname = "sm" )
This will return one list object, each element of which is a raster object. This is probably not that useful to you, but you can then access each one using smRaster[[1]]
, smRaster[[2]]
etc.
But use a raster stack if your files have the same extent and resolution!
Reading the files in using stack
is likely to be more efficient and help you write more readable, shorter code. You can operate on all the rasters at once using convenient syntax, e.g. if I wanted to make a new raster that showed the sum of all the other rasters:
## First we use our files list to make the rasterStack
smStack <- stack( files , varname = "sm" )
## 'sum' returns a new rasterLayer, each cell is the sum of the corresponding cells in the stack
smSum <- sum( smStack , na.rm = TRUE )
## 'mean' does the same!!
smMean <- mean( smStack , na.rm = TRUE )
## What if we want the mean of only the first 7 days of rasters?
smMean <- mean( smStack[[1:7]] , na.rm = TRUE )
## To see how many rasters in the stack...
nlayers( smStack )
## To make a new object of just the first 7 rasters in the stack
subset( smStack , 1:7 )
## Is roughly equivalent to using the `[[` operator like this to get the first 7 layers in a new object
newRaster <- smStack[[1:7]]
## If you want to access an individual layer..
smStack[[ layernumber/or layername here ]]
## And to get the names:
names( smStack)
I would really strongly advise using a stack if you rasters cover the same spatial extent and resolution. It is more efficient, both for R and for your coding to just use a stack
! I hope I have convinced you! :-)