1

So today I was coding up something where I wanted to replace all negative values in a matrix with 0. Call this matrix B. Well this was no problem, I just wrote

B[which(B<0)]=0

But then just because I was curious I was wondering, what if we got rid of the which and wrote

B[B<0]=0

and to my surprise this also gave the same answer. If I would have looked up this question on Stack Overflow the second answer is pretty standard (and there are even more complicated faster methods), but my question is: are the two methods above actually the same? B<0 returns a Boolean matrix. Which method is faster and why?

4

2 回答 2

2

是的,您可以使用逻辑向量进行索引。它在这里解释:http: //cran.r-project.org/doc/manuals/r-release/R-intro.html#Index-vectors

于 2013-05-22T03:16:54.673 回答
2

至于速度问题,我尝试的测试似乎没有太大差异。例如,

B=.5-matrix(runif(10000),100,100) 

start = Sys.time()  
replicate(50000,B[B<0])
speed = Sys.time () - start

25.85 秒

start = Sys.time()  
replicate(50000,B[which(B<0)])
speed = Sys.time () - start

25.91 秒

于 2016-05-22T04:07:11.567 回答