-1

I'm new to R and trying to understand a few things about lists. Say I have the following:

n = c(2, 3, 5) 
s = c("aa", "bb", "cc", "dd", "ee")
b = c(TRUE, FALSE, TRUE, FALSE, FALSE)
x = list(n, s, b, 3)

I understand the following (I think) because I'm asking R to return the second list of values (because I'm using single brackets).

x[2]
# [[1]]
# [1] "aa" "bb" "cc" "dd" "ee"

This I don't understand because I'm using double brackets which is supposed to return a single value. Actually, I'm not what I would expect R should return here. I'm asking for a single value but the second group of objects is another list.

x[[2]]
# [1] "aa" "bb" "cc" "dd" "ee"
Zheyuan Li
  • 71,365
  • 17
  • 180
  • 248
Randy Minder
  • 47,200
  • 49
  • 204
  • 358
  • @ZheyuanLi - I did take a look. "[[" selects a single element. So why is it returning five elements? – Randy Minder Jun 29 '16 at 23:54
  • 1
    @RandyMinder This list is composed of vectors -- the "list elements" are vectors. `[[` is returning a single vector. `[` returns another list of vector or vectors. – Matthew Lundberg Jun 30 '16 at 01:26

2 Answers2

5

It looks like you're using the exact example found here, although perhaps this is a common list example.

In essence, x[2] is a "slice", which is a list of length 1 that contains the second item of x. x[[2]] is the second item of x. You can verify this with class(x[2]) and class(x[[2]]).

Noah
  • 3,437
  • 1
  • 11
  • 27
-1

X has become a list of lists. If you just run x you should get all of its elements, then the x[[2]] result should make sense.

To get the first element of the second list, try x[[2]][1] which is saying "the first object in the second list of object x."

Another helpful trick in R is to use str(x) which shows you the structure of the object, in this case the type of lists and their contents.

Evan
  • 1,960
  • 4
  • 26
  • 54
  • I guess my major confusion here is why x[2] and x[[2]] return the exact same thing. They perform different operations. – Randy Minder Jun 29 '16 at 23:59
  • @RandyMinder - the `x` `list` you have has 4 single sub-structures, which are also `list`s. `x[[2]]` selects a **single** sub-structure, which is equivalent to the second `list` stored in `x` – thelatemail Jun 30 '16 at 00:02
  • But @RandyMinder, `x[2]` and `x[[2]]` do not return the same thing: one is a vector of five chars, one is a list with one element, that element being a vector with of five chars. Accessing this list is similar to [Inception](http://www.imdb.com/title/tt1375666/): `x[2]` is the same as `x[2][1]` same as `x[2][1][1][1][1]`, etc, and it is very important to see why this happens like it does with lists. – r2evans Jun 30 '16 at 14:03
  • @r2evans - Your explanation really helped. If you type this up as an answer, I'll accept it. – Randy Minder Jun 30 '16 at 15:43