[R] Efficient nested loops

Petr PIKAL petr.pikal at precheza.cz
Thu Oct 21 14:39:05 CEST 2010


Hi

fjsanala at gmail.com napsal dne 21.10.2010 12:44:30:

> Hi Petr, thanks for your help.
> 
> My array has four dimensions. My problem is the next:
> 
> library(survival)
> initial <- array(rnorm(1200000),c(40,30,20,50))
> final <- array(0, 
dim=c(dim(initial)[1],dim(initial)[2],dim(initial)[3]))
> for (i in 1:dim(initial)[1]){
>     for (j in 1:dim(initial)[2]){
>         for (k in 1:dim(initial)[3]){
>             final[i,j,k] <- function(initial[i,j,k,])
>         }
>     }
> }
> 
> My own function has a high computational cost, so Can I use the apply 
function?

Well it strongly depends what and how function "function" computes its 
result.

Basically you can use apply for computing a result over margin of array 

> ar<-array(1:120, c(5,4,3,2))
> apply(ar, 4, sum)
[1] 1830 5430
> apply(ar, 3, sum)
[1] 1620 2420 3220
> apply(ar, 2, sum)
[1] 1590 1740 1890 2040
> apply(ar, 1, sum)
[1] 1404 1428 1452 1476 1500

> apply(ar, 4, range)
     [,1] [,2]
[1,]    1   61
[2,]   60  120

Regards
Petr

> 
> Thank you!
> 
> 

> 2010/10/21 Petr PIKAL <petr.pikal at precheza.cz>
> Hi
> 
> r-help-bounces at r-project.org napsal dne 21.10.2010 10:40:40:
> 
> > Dear R community,
> >
> > I am working with huge arrays, so I spend a lot of time computing. 
This
> is
> > my code:
> >
> > for (x in 1:dim(variable)[1]){
> >     for (y in 1:dim(variable)[2]){
> >         for (z in 1:dim(variable)[3]){
> >             result <- max(variable[x,y,z,])
> >         }
> >     }
> > }
> >
> > Is there a more efficient procedure to do this task?

> is this what you are looking for?
> 
> ar<-array(rnorm(24),c(4,3,2))
> apply(ar, 3, max)
> 
> Regards
> Petr
> 
> 
> >
> > Thanks in advance!
> >
> >    [[alternative HTML version deleted]]
> >
> > ______________________________________________
> > 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.



More information about the R-help mailing list