How to fill a list with vectors of different length?

59 Views Asked by At

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

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

If possible, I would like a solution using the lapply function.

3

There are 3 best solutions below

2
jay.sf On BEST ANSWER

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

...
0
asd-tm On

You can do the following:

lapply(1:100, function(x) 1:x)

Or

lapply(1:100, \(x) 1:x)

It will return

[[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
Etc... 
0
KacZdr On

Here is how it should look using for loop. However, the above solutions with lapply are more preferred in R.

myList <- list()
for(i in 1:100) {
  myList[[i]] <- c(1:i)
}

Output:

> myList
[[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

...