SFu*_*n28 137 r increment operators variable-assignment
R有+=
(+等于)或++
(加上加号)的概念作为c ++/c#/其他人吗?
bap*_*ste 59
关注@GregaKešpret,您可以创建一个中缀运算符:
`%+=%` = function(e1,e2) eval.parent(substitute(e1 <- e1 + e2))
x = 1
x %+=% 2 ; x
Run Code Online (Sandbox Code Playgroud)
Gre*_*ret 33
R没有increment operator
(例如C中的++)的概念.但是,自己实现一个并不困难,例如:
inc <- function(x)
{
eval.parent(substitute(x <- x + 1))
}
Run Code Online (Sandbox Code Playgroud)
在那种情况下你会打电话
x <- 10
inc(x)
Run Code Online (Sandbox Code Playgroud)
但是,它引入了函数调用开销,所以它比键入自己慢x <- x + 1
.如果我没有被误解increment operator
,那么引入编译器的工作就更容易,因为它可以直接将代码转换为那些机器语言指令.
had*_*ley 17
R没有这些操作,因为R中的(大多数)对象是不可变的.他们不会改变.通常,当您看起来正在修改对象时,您实际上是在修改副本.
Wan*_*rer 15
递增和递减10.
require(Hmisc)
inc(x) <- 10
dec(x) <- 10
Run Code Online (Sandbox Code Playgroud)
我们发布了一个包,rooperators,来帮助处理这种事情。您可以在此处阅读更多相关信息:https : //happylittlescripts.blogspot.com/2018/09/make-your-r-code-nicer-with-roperators.html
install.packages('roperators')
require(roperators)
x <- 1:3
x %+=% 1; x
x %-=% 3; x
y <- c('a', 'b', 'c')
y %+=% 'text'; y
y %-=% 'text'; y
# etc
Run Code Online (Sandbox Code Playgroud)
我们可以覆盖+
. 如果使用一元+
并且其参数本身是一元+
调用,则在调用环境中增加相关变量。
`+` <- function(e1,e2){
# if unary `+`, keep original behavior
if(missing(e2)) {
s_e1 <- substitute(e1)
# if e1 (the argument of unary +) is itself an unary `+` operation
if(length(s_e1) == 2 &&
identical(s_e1[[1]], quote(`+`)) &&
length(s_e1[[2]]) == 1) {
# increment value in parent environment
eval.parent(substitute(e1 <- e1 + 1, list(e1 = s_e1[[2]])))
# else unary `+` should just return it's input
} else e1
# if binary `+`, keep original behavior
} else .Primitive("+")(e1, e2)
}
x <- 10
++x
x
# [1] 11
Run Code Online (Sandbox Code Playgroud)
其他操作不变:
x + 2
# [1] 13
x ++ 2
# [1] 13
+x
# [1] 11
x
# [1] 11
Run Code Online (Sandbox Code Playgroud)
但是不要这样做,因为你会减慢一切。或者在另一个环境中进行,并确保这些指令没有大循环。
你也可以这样做:
`++` <- function(x) eval.parent(substitute(x <- x + 1))
a <- 1
`++`(a)
a
# [1] 2
Run Code Online (Sandbox Code Playgroud)