Martin
Martin

Reputation: 641

How to create a vector of lists in R?

I have a list (tmpList), which looks like this:

$op
[1] "empty"

$termset
$termset$field
[1] "entry"

$termset[[2]]
$termset[[2]]$explode
[1] "Y"

This is a list with a list inside. If I add this list to a vector

theOneVector = c(theOneVector, tmpList)

Now the resulting vector is of the length 2, because the first entry ("op") of the list is separated from the tmpList. Is it possible to append the complete tmpList into this vector?
I already tried it with

theOneVector = c(theOneVector, list(tmpList))

which gives a vector with the length of 1, but it is very cumbersome to access the elements of the list with this extra list around the list. (Too much list in one sentence I think.)

Any help would be appreciated,
Martin

Upvotes: 13

Views: 28914

Answers (3)

Raphvanns
Raphvanns

Reputation: 1894

I think a list() of list() is what you want.

Here is a simple example with lapply() which shows how to use them. Note that lapply() will apply the function provided to each element of the list given in argument and return a list containing the results of the individual executions.

> l1 = list(a = 10, b = 11)
> l2 = list(a = 20, b = 22)

> test_function <- function(l){
   return(paste("a =", l$a, "b = ", l$b, "\n"))
  }


# Do something to each element of the list 
# (i.e.: apply a function test_function() using lapply()). 
# This will return a list over which you can iterate.
# Each individual list l1 and l2 is "wrapped" into a single list: list(l1, l2)
> res = lapply(X = list(l1, l2), FUN = test_function)
> res
[[1]]
[1] "a = 10 b =  11 \n"

[[2]]
[1] "a = 20 b =  22 \n"

# First element of the results
> res[1]
[1] "a = 10 b =  11 \n"

# Second element of the results
> res[2]
[1] "a = 20 b =  22 \n"

Upvotes: 1

doug
doug

Reputation: 70028

the expression 'c(theOneVector, list(tmpList))' actually didn't return a vector of length 1, it returned a list (by coersion) because the items in a vector must all be of the same mode (data type).

Here's what you can do to create a container in R that will hold items of different mode and whose items are easy to access:

# create the container (an R 'list')
vx = vector(mode="list")

# create some items having different modes to put in it
item1 = 1:5
item2 = "another item"
item3 = 34
item4 = list(a = c(1:5), b = c(10:15))

# now fill the container 
vx$item1 = item1
vx$item2 = item2
vx$item3 = item3
vx$item4 = item4

# access the items in the container by name:
vx$item1
# returns: [1] 4 5 6
vx$item2
# returns: [1] "another item"

Upvotes: 1

Dirk is no longer here
Dirk is no longer here

Reputation: 368181

You can stick a vector (a restricted structure where all components have to be of the same type) into a list (unrestricted).

But you cannot do the reverse. Use lists of lists of lists ... and then use lapply et al to extract.

Upvotes: 18

Related Questions