Assign element to list in R

Viewed 64

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.

3 Answers

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"

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...

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"
Related