eager2learn
eager2learn

Reputation: 1488

Lists inside list, how to access elements?

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?

Upvotes: 5

Views: 37287

Answers (3)

droopy
droopy

Reputation: 2818

you can made a list of the two vectors :

l <- vector("list", 2)
l[[1]] <- 1:3
l[[1]] <- list(l[[1]],2:4)

Upvotes: 2

BrodieG
BrodieG

Reputation: 52637

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

Upvotes: 8

SetupX
SetupX

Reputation: 413

I don't understand what exactly you mean. But you can use a list containing two lists like this:

a=list();
a[[1]]=c(1,2,3);
a[[2]]=c(3,4,5);
a[['key']]=c(5,6,7)
a[[1]][1] //the first element in sublist 1
a[['key']][2] //the second element in sublist 'key'

if you want to store two vector, may be a matrix is what you waht

a[[1]]=cbind(a[[1]], c(2,3,4))
a[[1]][,1] //the first vector in sublist 1

Upvotes: 3

Related Questions