Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initialising list with given length and content

Say that I want to create a list of length 2, and fill each slice with the sequence 1:3 directly. I know that creating a list with pre-specified length can be done as

l <- vector("list", length = 2)

and all slices will be filled with NULL.

one way I've found is to use lapply:

lapply(l, function(x) x=1:3)

which will do it:

> l <- vector("list", length = 2)     
> lapply(l, function(x) x=1:3)

[[1]]
[1] 1 2 3

[[2]]
[1] 1 2 3

But is there a way to do it straight away?

like image 480
shitoushan Avatar asked Sep 19 '25 01:09

shitoushan


1 Answers

Here is an option with replicate

replicate(2, 1:3, simplify = FALSE)
#[[1]]
#[1] 1 2 3

#[[2]]
#[1] 1 2 3

Or apply rep on a list

rep(list(1:3), 2)
like image 178
akrun Avatar answered Sep 20 '25 14:09

akrun