[R] Trying to avoid nested loop

arun smartpink111 at yahoo.com
Fri Oct 4 16:30:58 CEST 2013


Hi,
set.seed(49)
 X = matrix(rnorm(100), 10, 10)
X1<- X

result<-0
for(m in 1:nrow(X)){  for(n in 1:ncol(X)){        if(X[m,n] != 0){      result = result + (X[m,n] / (1 + abs(m - n)))    }      }}


indx<-which(X!=0,arr.ind=TRUE)
 indx1<-1+abs(indx[,1]-indx[,2])

X1[indx]<- X1[indx]/indx1
#or

res1<- sapply(seq_len(nrow(X)),function(m) do.call(rbind,lapply(seq_len(ncol(X)),function(n) {if(X[m,n]!=0) X[m,n]/(1+abs(m-n))})))
 res2<-t(X1)
 identical(res1,res2)
#[1] TRUE


res3<- sum(res2)
all.equal(res3,result)
#[1] TRUE
A.K.



----- Original Message -----
From: philippe massicotte <pmassicotte at hotmail.com>
To: "r-help at r-project.org" <r-help at r-project.org>
Cc: 
Sent: Friday, October 4, 2013 9:49 AM
Subject: [R] Trying to avoid nested loop

Dear R users.
I'm trying to avoid using nested loops in the following code but I'm not sure how to proceed. Any help would be greatly appreciated.
With regards,Phil
X = matrix(rnorm(100), 10, 10)
## Version with nested loopsresult = 0
for(m in 1:nrow(X)){  for(n in 1:ncol(X)){        if(X[m,n] != 0){      result = result + (X[m,n] / (1 + abs(m - n)))    }      }}
## No loop-sum(ifelse(M > 0, M/??? , 0))

                          
    [[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