My task is to create a list containing 100 vectors: c(1), c(1,2), c(1,2,3), ... , c(1:100).
list
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.
for
If possible, I would like a solution using the lapply function.
lapply
Using seq_len.
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 ...
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...
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 ...
Copyright © 2021 Jogjafile Inc.
Using
seq_len.