Apollo
Apollo

Reputation: 9054

How to predefine the length of a list

How can I create a list of size n? For example, lines = read.table(filename, sep="\n") how would I create a list called linesCopy that is of the size of lines?

I tried something like linesCopy <- [[length(lines)]] but this throws unexpected token [[

Upvotes: 2

Views: 223

Answers (2)

Carlos Cinelli
Carlos Cinelli

Reputation: 11597

A list is just a vector, you can create a list of any size using vector().

For example, a list of size 4:

vector("list", 4)
[[1]]
NULL

[[2]]
NULL

[[3]]
NULL

[[4]]
NULL

Or, specific in your case, a list named linesCopy with the same size as the length of lines:

linesCopy <- vector("list", length(lines))

Upvotes: 9

Jordan
Jordan

Reputation: 715

I think that

linesCopy         <- list()
length(linesCopy) <- length(lines)

might do what you want. There's probably a prettier way to do it, but I can't think of it off the top of my head.

Upvotes: 0

Related Questions