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...