我有一个现有的清单:
mylist = list("player1"="Mike", "player2"="John")
我想添加一个名为“player17”的新元素“Sam”,除了名称存储在变量中:
new_name="player17"
所以我尝试了不同的语法:
c(mylist, new_name="Sam")
with(mylist, assign(new_name, "Sam"))
有没有办法在一个步骤中执行此操作(我知道我也可以使用函数names
在两个步骤中更改每个元素的名称)。
编辑,我的列表中的元素可以是data.frames。
答案 0 :(得分:1)
To append a value in a key we can
mylist[[key]] = c(mylist[[key]],'Sam')
For example,
mylist = list("player1"="Mike", "player2"="John")
mylist[["player1"]] = c(mylist[["player1"]],'Sam')
mylist
#$player1
#[1] "Mike" "Sam"
#$player2
#[1] "John"
This will also work if the key isn't already used
new_name="player17"
mylist[[new_name]] = c(mylist[[new_name]],'Sam')
#$player1
#[1] "Mike" "Sam"
#$player2
#[1] "John"
#$player17
#[1] "Sam"
EDIT : As per the update, if there are dataframes in our list we can use rbind
instead of c
mylist=list(a = mtcars, b = mtcars*10)
mylist[["c"]] = rbind(mylist[["c"]], mtcars/10)
and this works for the above example as well.