Accessing R List Components
We can access components of an R list in two ways.
1. Access components by names:
All the components of a list can be named and we can use those names to access the components of the R list using the dollar command.
Example:
R
# R program to access # components of a list # Creating a list by naming all its components empId = c (1, 2, 3, 4) empName = c ( "Debi" , "Sandeep" , "Subham" , "Shiba" ) numberOfEmp = 4 empList = list ( "ID" = empId, "Names" = empName, "Total Staff" = numberOfEmp ) print (empList) # Accessing components by names cat ( "Accessing name components using $ command\n" ) print (empList$Names) |
$ID [1] 1 2 3 4 $Names [1] "Debi" "Sandeep" "Subham" "Shiba" $`Total Staff` [1] 4 Accessing name components using $ command [1] "Debi" "Sandeep" "Subham" "Shiba"
2. Access components by indices:
We can also access the components of the R list using indices.
To access the top-level components of a R list we have to use a double slicing operator “[[ ]]” which is two square brackets and if we want to access the lower or inner-level components of a R list we have to use another square bracket “[ ]” along with the double slicing operator “[[ ]]“.
Example:
R
# R program to access # components of a list # Creating a list by naming all its components empId = c (1, 2, 3, 4) empName = c ( "Debi" , "Sandeep" , "Subham" , "Shiba" ) numberOfEmp = 4 empList = list ( "ID" = empId, "Names" = empName, "Total Staff" = numberOfEmp ) print (empList) # Accessing a top level components by indices cat ( "Accessing name components using indices\n" ) print (empList[[2]]) # Accessing a inner level components by indices cat ( "Accessing Sandeep from name using indices\n" ) print (empList[[2]][2]) # Accessing another inner level components by indices cat ( "Accessing 4 from ID using indices\n" ) print (empList[[1]][4]) |
$ID [1] 1 2 3 4 $Names [1] "Debi" "Sandeep" "Subham" "Shiba" $`Total Staff` [1] 4 Accessing name components using indices [1] "Debi" "Sandeep" "Subham" "Shiba" Accessing Sandeep from na...
R – Lists
A list in R programming is a generic object consisting of an ordered collection of objects. Lists are one-dimensional, heterogeneous data structures.
The list can be a list of vectors, a list of matrices, a list of characters, a list of functions, and so on.
A list is a vector but with heterogeneous data elements. A list in R is created with the use of the list() function.
R allows accessing elements of an R list with the use of the index value. In R, the indexing of a list starts with 1 instead of 0.
Contact Us