I have a function that needs to return two two different types of groups of vectors. I could do this using a list consisting of two matrices, where the vectors, that I want to return, correspond to columns in the matrix, but since the vectors all have different lengths, I would like to save the vectors in a list themselves, so that I have a list consisting of two lists.
I would like to add the vectors to the sublists now, but don't know which indices to use.
For example if I would like to add the vector x to the first sublist in my list(call it l), how would I do that?
l[[1]] <- x
would only replace the first vector in the first sublist, but how could I access the second element in the sublist using indices?
To add elements to sublists, start with the list:
l <- list(list(1:3), list(5:8))
str(l)
Which looks like so:
List of 2
$ :List of 1
..$ : int [1:3] 1 2 3
$ :List of 1
..$ : int [1:4] 5 6 7 8
And add another vector inside a list:
l[[1]] <- c(l[[1]], list(100:103))
str(l)
Produces:
List of 2
$ :List of 2
..$ : int [1:3] 1 2 3
..$ : int [1:4] 100 101 102 103
$ :List of 1
..$ : int [1:4] 5 6 7 8
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