replace() vs “[<-”?

旧城冷巷雨未停 提交于 2019-12-05 15:53:28

They're basically exactly the same thing. If you look at the source code of replace, you'll see :

function (x, list, values) 
{
    x[list] <- values
    x
}
<environment: namespace:base>

So replace is nothing else but a wrapper around [<- :

> replace(x.tst, s.tst==1, 0)
     [,1] [,2] [,3]
[1,]    0    0    5
[2,]    0    4    6

Using [<- can give you a speedup if you need to do this a million times, as you lose the extra call to the wrapper function. But it's really marginal, so it's a matter of choice. I would say that replace()is a bit more readible

Btw, x.tst[s.tst==1] <- 0 is quite more readible than "[<-"(x.tst, s.tst==1, 0) . No reason to use that construct, unless you want to save the result in a new dataframe.

To clarify, as @Andrie pointed out, both with replace() and "[<-"(x.tst, s.tst==1, 0) you get a copy of the whole x.tst with the relevant values changed. So you can put that in a new object. This is contrary to x.tst[s.tst==1] <- 0, where you change the values in x.tst itself. Mind you, it doesn't save on memory, as R will make internally a copy of x.tst before doing the manipulation.

Timing results :

> system.time(replicate(1e6, replace(x.tst, s.tst==1, 0)))
   user  system elapsed 
  12.73    0.03   12.78 

> system.time(replicate(1e6, "[<-"(x.tst, s.tst==1, 0)))
   user  system elapsed 
   6.42    0.02    6.44 

> system.time(replicate(1e6, x.tst[s.tst==1] <- 0))
   user  system elapsed 
   5.28    0.02    5.32 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!