0

In my current explorations of R, I noted that if you start with the following list object:

l1 = c(1,2,3,4)

You can then access the 3rd item in l1 using the syntax:

l1[3] #-> 2

Meaning, to access list items by index, one can following the pattern

nameoflist[index_of_item]

However, if I try this with nested lists, say the following example...

l2 = list("a","b", c(1,2,3,4))

I notice that I can correctly access the items in the top level list using the syntax before. For example:

l2[1] #-> "a"
l2[2] #-> "b"
l2[3] #-> 1 2 3 4

But check what happens when I wish to access the 2nd item of the nested list (which is itself the 3rd item in the top level list as u see in the above example)

l2[3][2] #-> NULL 

But I expected to see 2 as the output of the above expression! Moreover, using the same above approach, but with index "1", returns the full list! And this happens for any extra [1]s you append to the expression! See the example below...

l2[3][1] #-> 1 2 3 4 
l2[3][1][1] #-> 1 2 3 4 
l2[3][1][1][1] #-> 1 2 3 4 

Weird!

So, what's happening here? I haven't yet seen R docs on how to access items in nested lists, so need some assistance here.

Update

I have noted that there's an explanation for how to use [[]] for such situations here, However, this scenario like mine might help others who don't even know about that operator yet. So, I doubt this question is exactly the same as the one linked to. That said, I've found 2 alternative ways to solve this...

JWL
  • 13,591
  • 7
  • 57
  • 63
  • 1
    `l2[[3]][2]` ... – jogo Jul 31 '19 at 08:56
  • @jogo thanks. Also found that using the more intuitive approach `l2[3][[1]][2]` is more readable (for us coming to R from say Python) – JWL Jul 31 '19 at 09:10
  • 1
    As part of understanding the difference between [ ] and [[ ]], you should also learn the difference between lists and atomic vectors. In R, the first object that you call a 'list', is not a list: is.list(c(1,2,3,4)) returns FALSE. c(1,2,3,4) is a vector, but not a list. – Joe Jul 31 '19 at 10:03
  • Alright @Joe ;-) – JWL Jul 31 '19 at 12:53

0 Answers0