Name Elements of List

To name elements of an R List, access names of this list using names() function, and assign a vector of characters.

In this tutorial, we will learn how to name elements of a list in R, using names() function, with the help of example programs.

Syntax

The syntax to assign names for elements in list myList is

names(myList) <- c(name1, name2, ...)

If the length of names vector is less than that of elements in the list, the name of elements which are not provided a name would get <NA> as name.

If the length of names vector is greater than that of elements in the list, R throws an error.

ADVERTISEMENT

Examples

In the following program, we will create a list with three elements, and set names for these elements using names() function.

Example.R

x <- list(TRUE, 25, "Apple")
names(x) <- c("In Stock", "Quantity", "Product")
print(x)

Output

$`In Stock`
[1] TRUE

$Quantity
[1] 25

$Product
[1] "Apple"

Length of Names less than that of List

Let us assign a vector for names whose length is less than the number of elements in the list.

Example.R

x <- list(TRUE, 25, "Apple")
names(x) <- c("In Stock", "Quantity")
print(x)

Output

$`In Stock`
[1] TRUE

$Quantity
[1] 25

$<NA>
[1] "Apple"

Length of Names greater than that of List

Let us assign a vector for names whose length is less than the number of elements in the list.

Example.R

x <- list(TRUE, 25, "Apple")
names(x) <- c("In Stock", "Quantity", "Product", "Origin")
print(x)

Output

Error in names(x) <- c("In Stock", "Quantity", "Product", "Origin") : 
  'names' attribute [4] must be the same length as the vector [3]

Conclusion

In this R Tutorial, we learned how to name elements of a List in R programming using names() function, with the help of examples.