list 在 R 中命名列表元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38643000/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Naming list elements in R
提问by RobertMyles
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
but:
但:
for(i in 1:3){
filList[i] <- Fil[i]
names(filList[i]) <- names(Fil[i])
}
identical(Fil,filList)
[1] FALSE
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?
我认为它让我感到困惑的主要原因是因为第names
一个 for 循环中第一行左侧的形式需要与右侧的形式不同才能工作;我会认为这些应该是一样的。有人可以向我解释一下吗?
回答by James
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.
第一种情况是正确的用法。在要发送的第二壳体filList[i]
到names<-
其只存在作为临时子集化对象。
Alternatively, you could just do everything outside the loop with:
或者,您可以使用以下命令在循环外执行所有操作:
names(filList) <- names(Fil)