R Programming language - R List

htt‮www//:sp‬.theitroad.com

In R programming language, a list is a collection of values of different data types. A list can contain any combination of atomic vectors, matrices, other lists, and even functions. Here are some examples of lists in R:

list1 <- list(1:5, "hello", matrix(c(1, 2, 3, 4), nrow = 2), list("a", "b", "c"))
list2 <- list(c(1, 2, 3), c("apple", "banana", "orange"), list(TRUE, FALSE, TRUE))

In R, you can create a list using the list() function, which takes any number of arguments and combines them into a list. You can also create a list using the square bracket notation, like this:

list1 <- c(1:5, "hello", list(c(1, 2), matrix(c(3, 4), nrow = 1)))

In this case, the c() function combines the values into a vector, and the list() function creates a list with the vector and a matrix as elements.

You can access individual elements of a list using double square bracket notation, like this:

list1 <- list(1:5, "hello", matrix(c(1, 2, 3, 4), nrow = 2), list("a", "b", "c"))
print(list1[[1]]) # Output: 1 2 3 4 5
print(list1[[2]]) # Output: "hello"

You can also access entire sub-lists using single square bracket notation, like this:

list1 <- list(1:5, "hello", matrix(c(1, 2, 3, 4), nrow = 2), list("a", "b", "c"))
print(list1[3]) # Output: a 2x2 matrix

You can modify individual elements of a list using double square bracket notation and the assignment operator, like this:

list1 <- list(1:5, "hello", matrix(c(1, 2, 3, 4), nrow = 2), list("a", "b", "c"))
list1[[2]] <- "world"
print(list1[[2]]) # Output: "world"

You can also add elements to a list using the append() function or the concatenation operator, like this:

list1 <- list(1:5, "hello", matrix(c(1, 2, 3, 4), nrow = 2), list("a", "b", "c"))
list1 <- append(list1, "new element")
list1 <- c(list1, list("another list"))

Understanding how to work with lists in R is important for many data manipulation and analysis tasks, especially when working with complex data structures that require different types of values to be stored together.