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

前端 未结 9 680
攒了一身酷
攒了一身酷 2020-11-29 00:40

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

相关标签:
9条回答
  • 2020-11-29 01:17

    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.

    0 讨论(0)
  • 2020-11-29 01:19

    Increment and decrement by 10.

    require(Hmisc)
    inc(x) <- 10 
    
    dec(x) <- 10
    
    0 讨论(0)
  • 2020-11-29 01:20

    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)
    
    0 讨论(0)
  • 2020-11-29 01:21

    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.

    0 讨论(0)
  • 2020-11-29 01:27

    We can also use inplace

    library(inplace)
    x <- 1
    x %+<-% 2
    
    0 讨论(0)
  • 2020-11-29 01:29

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

    0 讨论(0)
提交回复
热议问题