buzaku
buzaku

Reputation: 361

Creating a vector of R objects

I am trying to pack a few igraph graph objects into a vector.

First, I initialize the container

x <- vector("list", 10)

The I build the vector, by indexing in:

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

This throws up a lot of warnings like so:

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

The following works though:

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

My question is: Since I am building a vector of objects, shouldn't [] and [[]] work similarly?

Upvotes: 2

Views: 544

Answers (1)

akrun
akrun

Reputation: 887691

We can use lapply to create a list of graph objects. Here, we don't need to initialize a list before

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

Regarding the OP's code, the list assignment should be [[ instead of [

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

The reason is that x[i] is not extracting the list element, it is still a list of length 1

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

where as

x[[1]]
#NULL

Upvotes: 1

Related Questions