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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With