AnyCompiler

Vectors vs. Lists

Every vector you've seen so far holds one type of thing throughout — all numbers, or all strings. A list() can hold a mix of anything: strings, numbers, logicals, even other lists, each slot independent of the others. This is R's answer to the kind of heterogeneous collection other languages build with tuples, objects, or structs.

Indexing a list with single brackets, lst[1], returns a smaller list containing that one element — still a list. Indexing with double brackets, lst[[1]], reaches inside and returns the element itself, unwrapped. This [ ] vs [[ ]] distinction is one of the most common sources of confusion for people new to R, and it matters: code expecting the raw string "R" will not behave correctly if it's handed a one-element list containing "R" instead.

lst <- list(name = "R", version = 4.0, active = TRUE)
print(lst[[1]])
print(lst[1])
print(class(lst[1]))
print(class(lst[[1]]))
Output
[1] "R"
$name
[1] "R"

[1] "list"
[1] "character"

lst[[1]] returned exactly "R", with class "character" — the raw value. lst[1] returned an entire named list — printed with its $name label and all — and its class is "list", not "character", even though it contains only that one string. Next: named lists and structures — reading and updating fields by name with $.

Practice exercise

Create lst <- list(1, "two", TRUE), then print class(lst[1]) and class(lst[[1]]) to see the difference between [ ] and [[ ]].