2015-09-17 126 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