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

前端 未结 9 814
攒了一身酷
攒了一身酷 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:38

    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
    

提交回复
热议问题