Ahdee
Ahdee

Reputation: 4949

Get named variable from list of list

this is probably trivial but can someone help me with this? I been using the apply to call a function that returns a list, as such l <- apply(df, 1, manydo); manydo function returns a list list("a" = a, "b" = b)

the output l appears to be a list of list, because when I type str(l) it returns

List of 5
 $ 1:List of 2
  ..$ a: Named num [1:36] 3.29 3.25 3.36 3.26 3.34 ...
  .. ..- attr(*, "names")= chr [1:36] "V1" "V2" "V3" "V4" ...
  ..$ b: Named num [1:36] 0.659 0.65 0.672 0.652 0.669 ...

I tried to access it many ways such as

l[1][1]
or l[1]['a']
unlist(l[1][1]['a'])

but nothing works. What I want is to be able to get for example, the first element and 'a' variable? in addition, if I just call the function directly say:

l <- manydo(c(1:36)) # I can access this
l['a'] # this works, so I'm confuse ;(

thanks!

Upvotes: 1

Views: 88

Answers (1)

Matthew Lundberg
Matthew Lundberg

Reputation: 42639

[ returns a list containing the selected elements. [[ returns a single element (not wrapped in a list), so that's what you want to use here.

l <- list(list(a=1:10, b=10:22), list(), list(), list(), list())
str(l)
## List of 5
##  $ :List of 2
##   ..$ a: int [1:10] 1 2 3 4 5 6 7 8 9 10
##   ..$ b: int [1:13] 10 11 12 13 14 15 16 17 18 19 ...

...

Now to retrieve a:

 l[[1]][['a']]
 [1]  1  2  3  4  5  6  7  8  9 10

l[[1]] is the list containing a. l[[1]][['a']] is the value of a itself.

Upvotes: 2

Related Questions