创建R对象的向量

问题描述 投票:1回答:1

我试图将一些igraph图形对象打包成一个向量。

首先,我初始化容器

x <- vector("list", 10)

我通过索引来构建向量:

for (i in 1:10) x[i] <- igraph::make_full_graph(10)

这引发了很多警告:

Warning messages:
1: In x[i] <- make_full_graph(10) :
  number of items to replace is not a multiple of replacement length

以下是有效的:

for (i in 1:10) x[[i]] <- igraph::make_full_graph(10)

我的问题是:由于我正在构建一个对象矢量,不应该[][[]]工作类似吗?

r igraph
1个回答
0
投票

我们可以使用lapply来创建图形对象的list。在这里,我们不需要在之前初始化list

lapply(1:10, function(x) igraph::make_full_graph(10))

关于OP的代码,list赋值应该是[[而不是[

for (i in 1:10) x[[i]] <- igraph::make_full_graph(10)

原因是x[i]没有提取list元素,它仍然是长度为1的list

x[1]
#[[1]]
#NULL

x[[1]]
#NULL
© www.soinside.com 2019 - 2024. All rights reserved.