5

C and VB.NET (and perhaps some others) have convenient functions for incrementing a variable. E.g.:

x = 3
x +=5
# x now equals 8

Is there a way to define such an operator in R? I've tried:

`+=` <- function(x, y){x <<- x + y}

but no joy. That was based on the answer to this question.

Community
  • 1
  • 1
CJB
  • 1,759
  • 17
  • 26
  • 2
    a slight variation, but could you live with `'%+=%' <- function(x, y){x + y}` – Benjamin Aug 04 '15 at 13:22
  • Thanks Benjamin - that works (but edit it to `'%+=%' <- function(x, y){x <<- x + y}`). Why not put it as an answer? – CJB Aug 04 '15 at 13:28
  • 3
    @ChristopherBarry That wouldn't work. Unless you're planning on calling the variable `x` always. – Dason Aug 04 '15 at 13:29
  • the idea is more to use a replacement function like `add<-` <- function(n, value) n+value – Colonel Beauvel Aug 04 '15 at 13:33
  • I could be unpopular, but if you feel the need of such operator, very likely you are doing things not much R-ish. Good R programmers don't miss this operator. I can't remember last time I wrote the line `i<-i+1` in R, while `i++` or similar are omnipresent in many other languages. – nicola Aug 04 '15 at 13:35
  • Another useful thing might be adding an element to the end of a vector or data frame of arbitrary length without having to write its name twice. And sorry for the duplicate question - didn't come up when I searched. The answer appears to be `'%+=%' = function(e1,e2) eval.parent(substitute(e1 <- e1 + e2))`. – CJB Aug 04 '15 at 13:40

0 Answers0