在R中命名列表元素 [英] Naming list elements in R
问题描述
最近我一直在处理一些大型的复杂列表,并且我已经看到了一些令人惊讶的行为(至少对我来说是令人惊讶的),主要是与为列表分配名称有关.一个简单的例子:
I've been doing some work with some large, complex lists lately and I've seen some behaviour which was surprising (to me, at least), mainly to do with assigning names to a list. A simple example:
Fil <- list(
a = list(A=seq(1, 5, 1), B=rnorm(5), C=runif(5)),
b = list(A="Cat", B=c("Dog", "Bird"), C=list("Squirrel", "Cheetah", "Lion")),
c = list(A=rep(TRUE, 5), B=rep(FALSE, 5), C=rep(NA, 5)))
filList <- list()
for(i in 1:3){
filList[i] <- Fil[i]
names(filList)[i] <- names(Fil[i])
}
identical(Fil,filList)
[1] TRUE
但是:
for(i in 1:3){
filList[i] <- Fil[i]
names(filList[i]) <- names(Fil[i])
}
identical(Fil,filList)
[1] FALSE
我认为它使我感到困惑的主要原因是,第一个for循环中第一条names
行的左侧形式需要与右侧的形式有所不同;我本以为这些应该是相同的.有人可以向我解释一下吗?
I think the main reason it confuses me is because the form of the left-hand side of first names
line in the first for loop needs to be different from that of the right-hand side to work; I would have thought that these should be the same. Could anybody please explain this to me?
推荐答案
第一种情况是正确用法.在第二种情况下,您将filList[i]
发送到names<-
,而names<-
仅作为临时子集对象存在.
The first case is the correct usage. In the second case you are sending filList[i]
to names<-
which is only exists as a temporary subsetted object.
或者,您可以使用以下方法完成循环外的所有操作:
Alternatively, you could just do everything outside the loop with:
names(filList) <- names(Fil)
这篇关于在R中命名列表元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!