Assigning a value to a list item using `assign()`

后端 未结 1 2004
日久生厌
日久生厌 2021-02-07 06:51

A little bit of context first...

I\'ve written an infix function that in essence replaces the idiom

x[[length(x) +1]] <- y

..or simply

1条回答
  •  独厮守ぢ
    2021-02-07 07:08

    Suggest not using assign and instead:

    `%+=%`<- function(x, value) eval.parent(substitute(x <- append(x, value)))
    
    x <- 3
    x %+=% 5
    x
    ## [1] 3 5
    
    L <- list(a = 1, b = 2)
    L %+=% 3
    ## List of 3
    ## $ a: num 1
    ## $ b: num 2
    ## $  : num 3
    
    L <- list(a = 1, b = 2)
    L$a %+=% 4
    str(L)
    ## List of 2
    ##  $ a: num [1:2] 1 4
    ##  $ b: num 2
    

    or try +<- syntax which avoids the eval:

    `+<-` <- append
    
    # test
    x <- 3
    +x <- 1
    x
    ## [1] 3 1
    
    # test
    L<- list(a = 1, b = 2)
    +L <- 10
    str(L)
    ## List of 3
    ##  $ a: num 1
    ##  $ b: num 2
    ##  $  : num 10
    
    # test
    L <- list(a = 1, b = 2)
    +L$a <- 10
    str(L)
    ## List of 2
    ##  $ a: num [1:2] 1 10
    ##  $ b: num 2
    

    Or try this replacement function syntax which is similar to +<-.

    `append<-` <- append
    x <- 3
    append(x) <- 7
    ## [1] 3 7
    
    ... etc ...
    

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