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

让人想犯罪 __ 提交于 2019-12-03 05:03:23

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 ...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!