In R, you can use indexing operators to access, modify, or extract elements from a list. R has main 3 indexing operators. They are as follows :
- [ ] always returns a list with a single element.
- [[ ]] returns a object of the class of item contained in the list.
- $ returns elements from list that have names associated with it, not necessarily same class
Examples: Extracting Elements from List
To access a specific element in a list, you can use the [ ] operator with the index of the element you want to extract. The first element has an index of 1. It returns data in the form of list.
dat <- list( str='R', vec=c(1,2,3), bool=TRUE ) a = dat["str"]
class(a) returns "list". It means "a" is a list.
b = dat[["str"]]
class(b) returns "character". It means "b" is a character vector.
c = dat$str
class(c) returns "character". It means "c" is a character vector.
R Indexing Operators |
Both $ and [[ ]] works same. But it is advisable to use [[ ]] in functions and loops.
How to Extract Multiple Elements from List
You can extract multiple elements from the list using a vector of indices within the [ ] operator.
# Creating a list my_list <- list("apple", "banana", "orange", "grape") # Extracting elements at index 1 and 3 selected_elements <- my_list[c(1, 3)] print(selected_elements)Output:
[[1]] [1] "apple" [[2]] [1] "orange"
How to Modify Elements in a List
You can also use indexing operators to modify elements within a list.
# Creating a list my_list <- list("apple", "banana", "orange", "grape") # Modifying the element at index 2 my_list[2] <- "pear" print(my_list)Output:
[[1]] [1] "apple" [[2]] [1] "pear" [[3]] [1] "orange" [[4]] [1] "grape
How to extract a list of list
dat1 <- list( Bal02 = list( ivtable = data.frame(x=1, y=2, z=3), ivscore = 0.1 ) ) dat1$Bal02$ivtable
dat1$Bal02: This part of the code extracts the element with the name "Bal02" from the list dat1. It assumes that dat1 is a list, and within that list, there is an element named "Bal02", which is also a list.
$ivtable: After extracting the sublist "Bal02" using $Bal02, we further extract the element "ivtable" from this sublist using the $ operator. It assumes that the sublist "Bal02" contains an element named "ivtable".
You can also use the following command to extract a list of lists (sublist) in R.
dat1[[c("Bal02","ivtable")]]
Share Share Tweet