Site icon Spark By {Examples}

How to Create a List in R?

create list in r

In R, you can create a list using the list() function. A list is a versatile data structure that can hold elements of different data types, including vectors, matrices, data frames, and even other lists, providing flexibility in handling heterogeneous data.

In this article, I will cover essential aspects of working with lists in R, demonstrating the creation of lists using the list() function and combining vectors to form lists. It also explores creating an empty list, concatenating lists, and accessing list elements by name or index. The tutorial further discusses updating, deleting elements, and converting lists into vectors and matrices.

Key points-

Create a List in R

The list() function in R is used to create a list. It combines multiple arguments of different types into a single list. You can access the elements using indexing or the names assigned to them. Let’s create a list with elements of different types using the list() function.


# Create a list using list()
my_list <- list(1, c("Welcome", "To", "Spark", "By", "Examples"), TRUE)
cat("Create  a list")
my_list

Yields below output.

Here, [[1]], [[2]], and [[3]] are the indices of the elements in the list. You can access individual elements of a list using double square brackets, like my_list[[2]] would give you the character vector c("Welcome", "To", "Spark", "By", "Examples").

create list in r

Create a List by Combining Vectors

Alternatively, you can create a list in R by combining more than two vectors. First, create a list of vectors and assign them to a variable(name). To combine these vectors you can use the list() function. After the creation of the list, you can assign names to list elements by using the names() function.


# Create a list by combining vectors
# Create a list
my_list <- list(c(11,11,33,44,44),
                c(32,32,33,22,22),
                c("spark","pyspark","R","java","jsp")
) 

# assign names to the list elements using names()
names(my_list) <- c("id", "pages", "name")
my_list

Yields below output.

create list in r

As you can see, the above code has created a list in R with three elements id, pages, and name. Each element is a vector of values.

Create an Empty List

You can create an empty list using the list() function in R. When we pass any elements inside the parenthesis of the list() you can create an empty list.


# Create an empty list
empty_list <- list()
empty_list

# Type of the object
class(empty_list)

# Length of the empty list
length(empty_list)

Yields below output.


# Output:
> empty_list
list()

> # Type of the object
> class(empty_list)
[1] "list"

> # Length of the empty list
> length(empty_list)
[1] 0

Create a List By concatenating the List with Another List

To concatenate one list with another list pass both lists to the c() function, this adds a second list to the end of the first list and returns a new list. Let’s create two lists (my_list and new_list) and concatenate them into a new list (concat_list) using list() function.


# Create a list by concatenating list with another list

# Create first list
my_list <- list(id = c(11,11,33,44,44),
                 pages = c(32,32,33,22,22),
                  name = c("spark","pyspark","R","java","jsp")
                ) 

# Create second list
my_list <- list(id = c(11,11,33,44,44),
                 pages = c(32,32,33,22,22),
                  name = c("spark","pyspark","R","java","jsp")
                ) 

# Concatenate the two lists
new_list <- list(duration = c("40days", "30days", "45days", "20days", "25days"))
concat_list <- c(my_list, new_list)
concat_list

The above code has created a new list named concat_list with four elements id, pages, name, and duration. The first three elements are taken from my_list, and the fourth component (duration) is added from new_list

Yields below output.


# Output:
> concat_list
$id
[1] 11 11 33 44 44

$pages
[1] 32 32 33 22 22

$name
[1] "spark"   "pyspark" "R"       "java"    "jsp"    

$duration
[1] "40days" "30days" "45days" "20days" "25days"

Access Elements from a List in R by Name

In R, you can access specified elements in a list by name using the $ operator or index using double square brackets [[]]. In this example, I will extract specified list elements by name using the $ operator.


# Access specified list elements by name

# Create a list
my_list <- list(id = c(11,11,33,44,44),
                 pages = c(32,32,33,22,22),
                  name = c("spark","pyspark","R","java","jsp")
                ) 
cat("Access specified element in a list by name")
my_list$name

Yields below output.


# Output:
Access specified element in a list by name
[1] "spark" "spark" "R"     "java"  "jsp"

Access Elements from a List in R by Index

Similarly, you can access the elements of the R list using indices. To get the top-level elements of the list you can specify with double square brackets [[ ]] and to get the lower or inner-level elements of an R list you can specify with a single square bracket [ ] along with the double square brackets [[ ]].


# Access specified list elements by index

# Create a list
my_list <- list(id = c(11,11,33,44,44),
                 pages = c(32,32,33,22,22),
                  name = c("spark","pyspark","R","java","jsp")
                ) 
cat("Access specified element in a list by name")
# Access top level elements
my_list[[3]]

# Access inner level elements
my_list[[3]][2]

Yields below output.


# Output:
Access specified element in a list by index
> my_list[[3]]
[1] "spark" "spark" "R"     "java"  "jsp"  

> my_list[[3]][2]
[1] "spark"

Update the List Elements in R

When we talk about updating a list, we refer to adding new elements to it. There are two ways to add elements to a list: top-level updation and inner-level updation. For top-level updation, you can use double square brackets([[]]). For inner-level updation, you need to use a single bracket([]) along with double-square brackets([[]]).


# Updating list elements
my_list <- list(id = c(11,11,33,44,44),
                pages = c(32,32,33,22,22),
                name = c("spark","pyspark","R","java","jsp")
)
# Update the the top-level element
my_list[[1]] = c(100, 101, 102, 103, 104)

# Update the the inner-level element
my_list[[3]][2] = "pandas"

cat("After updating the list\n")
my_list

Yields below output.


# Output:
After updating the list
> my_list
$id
[1] 100 101 102 103 104

$pages
[1] 32 32 33 22 22

$name
[1] "spark"  "pandas" "R"      "java"   "jsp"

Delete the List Elements

To delete elements of an R list, first, you can access those elements and then insert a negative sign before those elements. You can delete elements at both the top level of the list and the inner level of a specific element.


# Delete the list elements
my_list <- list(id = c(11,11,33,44,44),
                pages = c(32,32,33,22,22),
                name = c("spark","pyspark","R","java","jsp")
                ) 

# Delete a top level elements
cat("After Deleting element")
my_list[-3]

# Delete a inner level elements
cat("After Deleting element")
my_list[[2]][-2]

Yields below output.

The above code has returned the modified list without the “name” element at the top level and the second element in the “pages” vector at the inner level.


# Output:
After updating the list
> my_list
$id
[1] 100 101 102 103 104

$pages
[1] 32 32 33 22 22

$name
[1] "spark"  "pandas" "R"      "java"   "jsp"

Convert List to Vector

To convert a list to a vector in R use unlist() function. This function takes a list as one of the arguments and returns a Vector. A list in R is an object consisting of heterogeneous elements meaning can contain elements of different types whereas a vector in R is a basic data structure containing elements of the same data type.

Let’s pass the above-created list object my_list as an argument to unlist() function, this returns a vector with each element of the list.


# Convert list to vector

# Create list
my_list <- list(id = c(11,11,33,44,44),
                pages = c(32,32,33,22,22),
                name = c("spark","pyspark","R","java","jsp")
                ) 
vector <- unlist(my_list)
vector
class(vector)

# Output:
> print(vector)
      id1       id2       id3       id4       id5    pages1    pages2    pages3    pages4 
     "11"      "11"      "33"      "44"      "44"      "32"      "32"      "33"      "22" 
   pages5     name1     name2     name3     name4     name5 
     "22"   "spark" "pyspark"       "R"    "java"     "jsp"
> class(vector)
[1] "character"

Convert R List to matrix

To convert a list to a matrix you can use the matrix() function along with the unlist() function in R programming. First, create a list and pass it into the unlist() function along with nrow and byrow parameters and then use the matrix() function to create a matrix.


# Convert list to matrix
my_list <- list(id = c(11,11,33,44,44),
                pages = c(32,32,33,22,22),
                name = c("spark","pyspark","R","java","jsp")
                ) 

# Convert list to matrix
matrix <- matrix(unlist(my_list), nrow = 3, byrow = TRUE)

cat("\nAfter converting list to matrix")
matrix
class(matrix)

Yields below output.


# Output:
After converting list to matrix
> matrix
     [,1]    [,2]      [,3] [,4]   [,5] 
[1,] "11"    "11"      "33" "44"   "44" 
[2,] "32"    "32"      "33" "22"   "22" 
[3,] "spark" "pyspark" "R"  "java" "jsp"

> class(matrix)
[1] "matrix" "array"

Conclusion

In this article, I have explained the fundamental operations of the lists using the list() function, including creating, accessing, updating, and deleting elements. Additionally, it demonstrated how to convert lists into vectors and matrices for further analysis.

Happy learning!!

Exit mobile version