Home > Blockchain >  How to Initialize an empty R list with a vector?
How to Initialize an empty R list with a vector?

Time:07-31

How can I create a list which is initialised with a vector of a given length?

For example empty_list <- vector("list", 10) creates an empty list with a length of 10 and can be all initialised with a value using empty_list[1:10] <- 25 but it's not possible to set their value to a vector and the following code results in error: empty_list[1:10] <- vector("numeric", 15).

Here is the error produced: Warning message: In empty_list[1:10] <- vector("numeric", 15) : number of items to replace is not a multiple of replacement length

I can do this using for loop:

empty_list <- vector("list", 10)

for (i in 1:11) { empty_list [[i]] <- vector("numeric", 15) }

But I am wondering if there is a better way than using for loop available.

CodePudding user response:

One possible way to solve your problem:

empty_list = rep_len(list(numeric(15)), 10)

CodePudding user response:

How about just using lapply or replicate()?

empty_list <-lapply(1:10, \(i) vector("numeric",15))

or

empty_list <- replicate(10, vector("numeric", 15),simplify = F)

If empty_list has already been created and has names, like this:

empty_list <- vector("list", 10)
names(empty_list) <- LETTERS[1:10]

then these names will be retained if you do this:

empty_list <-lapply(empty_list, \(i) vector("numeric",15))

Output:

$A
 [1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

$B
 [1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

$C
 [1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

$D
 [1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

$E
 [1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

$F
 [1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

$G
 [1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

$H
 [1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

$I
 [1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

$J
 [1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  • Related