Re: [R] to replace the for loop
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. __ R-help@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.
Re: [R] to replace the for loop
On 14-12-2013, at 08:01, Arnaud Michel wrote: > 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 }} > Your code is mangled. We don’t know what T is. You refer to TEMP in the for loop but you most likely meant T. Shouldn’t the second nrow in your for loop be ncol? > I don't find the function in the doc. Search with ??uppertri and you’ll find lower.tri in base with sufficient description to have a look at that entry. Depending on what packages you have, you may find more. > Thanks in advance for your help. > T[col(T)>=row(T)] <- 0 T[upper.tri(T,diag=TRUE) ] <- 0 Berend > -- > Michel ARNAUD > Chargé de mission auprès du DRH > DGDRD-Drh - TA 174/04 > Av Agropolis 34398 Montpellier cedex 5 > tel : 04.67.61.75.38 > fax : 04.67.61.57.87 > port: 06.47.43.55.31 > > __ > R-help@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. __ R-help@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.
[R] to replace the for loop
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. -- Michel ARNAUD Chargé de mission auprès du DRH DGDRD-Drh - TA 174/04 Av Agropolis 34398 Montpellier cedex 5 tel : 04.67.61.75.38 fax : 04.67.61.57.87 port: 06.47.43.55.31 __ R-help@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.