I recently stumbled across replace() and "[<-". They seem to have similar functionality, for example with "[<-" I can do something like this:
> x.tst <- array(1:6, c(2,3))
> s.tst <- array(0, c(2,3))
> s.tst
[,1] [,2] [,3]
[1,] 0 0 0
[2,] 0 0 0
> s.tst[1:3] <- 1
> "[<-"(x.tst, s.tst==1, 0)
[,1] [,2] [,3]
[1,] 0 0 5
[2,] 0 4 6
> x.tst
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
Can somebody help to clarify the difference? What are the strengths of replace vs "[<-" and vis versa?
They’re basically exactly the same thing. If you look at the source code of replace, you’ll see :
So replace is nothing else but a wrapper around
[<-: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 thatreplace()is a bit more readibleBtw,
x.tst[s.tst==1] <- 0is 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 tox.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 :