Werner Wernersen
2005-Mar-23 14:14 UTC
[R] replace values in a matrix subject to boolean condition
Hi everybody! I am sorry to bother you with a question so simple but I think there might be a better solution: I have a matrix of size 360x501 where I want to check the value of each 5th column of each row and replace it (and the 6th, 7th, 8th column) by zero if the value is less than 1000. I have written a double loop to do that but that requires a lot of time. Is there a faster way to achieve this? Thanks, Werner
Uwe Ligges
2005-Mar-24 09:34 UTC
[R] replace values in a matrix subject to boolean condition
Werner Wernersen wrote:> Hi everybody! > > I am sorry to bother you with a question so simple but > I think there might be a > better solution: > I have a matrix of size 360x501 where I want to check > the value of each 5th > column of each row and replace it (and the 6th, 7th, > 8th column) by zero if the > value is less than 1000. I have written a double loop > to do that but that > requires a lot of time. > > Is there a faster way to achieve this?Two ways to interpret your question: 1) if col5 < 100 replace col5 & col6 & col7 & col8 by 0: X[X[,5] < 1000, 5:8] <- 0 2) if col5 < 100 replace col5 by 0, if col6 < 100 replace col6 by 0, ...: for(i in 5:8) X[X[,i] < 1000, i] <- 0 Uwe Ligges> Thanks, > Werner > > ______________________________________________ > R-help at stat.math.ethz.ch mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Werner Wernersen
2005-Mar-24 13:27 UTC
[R] replace values in a matrix subject to boolean condition
Uwe Ligges wrote:> Werner Wernersen wrote: > >> Hi everybody! >> >> I am sorry to bother you with a question so simplebut>> I think there might be a better solution: >> I have a matrix of size 360x501 where I want tocheck>> the value of each 5th column of each row andreplace it (and the 6th,>> 7th, >> 8th column) by zero if the value is less than 1000.I have written a>> double loop >> to do that but that requires a lot of time. >> >> Is there a faster way to achieve this? > > > > Two ways to interpret your question: > > 1) if col5 < 100 replace col5 & col6 & col7 & col8by 0:> > X[X[,5] < 1000, 5:8] <- 0 > > > 2) if col5 < 100 replace col5 by 0, if col6 < 100replace col6 by 0, ...:> > > for(i in 5:8) > X[X[,i] < 1000, i] <- 0 > > Uwe Ligges > > > > > >> Thanks, >> Werner >> >> ______________________________________________ >> R-help at stat.math.ethz.ch mailing list >> https://stat.ethz.ch/mailman/listinfo/r-help >> PLEASE do read the posting guide! >> http://www.R-project.org/posting-guide.html > > > >Thanks for all your answers! Now I did it with for (j in seq(3,length(d[1,]),by=5)) { d[d[,j]<1000,j:(j+3)] <- c(0,0,0,0) } which is so much faster than the double loop. Thanks again, Werner