R loop: name objectives by variable -


i need read daily netcdf files every month , give each name ended date

library(raster) year<-2004 startmonth<-1 for(monthd in 31){     days<-formatc(monthd, width=2, flag="0")     month<-formatc(startmonth,width=2,flag="0")     sm=raster(paste(year,month,days,"1.nc",sep=""),varname="sm")     monthd<monthd+1 } 

in end should have raster objectives named sm01 sm02 . . . sm31

for january. there must simple way it, i'm fresh in coding.

you want take mean of set of raster files. package raster has built-in object types handling situations such this. much more efficient create rasterstack , use calc find 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 list of filenames directly raster. manual, states:

x: filename (character), extent, raster*, spatialpixels*, spatialgrid*, object, 'image', matrix, im, or missing.

therefore if must have individual raster objects (and advise against in case) use loop planned, or use:

smraster <- lapply( files , raster , varname = "sm" ) 

this return one list object, each element of raster object. not useful you, can access each 1 using smraster[[1]] , smraster[[2]] etc.

but use raster stack if files have same extent , resolution!

reading files in using stack more efficient , write more readable, shorter code. can operate on all rasters @ once using convenient syntax, e.g. if wanted make new raster showed sum of other rasters:

## first use our files list make rasterstack smstack <- stack( files , varname = "sm" )  ## 'sum' returns new rasterlayer, each cell sum of corresponding cells in stack smsum <- sum( smstack , na.rm = true )  ## 'mean' same!! smmean <- mean( smstack , na.rm = true )  ## if want mean of first 7 days of rasters? smmean <- mean( smstack[[1:7]] , na.rm = true )  ## see how many rasters in stack... nlayers( smstack )  ## make new object of first 7 rasters in stack subset( smstack , 1:7 )  ## equivalent using `[[` operator first 7 layers in new object newraster <- smstack[[1:7]]  ## if want access individual layer.. smstack[[ layernumber/or layername here ]]  ## , names: names( smstack) 

i advise using stack if rasters cover same spatial extent , resolution. more efficient, both r , coding use stack! hope have convinced you! :-)


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -