[R] to replace the for loop

arun smartpink111 at yahoo.com
Sat Dec 14 08:34:27 CET 2013


Hi,
May be this helps:

set.seed(42)
 T <- matrix(sample(1:20,20,replace=TRUE),ncol=5)
 TEMP <- T
T1 <- T
 for(i in 1: nrow(TEMP)){
 for(j in 1: nrow(TEMP)){if (i <= j) T[i, j] <- 0 }}
 
indx <- expand.grid(rep(list(1:nrow(TEMP)),2))[,2:1]
T1[as.matrix(indx[indx[,1] <= indx[,2],])] <- 0

#or 
library(gtools)
indx <- permutations(nrow(TEMP),2,1:nrow(TEMP),repeats=TRUE)
T1[indx[indx[,1] <= indx[,2],]] <- 0

 identical(T,T1)
#[1] TRUE
A.K.

Hello 

I would like to replace the for loop this below 

T <- as.matrix(T) 
for(i in 1: nrow(TEMP)){ 
for(j in 1: nrow(TEMP)){if (i <= j) T[i, j] <- 0 }} 

I don't find the function in the doc. 
Thanks in advance for your help.



More information about the R-help mailing list