r - 将元素分配给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
。
解决方案
更简单:
`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"
推荐阅读
- java - git gc 似乎覆盖了一个包文件,使打开的文件描述符持有对“old-xxx.pack”的引用
- sql-server - 更改同一数据库中超过 3 个表中存在的相同 COLUMN 数据类型
- java - 从 TestRunner 运行时出现 NullPointerException,当我从功能文件单独运行时同样有效
- go - 在 Redis 中按值过滤(使用 go 和 redis-go)
- typescript - 使用参数模拟和测试 onError
- php - 在混合字符串中,将数组的字符键和数字设为 PHP 中的值
- google-cloud-platform - 谷歌云笔记本在进行推理时出现错误 524
- macos - 带有别名 zsh 的终端命令前面的奇怪数字和符号
- excel - 我不知道如何总结这个烂摊子,plz halp(每小时半小时的平均等待时间+每小时排队的人数)
- python-3.x - 更改或设置 matplotlib 表的字体属性