Access Elements of List
To access elements of an R List, we may use index, or names of elements.
In this tutorial, we will learn how to access elements of a list in R, in different ways, with the help of example programs.
Examples
Access Elements using Index
In the following program, we will create a list with three elements, and read its elements using index.
Example.R
x <- list(TRUE, 25, "Apple") print(x[1]) print(x[2]) print(x[3])
Output
[[1]] [1] TRUE [[1]] [1] 25 [[1]] [1] "Apple"
We can also assign new values for elements in the list.
Example.R
x <- list(TRUE, 25, "Apple") x[2] = 38 print(x)
Output
[[1]] [1] TRUE [[2]] [1] 38 [[3]] [1] "Apple"
Access Elements using Names
In the following program, we will create a list with three elements, assign names to the elements, and read its elements using element names with $ operator.
Example.R
x <- list(TRUE, 25, "Apple") names(x) <- c("In Stock", "Quantity", "Product") print(x$'In Stock') print(x$Quantity) print(x$Product)
Output
[1] TRUE [1] 25 [1] "Apple"
Conclusion
In this R Tutorial, we learned how to access elements of a List in R programming using names() function, with the help of examples.