2015-09-17 77 views
1

我想問一下,如果有一種方法,通過一個變量來指代一個列表元素名稱列表元素名稱:請參閱通過可變

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) 

回答

2

我們可以使用[[提取list元素。

Labels[[ElementName]] 
#[1] 1 3 5 7 

如果我們使用的是list元素的名稱,我們使用引號

Labels[['Name']] 
#[1] 1 3 5 7 

欲瞭解更多信息,請?"[["?Extract

+1

謝謝你很多akrun。我不知道。 – Apostolos