替换()与“[<-"? [英] replace() vs "[<-"?
问题描述
我最近偶然发现了 replace()
和 "[<-"
.它们似乎具有类似的功能,例如使用 "[<-"
我可以这样做:
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
有人可以帮助澄清差异吗?replace
与 "[<-"
的优势是什么?反之亦然?
Can somebody help to clarify the difference? What are the strengths of replace
vs "[<-"
and vis versa?
推荐答案
它们基本上是一回事.如果你查看replace的源代码,你会看到:
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>
因此,replace 只不过是对 [<-
的包装:
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
如果您需要这样做一百万次,使用 [<-
可以为您提供加速,因为您会丢失对包装器函数的额外调用.但它真的很边缘,所以这是一个选择的问题.我会说 replace()
更易读
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
顺便说一句,x.tst[s.tst==1] <- 0
比 "[<-"(x.tst, s.tst==1, 0)
.没有理由使用该构造,除非您想将结果保存在新的数据框中.
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.
为了澄清,正如@Andrie 指出的,replace()
和 "[<-"(x.tst, s.tst==1, 0)代码> 你会得到整个 x.tst 的副本,并更改了相关值.所以你可以把它放在一个新对象中.这与
x.tst[s.tst==1] <- 0
不同,您可以在其中更改 x.tst 本身的值.请注意,它不会节省内存,因为 R 会在进行操作之前在内部制作 x.tst 的副本.
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.
计时结果:
> 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
这篇关于替换()与“[<-"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!