2

We can use append function to add element to list. For example like blow.

a_list <- list()
a_list <- append(a_list, "a")

But I want do to like this. The append_new don't return but change the a_list.

a_list <- list()
append_new(a_list, "a")

It can be used by eval function to do this.

a_list <- list()
eval(parse(text="a_list[[1]]<-a"))
a_list

But if I want to write the function add_element_to_list.

a_list <- list()
add_element_to_list(a_list, "a")
a_list  ##  same as list("a")

How to write the function? This function like assign but more powerful.

The post use eval(parse(text="")) but it can not write in the custom function append_new.

Hou ZeYu
  • 341
  • 1
  • 3
  • 11
  • Very related, [Why doesn't assign to a list element work?](https://stackoverflow.com/q/9561053/903061). It doesn't have a solution for your problem other than `eval(parse())`, but you could presumably write a wrapper for `eval(parse())`? – Gregor Thomas Feb 25 '20 at 17:41
  • I already read this post, but it can not help me to do the custom function. – Hou ZeYu Feb 25 '20 at 17:47

3 Answers3

1

Simpler:

`append<-` <- function(x, value) {
  c(x, value)
}

x <- as.list(1:3)
y <- as.list(1:3)
append(x) <- y
append(x) <- "a"
print(x)

[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 3

[[4]]
[1] 1

[[5]]
[1] 2

[[6]]
[1] 3

[[7]]
[1] "a"
thc
  • 9,527
  • 1
  • 24
  • 39
0

Perhaps something like this?

add_element_to_list <- function(this, that)
{
  if(typeof(this) != "list") stop("append_new requires a list as first argument")
  assign(deparse(substitute(this)), 
         append(this, that), 
         envir = parent.frame(),
         inherits = TRUE)
}

a_list <- list()

add_element_to_list(a_list, "a")

a_list 
#> [[1]]
#> [1] "a"

add_element_to_list(a_list, "b")

a_list 
#> [[1]]
#> [1] "a"
#> 
#> [[2]]
#> [1] "b"

I would be very cautious in using something like this in a package though, since it is not idiomatic R. In general, R users expect functions not to modify existing objects but to return new objects.

Of course there are some notable exceptions...

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
  • Yes, but I find the python can use self.method to do a lot of things. I can help me to reduce the code in main. So I want to try to write R-code like that style. But there are not self concept in R. – Hou ZeYu Feb 25 '20 at 18:00
0

Using evil parse:

append_new <- function(x, y){
  eval(parse(text = paste0(x, "[ length(", x, ") + 1 ]<<- '", y, "'")))
}

a_list <- list()

append_new(x = "a_list", y = "a")

a_list
# [[1]]
# [1] "a"

append_new(x = "a_list", y = "b")

a_list
# [[1]]
# [1] "a"
# 
# [[2]]
# [1] "b"
zx8754
  • 52,746
  • 12
  • 114
  • 209