问题
Does R have a concept of +=
(plus equals) or ++
(plus plus) as c++/c#/others do?
回答1:
No, it doesn't, see: R Language Definition: Operators
回答2:
Following @GregaKešpret you can make an infix operator:
`%+=%` = function(e1,e2) eval.parent(substitute(e1 <- e1 + e2))
x = 1
x %+=% 2 ; x
回答3:
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:
inc <- function(x)
{
eval.parent(substitute(x <- x + 1))
}
In that case you would call
x <- 10
inc(x)
However, it introduces function call overhead, so it's slower than typing x <- x + 1
yourself. If I'm not mistaken increment operator
was introduced to make job for compiler easier, as it could convert the code to those machine language instructions directly.
回答4:
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.
回答5:
Increment and decrement by 10.
require(Hmisc)
inc(x) <- 10
dec(x) <- 10
回答6:
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
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
回答7:
We can override +
. If unary +
is used and its argument is itself an unary +
call, then increment the relevant variable in the calling environment.
`+` <- 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
other operations don't change :
x + 2
# [1] 13
x ++ 2
# [1] 13
+x
# [1] 11
x
# [1] 11
Don't do it though as you'll slow down everything. Or do it in another environment and make sure you don't have big loops on these instructions.
You can also just do this :
`++` <- function(x) eval.parent(substitute(x <-x +1))
a <- 1
`++`(a)
a
# [1] 2
回答8:
There's another way of doing this, which i find very easy, maybe might be off some help
I use <<-
for these situation
The operators <<-
assigns the value to parent environment
inc <- function(x)
{
x <<- x + 1
}
and you can call it like
x <- 0
inc(x)
来源:https://stackoverflow.com/questions/5738831/r-plus-equals-and-plus-plus-equivalent-from-c-c-java-etc