Lists in R Language

The post is about Lists in R Language. It is in the form of questions and answers for creating lists, updating and removing the elements of a list, and manipulating the elements of Listsin R Language.

What are Lists in R Language?

Lists in R language are the objects that contain elements of different data types such as strings, numbers, vectors, and other lists inside the list. A list can contain a matrix or a function as its elements. The list is created using the list() function in R. In other words, a list is a generic vector containing other objects. For example, in the code below, the variable $X$ contains copies of three vectors, n, s, b, and a numeric value 3.

n = c(2, 3, 5)
s = c("a", "b", "c", "d")
b = c(TRUE, FALSE, TRUE, TRUE, FALSE, TRUE)

# create an ex that contains copies of n, s, b, and value 3
x = list(n, s, b, 3)

Explain How to Create a List in R Language

Let us create a list that contains strings, numbers, and logical values. for example,

data <- list("Green", "Blue", c(5, 6, 7, 8), TRUE, 17.5, 15:20)
print(data)

The print(data) will result in the following output.

Lists in R Language

How to Access Elements of the Lists in R Language?

To answer this, let us create a list first, that contains a vector, a list, and a matrix.

data <- list(c("Feb","Mar","Apr"), 13.4, matrix(c(3,9,5,1,-2,8), nrow = 2))

Now let us give names to the elements of the list created above and stored in the data variable.

names(data) <- c("Months", "Value", "Matrix")

data

## Output
$Months
[1] "Feb" "Mar" "Apr"

$Value
[1] 13.4

$Matrix
     [,1] [,2] [,3]
[1,]    3    5   -2
[2,]    9    1    8

To access the first element of a list by name or by index, one can type the following command.

# access the first element of the list
data[1]   #or print(data[1])
data$Months

## Output
$Months
[1] "Feb" "Mar" "Apr"

Similarly, to access the third element, use the command

# access the third element of the list
data[3]   #or print(data[3])  #or  data[[3]]
data$Matrix

## Output
$Months
[1] "Feb" "Mar" "Apr"

How Elements of the List are Manipulated in R?

To add an element at the end of the list, use the command

data[4] <- "New List Element(s)"

To remove the element of a list use

# Remove the first element of a list
data[1] <- NULL

To update certain elements of a list

data[2] = "Updated Element"

Statistics and Data Analysts

Leave a Reply

Discover more from R Language Frequently Asked Questions

Subscribe now to keep reading and get access to the full archive.

Continue reading