创建 R 对象的向量
Creating a vector of R objects
我正在尝试将几个 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)
我的问题是:由于我正在构建一个对象向量,所以 []
和 [[]]
的工作方式不应该相似吗?
我们可以使用 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
我正在尝试将几个 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)
我的问题是:由于我正在构建一个对象向量,所以 []
和 [[]]
的工作方式不应该相似吗?
我们可以使用 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