📚 R Programming Tutorial

R Programming

Learn R programming concepts with simple explanations, examples, techniques and practical notes.

← Back to R Programming

General List Operations

Lists in R are flexible data structures that allow storing heterogeneous data types. Here are common list operations:

List Indexing

In R, indexing allows the user to access elements from the list. For this purpose, there are three operators. Those are,

  • [ ] Operator
  • [[ ]] Operator
  • $ Operator

[ ] Operator

The [ ] operator is used to extract element(s) from a list. This allows us to extract multiple elements of a list.

Example:

> std_ls <- list(rno = 521, name = "Madhu", scores = c(82, 56, 74))
> std_ls[1]

Output:

$rno
[1] 521
> std_ls[2:3]

Output:

$name
[1] "Madhu"

$scores
[1] 82 56 74

[[ ]] Operator

The [[ ]] operator is used for extracting elements from list objects. This is the same as the [ ] operator, but the only difference is that [[ ]] selects only one element whereas the [ ] operator can select more than one element in a single command.

Example:

> std_ls <- list(rno = 521, name = "Madhu", scores = c(82, 56, 74))
> std_ls[[1]]  # Output: 521
> std_ls[[2]]  # Output: "Madhu"
> std_ls[[3]]  # Output: 82 56 74

Note: The [ ] operator always returns a list, whereas the [[ ]] operator returns the element itself.

The [[ ]] operator is mainly used to extract a nested element of a list.

Example:

> std_ls <- list(rno = 521, name = "Madhu", scores = c(82, 56, 74))
> std_ls[[3]][[2]]  # To access the second element of the third element
                    # Output: 56

$ Operator

The $ operator can be used for lists and data frames in R. Unlike the [ ] operator, it selects only a single element at a time. It can be used to access an element in a named list.

Example:

> std_ls <- list(rno = 521, name = "Madhu", scores = c(82, 56, 74))
> std_ls$rno        # Output: 521
> std_ls$name       # Output: "Madhu"
> std_ls$scores     # Output: 82 56 74
> std_ls$scores[2]  # Output: 56
> std_ls$scores[3]  # Output: 74