Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent of += (plus equals) in R [duplicate]

Does R have a concept of += (plus equals) or ++ (plus plus) as c++/c#/others do?

like image 709
SFun28 Avatar asked Apr 21 '11 02:04

SFun28


5 Answers

No, it doesn't, see: R Language Definition: Operators

like image 168
Patrick Cuff Avatar answered Oct 02 '22 01:10

Patrick Cuff


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

`%+=%` = function(e1,e2) eval.parent(substitute(e1 <- e1 + e2))
x = 1
x %+=% 2 ; x
like image 31
baptiste Avatar answered Oct 02 '22 02:10

baptiste


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.

like image 31
Grega Kešpret Avatar answered Oct 02 '22 03:10

Grega Kešpret


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.

like image 20
hadley Avatar answered Oct 02 '22 01:10

hadley


Increment and decrement by 10.

require(Hmisc)
inc(x) <- 10 

dec(x) <- 10
like image 44
Wanderer Avatar answered Oct 02 '22 03:10

Wanderer