[R] loops

Uwe Ligges ligges at statistik.uni-dortmund.de
Tue May 2 20:03:23 CEST 2000


Heberto Ghezzo wrote:
> 
> Hi R friends,
> [...]
>  
> cra <- function(x) {
>   nc <- dim(x)[2]
>   nr <- dim(x)[1]
> 
>   ca <- apply(x,2,mean)
>   xc1 <- t(x)-ca
>   xc <- t(xc1)
>   xr1 <- apply(xc,1,rank)
>   xr <- t(xr1)
> 
>   s <- NULL
>   k <- 0
>   for ( j in 1:(nc-1)) {
>     for (jp in (j+1):nc ) {
>       k <- k+1
>       s[k] <- a1(xr[,j],xr[,jp])
>      }
>    }
>   cra <- max(s)
> }
> 
> a1 <- function(x,y){
>   nr <- length(x)
>   h <- x-y
>   s <- 0
>   for( i in 1:(nr-1)){
>     ip <- (i+1):nr
>     a <- h[i]-h[ip]
>     s<- s+sum(a*a)
>   }
>   return(s)
> }


OK. I have had a look to a1(.).
You can remove the loop on this way (only code improved, did not thougth
about the real problem...):

a1 <- function(x,y){
  nr1 <- length(x) - 1
  h <- x - y
  return(sum((h[rep(1:nr1, nr1:1)] - h[nr1 - sequence(nr1:1) + 2])^2))
}

## So it should not be necessary to have an own function a1(.), and
cra(.) looks as follows:


cra <- function(x) {
  nr1 <- dim(x)[1] - 1
  nc <- dim(x)[2]
  xr <- t(apply(t(t(x) - apply(x, 2, mean)), 1, rank))
  ## Not readable any more, but also not so many variables in use.
  ## Maybe this can be simplified ???
  s <- NULL
  k <- 0
  for ( j in 1:(nc - 1)) {
    for (jp in (j + 1):nc ) {
      k <- k + 1
      h <- xr[ ,j] - xr[ ,jp]
      s[k] <- sum((h[rep(1:nr1, nr1:1)] - h[nr1 - sequence(nr1:1) +
2])^2)
     }
   }
  cra <- max(s) 
## or do you want return(max(s)) ???
}


Maybe you can remove some more loops, but there's no more time left ....

Regards,
Uwe Ligges
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list