How to fill a list with vectors of different lengths in R?

Advertisements

My task is to create a list containing 100 vectors: c(1), c(1,2), c(1,2,3), … , c(1:100) in R.

I tried to do it using a for loop, but I don’t know how.

If possible, I would like a solution using the (l)apply function.

Thanks!

>Solution :

Using seq_len.

> lapply(1:100, seq_len)
[[1]]
[1] 1

[[2]]
[1] 1 2

[[3]]
[1] 1 2 3

[[4]]
[1] 1 2 3 4

[[5]]
[1] 1 2 3 4 5

[[6]]
[1] 1 2 3 4 5 6

[[7]]
[1] 1 2 3 4 5 6 7

[[8]]
[1] 1 2 3 4 5 6 7 8

[[9]]
[1] 1 2 3 4 5 6 7 8 9

[[10]]
 [1]  1  2  3  4  5  6  7  8  9 10

...

Leave a ReplyCancel reply