0

So I have a list (a1) of length two with a vector within each list element. Here is a simplified version.

a1 <- list(c(0, 1, 2), c(3, 4, 5))

How can I access an element within the vector of a list?

Like if I want to grab the number 2, i've tried the following without luck.

a1[1,][3]

Thanks

Austin Ulfers
  • 354
  • 6
  • 17
  • Please edit the first code block to have valid R code. I'm guessing this should be something like `a1 <- list(c(0, 1, 2), c(3, 4, 5))` – camille May 23 '18 at 20:57
  • Use double brackets for the first level, and single for the second, e.g. `a1[[1]][3]` will give you 2, `a1[[2]][2]` will give you 4. – mysteRious May 23 '18 at 21:59

1 Answers1

1

You need

a1[[1]][3]

a1 has only a single dimension, so there is no need for a comma. Since a1 is a list, selecting a1[1] is a list of length 1 containing the vector c(0, 1, 2). To get into the list, you need the second set of braces (a1[[1]]).

Melissa Key
  • 4,476
  • 12
  • 21
  • Is it any different if instead of it being a vector, it is another list? – Austin Ulfers May 23 '18 at 21:01
  • Yes. If the contents of `a1` is another list, you would need to access the third entry as `a1[[1]][[3]]` – Melissa Key May 23 '18 at 21:02
  • I used the `typeof()` function to see what it was and it turns out it is a list within `a1` but when I try to do the `[[x]][[y]]` it gives me `Error in .subset2(x, i) : subscript out of bounds` – Austin Ulfers May 23 '18 at 21:06
  • You need to clarify your question then - I'm not sure how to help you. What is `y`? how long is the list `y` is trying to access? What did you call `typeof` on? Please provide more details on exactly what you are doing and what you are trying to accomplish. – Melissa Key May 23 '18 at 21:10
  • Ok, I figured it out, I guess what I thought was a list within my list was actually a string that was just separated by commas which would explain why what you were explaining wasn't working. Thanks for the help! – Austin Ulfers May 23 '18 at 21:16