在R列表中插入元素

hig*_*dth 3 dictionary r list vector

我想在"词典"中存储一些条目,以便我可以通过名称来检索它们.我可以像这样间接形成类似的东西:

> a = list(c(1,2),c(9,9,0,0))
> names(a) = c("first","second")
> a
$first
[1] 1 2

$second
[1] 9 9 0 0
Run Code Online (Sandbox Code Playgroud)

但是,我不能通过简单地按名称插入它们来做同样的事情:

> a=list()
> a["first"] = c(1,2)
Warning message:
In a["first"] = c(1, 2) :
  number of items to replace is not a multiple of replacement length
> a
$first
[1] 1
Run Code Online (Sandbox Code Playgroud)

为什么会这样,我应该使用什么语法将名称中的矢量或矩阵等对象插入列表?

jor*_*ran 6

你的问题是你正在使用[而不是[[.这应该工作:

a[['first']] <- c(1,2)
Run Code Online (Sandbox Code Playgroud)

应该这样:

a$first <- c(1,2)
Run Code Online (Sandbox Code Playgroud)

请记住,在访问特定元素[为您提供子列表.[[