Reputation: 598
I would like to ask if there is a way to refer to a list element name via a variable:
Labels <- vector(mode = "list") # Make a list called "Labels"
Labels[[1]] <- c(1,3,5,7) # Assign value to the first list element
names(Labels)[1] <- "Name" # Assign the name "Name" to the first list element
print(Labels)
print(Labels$Name)
# [1] 1 3 5 7
# Now I have the name of the first list element "Name"
# in the variable "ElementName"
ElementName <- "Name"
# How R will understand in the next line
# that I refer to the value "Name" of the variable "ElementName"
# in order to get
# [1] 1 3 5 7
print(Labels$ElementName)
Upvotes: 3
Views: 2365
Reputation: 886998
We can use [[
to extract the list
elements.
Labels[[ElementName]]
#[1] 1 3 5 7
If we are using the name of the list
element, we use quotes
Labels[['Name']]
#[1] 1 3 5 7
For more info, check ?"[["
or ?Extract
Upvotes: 4