On Thu, Jul 7, 2011 at 9:10 AM, confused <cstoc...@climate.unibe.ch> wrote:

> Hi there
>
> I'm working with ncdf data. I have different dataset for 4 runs, 4 seasons
> and 3 timeslices (48 datasets in total). The datasets have the following
> dimensions: 96 longitudes, 48 latitudes and 30 time steps. To read all of
> them in, I wrote the following loop:
>
> runs <- c("03","04","05","06")
> years <- c(1851,1961,2061)
> seasons <- c("DJF","MAM","JJA","SON")
>
> for (i in runs) {
> for (j in years) {
> for (k in seasons) {
>
> data <- open.ncdf(paste("/data09/cstocker/data/atm/tr_1500_",
> i,"/PRECT/PREC_tr1500_", i,"_", j,"_", k,".nc", sep=""))
>
> prect <- get.var.ncdf(data, "PRECT")
>
> assign(paste("prec", k, j, i, sep="_"), prect)
>
> }
> }
> }
>
> I produced 48 variables called prec_DJF_1851_03 and so on..
>
> Now, how can I select an element out of each of these variables?
>

Are all your data arrays (i.e., the data in each of your  48 files) the same
shape? If so, easiest approach (assuming I'm understanding your problem,
which is not a given!) would be simply to put all the data into one array in
the first place. I.e, something like:

nruns <- length(runs)
nyears <- length(years)
nseaons <- length(seasons)

bigdata <- NA    # flag to show it's not initialized yet

for (i in runs) {
for (j in years) {
for (k in seasons) {

   data <-
open.ncdf(paste("/data09/cstocker/data/atm/tr_1500_",i,"/PRECT/PREC_tr1500_",
i,"_", j,"_", k,".nc", sep=""))
   prect <- get.var.ncdf(data, "PRECT")

  if( length(bigdata) == 1 ) {       # is bigdata un-initialized?
     nx = dim(prect)[1]
     ny = dim(prect)[2]
     nz = dim(prect)[3]
    bigdata = array(0., dim=c(nx,ny,nz,nseasons,nyears,nruns))
    }

   bigdata[,,,k,j,i] = prect

   close.ncdf( data )    # remember to close the file
    }
    }
    }

Then you can conveniently select from bigdata however you want.

If the shape of the data in each file is different, you have to use an
analogous approach with lists instead.

Regards,

--Dave

-- 
David W. Pierce
Division of Climate, Atmospheric Science, and Physical Oceanography
Scripps Institution of Oceanography
(858) 534-8276 (voice)  /  (858) 534-8561 (fax)    dpie...@ucsd.edu

        [[alternative HTML version deleted]]

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to