R:+=(加等于)和++ (加加)相当于 c++/c#/java 等?
R 是否像 c++/c#/其他语言一样有 +=
(加等于)或 ++
(加加)的概念?
Does R have a concept of +=
(plus equals) or ++
(plus plus) as c++/c#/others do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
不,不是,请参阅:R 语言定义:运算符< /a>
No, it doesn't, see: R Language Definition: Operators
按照@GregaKešpret,您可以创建一个中缀运算符:
Following @GregaKešpret you can make an infix operator:
R 没有增量运算符的概念(例如 C 中的 ++)。然而,自己实现一个并不困难,例如:
在这种情况下,您会调用
但是,它会引入函数调用开销,因此它比键入
x <- x + 1 慢自己。如果我没记错的话,引入增量运算符是为了使编译器的工作更容易,因为它可以将代码直接转换为那些机器语言指令。
R doesn't have a concept of
increment operator
(as for example ++ in C). However, it is not difficult to implement one yourself, for example:In that case you would call
However, it introduces function call overhead, so it's slower than typing
x <- x + 1
yourself. If I'm not mistakenincrement operator
was introduced to make job for compiler easier, as it could convert the code to those machine language instructions directly.R 没有这些操作,因为 R 中的(大多数)对象是不可变的。它们不会改变。通常,当您看起来像是在修改对象时,实际上是在修改副本。
R doesn't have these operations because (most) objects in R are immutable. They do not change. Typically, when it looks like you're modifying an object, you're actually modifying a copy.
递增和递减 10。
Increment and decrement by 10.
我们发布了一个包,ropers,来帮助解决这类问题。您可以在这里阅读更多相关信息: https ://happylittlescripts.blogspot.com/2018/09/make-your-r-code-nicer-with-roperators.html
We released a package, roperators, to help with this kind of thing. You can read more about it here: https://happylittlescripts.blogspot.com/2018/09/make-your-r-code-nicer-with-roperators.html
我们可以覆盖
+
。如果使用一元+
并且其参数本身就是一元+
调用,则在调用环境中递增相关对象。其他操作不会改变:
我真的不能推荐它,因为你弄乱了出于某种原因而优化的原语。
We can override
+
. If unary+
is used and its argument is itself an unary+
call, then increment the relevant object in the calling environment.other operations don't change :
I can't really recommend it since you're messing with primitives which are optimised for a reason.
我们还可以使用
inplace
We can also use
inplace
如果你想在数组中使用
i++
来增加索引,你可以尝试i <- i + 1
,例如,但这里
<-
不能替换为=
,这不会更新索引,因为
=
和<-
并不总是等效的,正如?`<-`
中所述If you want to use
i++
in an array to increment the index, you can tryi <- i + 1
, for example,but here
<-
can NOT be replaced with=
, which does not update the index,since
=
and<-
are not always equivalent, as said in?`<-`
这是一种增加变量的更简单的方法。
您将得到如下结果
Here is a simpler approach to increment a variable.
You will get results as follows