๐ŸŽ“ A1Learner
๐Ÿ”
0 of 40 lessons completed

R Lists

A list holds values of different types in one object. Each part can be a single value or a whole vector.

A list with mixed types

This list holds a name, an age, a flag and a vector of scores. Printing it shows each part under its name.

lst <- list(name = "Ana", age = 30, member = TRUE, scores = c(8, 9, 10))
print(lst)

The value and the smaller list

Double brackets print the second part itself. Single brackets print a smaller list that still holds that part.

lst <- list(name = "Ana", age = 30, member = TRUE)
print(lst[[2]])
print(lst[2])

Read, count and change parts

The dollar sign reads the name part and length counts three parts. The first part then changes to Bo.

lst <- list(name = "Ana", age = 30, member = TRUE)
print(lst$name)
print(length(lst))
lst[[1]] <- "Bo"
print(lst[[1]])

Split text into a list

strsplit cuts the text at each comma and returns the pieces in a list. unlist flattens those pieces into a plain vector.

parts <- strsplit("a,b,c", ",")
print(parts)
print(unlist(parts))

Example

profile <- list(user = "Cy", visits = 12, premium = FALSE, badges = c("fast", "kind"))
print(profile$visits)
profile[[2]] <- 13
print(profile[[2]])
print(length(profile))

Key points

  • list() builds a list from named parts.
  • Printing a list shows each part under its name.
  • Double brackets return the part itself.
  • Single brackets return a smaller list.
  • The $ sign reads a part by its name.
  • length() counts the parts in a list.
  • strsplit() splits text and returns the pieces in a list.
  • unlist() flattens a list into a plain vector.

In this example, the list stores four parts of mixed types. The second part changes to 13 and length confirms the list still holds four parts.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท rdrr.io R Snippets

Exercise

What does lst[2] return?