R: + = (plus equals) and ++ (plus plus) equivalent from C ++ / C # / java etc.?

Does R have the concept of += (plus equals) or ++ (plus plus), like C ++ / C # / others?

+136
operators variable-assignment increment r
Apr 21 '11 at 2:25
source share
7 answers
+101
Apr 21 '11 at 2:40
source share

Following @ GregaKešpret, you can make an infix operator:

 `%+=%` = function(e1,e2) eval.parent(substitute(e1 <- e1 + e2)) x = 1 x %+=% 2 ; x 
+59
Feb 17
source share

R has no concept of increment operator (as, for example, ++ in C). However, it is easy to implement them yourself, for example:

 inc <- function(x) { eval.parent(substitute(x <- x + 1)) } 

In this case, you would call

 x <- 10 inc(x) 

However, it enters the function overhead, so it is slower than entering x <- x + 1 yourself. If I am not mistaken, an increment operator was introduced to facilitate the work with the compiler, since it can directly convert the code into these machine language instructions.

+32
Apr 21 2018-11-11T00:
source share

R does not have these operations because (most) of the objects in R are immutable. They do not change. Usually, when it looks like you are modifying an object, you are actually modifying the copy.

+17
Apr 21 '11 at 3:14
source share

Increase and decrease by 10.

 require(Hmisc) inc(x) <- 10 dec(x) <- 10 
+15
Apr 21 2018-11-11T00:
source share

We have released a package, roperators to help with such things. 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 
+3
Sep 24 '18 at 21:44
source share

Just for fun:

 '+' <- function(e1,e2){ if(missing(e2)) { s_e1 <- substitute(e1) if(length(s_e1) == 2 && identical(s_e1[[1]], quote('+')) && length(s_e1[[2]]) == 1){ eval.parent(substitute(e1 <- e1 + 1,list(e1 = s_e1[[2]]))) } else e1 } else .Primitive("+")(e1,e2) } x <- 10 ++x x # [1] 11 

other operations do not change:

 x + 2 # [1] 13 x ++ 2 # [1] 13 +x # [1] 11 x # [1] 11 
+3
Jan 25 '19 at 14:38
source share



All Articles