首页 > 解决方案 > 将元素分配给R中的列表

问题描述

我们可以使用append函数将元素添加到列表中。例如像打击。

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

但我想这样做。append_new不返回但更改 a_list 。

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

函数可以使用它eval来执行此操作。

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

但是如果我想写函数add_element_to_list

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

函数怎么写?此功能类似assign但功能更强大。

post使用eval(parse(text=""))但不能写在自定义函数中append_new

标签: rpointersmethodsevalassign

解决方案


更简单:

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

推荐阅读