英文:
Add element to a list dynamically instead of invoking the list name directly
问题
我已经使用这段代码创建了一个列表:
i=1
assign(paste0("dat",i,"_list"),list()) #创建一个名为dat1_list的空列表
我想要将一个数据框添加到该列表中,可以像这样做:
dat1_list[[1]]<-iris
然而,我不想直接硬编码列表的实际名称(就像上面的代码行中那样),而是需要动态使用其名称的组成部分("dat",i的当前值,"_list")。
我已经尝试使用paste0()
,就像我创建列表时所做的那样(代码的第二行),但我无法使其正常工作。
谢谢您的时间、关注和建议!Mark
英文:
I have created a list using this code:
i=1
assign(paste0("dat",i,"_list"),list()) #creates empty list called dat1_list
and I would like to add a dataframe to that list, which I can do like this:
dat1_list[[1]]<-iris
HOWEVER I don't want to call the list directly by hard coding its actual name (as in the line immediately above) but instead I need to use the constituents of its name ("dat", current value of i, "_list") dynamically.
I have tried using paste0() like I did to create the list (second line of code, above), but I can't make it work.
Thank you for your time, attention and advice! Mark
答案1
得分: 2
你可以这样做,但我认为这是一个糟糕的主意 - 这段代码很难编写和阅读。
```R
i=1
obj_name = paste0("dat",i,"_list")
## 初始化空列表
assign(obj_name,list())
## 验证
dat1_list
# list()
## 给列表的第一个项目分配一个值
assign(obj_name, `[[<-`(get(obj_name), i = 1, value = iris[1:3, ]))
## 验证
dat1_list
# [[1]]
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1 5.1 3.5 1.4 0.2 setosa
# 2 4.9 3.0 1.4 0.2 setosa
# 3 4.7 3.2 1.3 0.2 setosa
## 扩展
assign(obj_name, `[[<-`(get(obj_name), i = 2, value = 3:5))
## 验证
# [[1]]
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1 5.1 3.5 1.4 0.2 setosa
# 2 4.9 3.0 1.4 0.2 setosa
# 3 4.7 3.2 1.3 0.2 setosa
#
# [[2]]
# [1] 3 4 5
也许你最好使用一个列表的列表?
<details>
<summary>英文:</summary>
You can do it like this but I think it's a terrible idea - this code is hard to write and hard to read.
i=1
obj_name = paste0("dat",i,"_list")
initialize the empty list
assign(obj_name,list())
verify
dat1_list
list()
assign a value to the 1st item of the list
assign(obj_name, [[<-
(get(obj_name), i = 1, value = iris[1:3, ]))
verify
dat1_list
[[1]]
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
extend
assign(obj_name, [[<-
(get(obj_name), i = 2, value = 3:5))
verify
[[1]]
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
[[2]]
[1] 3 4 5
Perhaps you'd be better using a list of lists?
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论