0

how to access elements from a vector that resides in a list not clear why it works like in de code example l[2] is a vector l[2][1] is expected to refer to the 1st element of the vector

l <- list( 0, c(1,7,12))

l[2][1] # does not work, gives.....[1] 1  7  12

l[2][[1]][1] # does work as desired, gives [1] 1, but don no why
l[2][[1]][2] # gives [1] 7, as desired
BenJ
  • 23
  • 5
  • [This post](https://stackoverflow.com/q/1169456/5325862) should have you covered with the difference between `[` and `[[` – camille Apr 20 '20 at 19:33

3 Answers3

1

Your can access it using l[[2]][1]

you can look at the output of l to see how items are organised. This can give you a clue as to how to call them

> l
[[1]]
[1] 0

[[2]]
[1]  1  7 12
Daniel O
  • 4,258
  • 6
  • 20
0

In general, when you use the single bracket notation, R returns an element of the same class as the original object.

l is a list, so when you access an element of the list, e.g. l[2], R returns the element you asked for but wrapped in a list.

> l[2]
[[1]]
[1]  1  7 12

> class(l[2])
[1] "list"

If you want to "peel away" this layer, you use the double bracket syntax. R will then return the actual object at that index.

> l[[2]]
[1]  1  7 12

> class(l[[2]])
[1] "numeric"

Now you can access the elements of the vector.

> l[[2]][1]
[1] 1

> l[[2]][2]
[1] 7
Ryan H.
  • 7,374
  • 4
  • 39
  • 46
0

If we use pluck, it is more easier

library(purrr)
pluck(l, 2, 1)
#[1] 1
akrun
  • 874,273
  • 37
  • 540
  • 662