[R] Looping multiple dimensions

jim holtman jholtman at gmail.com
Fri Jan 22 19:35:08 CET 2010


I would suggest that you use a 'list' for the data.  Something like
this should work:

objs <- grep("^mrunoff_", ls(), values=TRUE)  # get the names of the objects
result <- lapply(objs, function(.obj){
    .obj <- get(.obj)  # get the value
    lapply(1:12, function(. iter)  .obj[,, .iter])
})



On Fri, Jan 22, 2010 at 11:32 AM, Steve Murray <smurray444 at hotmail.com> wrote:
>
> Dear all,
>
> I have 30 arrays, each with dimensions 720,360,12. The naming format for each of these 30 objects is: mrunoff_5221, mrunoff_5222... mrunoff_5250.
>
>
> For example:
>> str(mrunoff_5221)
>   num [1:720, 1:360, 1:12] NA NA NA NA NA NA NA NA NA NA ...  (the initial NA's are nothing to worry about)
>
>
> I am looking for a way by which I can extract each of the third dimension of these grids (1:12) in turn, along with the first and second dimensions, to create new objects in the following style:
>
>
> #2071
> mrunoff_207101 <- mrunoff_5221[,,1]
> mrunoff_207102 <- mrunoff_5221[,,2]
> mrunoff_207103 <- mrunoff_5221[,,3]
> mrunoff_207104 <- mrunoff_5221[,,4]
> mrunoff_207105 <- mrunoff_5221[,,5]   ...(etc. - up to [,,12])
>
> #2072
> mrunoff_207201 <- mrunoff_5222[,,1]
> mrunoff_207202 <- mrunoff_5222[,,2]
> mrunoff_207203 <- mrunoff_5222[,,3]
> mrunoff_207204 <- mrunoff_5222[,,4]
> mrunoff_207205 <- mrunoff_5222[,,5]  ...(etc. - up to [,,12]) and mrunoff_ continues to 2100 and 5250 respectively.
>
>
> Clearly, this is a cumbersome and non-sustainable way to proceed! There will be 360 new objects in total, and I imagine that there must be a more effective way of achieving this, either via a loop or, possibly, one of the 'apply' functions. Yet my attempts to date have so far resulted in... well, a complete mess!
>
> If anyone has any suggestions as to a more efficient means of achieving this, then I'd be very grateful to hear them.
>
> Many thanks,
>
> Steve
>
>
> _________________________________________________________________
> Tell us your greatest, weirdest and funniest Hotmail stories
>
> ______________________________________________
> R-help at 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.
>



-- 
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem that you are trying to solve?



More information about the R-help mailing list