在R中索引嵌套列表结构 [英] Indexing nested list structure in R
问题描述
我已经从STATA过渡到R,并且我正在尝试不同的数据类型,以使R的数据结构在我的脑海中清晰可见.
I have transitioned from STATA to R, and I was experimenting with different data types so that R's data structures are clear in my mind.
这是我设置数据结构的方式:
Here's how I set up my data structure:
b<-list(u=5,v=12)
c<-list(u=7)
j<-list(name="Joe",salary=55000,union=T)
bcj<-list(b,c,j)
现在,我正在尝试找出访问u = 5的不同方法.我相信可以通过三种方式:
Now, I was trying to figure out different ways to access u=5. I believe there are three ways:
Try1:
bcj[[1]][[1]]
我有5个.正确!
Try2:
bcj[[1]][["u"]]
我有5个.正确!
Try3:
bcj[[1]]$u
我有5个.正确!
Try4
bcj[[1]][1][1]
这就是我得到的:
bcj[[1]][1][1]
$u
[1] 5
class(bcj[[1]][1][1])
[1] "list"
问题1:为什么会发生这种情况?
我还尝试了以下方法:
bcj[[1]][1][1][1][1][1]
$u
[1] 5
class(bcj[[1]][1][1][1][1][1])
[1] "list"
问题2:我本来希望看到一个错误,因为我认为bcj中不存在太多列表,但是R给了我一个列表.为什么会发生这种情况?
PS:我确实在SO上查看了此线程,但这是在谈论一个不同的问题.
PS: I did look at this thread on SO, but it's talking about a different issue.
推荐答案
我认为这足以回答您的问题.考虑一个 length-1列表:
I think this is sufficient to answer your question. Consider a length-1 list:
x <- list(u = 5)
#$u
#[1] 5
length(x)
#[1] 1
x[1]
x[1][1]
x[1][1][1]
...
总是给您相同的东西
#$u
#[1] 5
换句话说,x[1]
将与x
相同,并且您将陷入无限递归.不管您写多少[1]
,您自己都会得到x
.
In other words, x[1]
will be identical to x
, and you fall into infinite recursion. No matter how many [1]
you write, you just get x
itself.
如果我创建
t1<-list(u=5,v=7)
,然后再执行t1[2][1][1][1]
...这也可以.但是,t1[[2]][2]
给出NA
If I create
t1<-list(u=5,v=7)
, and then dot1[2][1][1][1]
...this works as well. However,t1[[2]][2]
givesNA
这是索引列表时[[
和[
之间的区别.使用[
总是以列表结尾,而[[
会取出内容.比较:
That is the difference between [[
and [
when indexing a list. Using [
will always end up with a list, while [[
will take out the content. Compare:
z1 <- t1[2]
## this is a length-1 list
#$v
#[1] 7
class(z1)
# "list"
z2 <- t1[[2]]
## this takes out the content; in this case, a vector
#[1] 7
class(z2)
#[1] "numeric"
如上所述,当您执行z1[1][1]...
时,总是会遇到z1
本身.如果您执行z2[2]
,则肯定会得到一个NA
,因为z2
仅具有一个元素,而您要求的是第二个元素.
When you do z1[1][1]...
, as discussed above, you always end up with z1
itself. While if you do z2[2]
, you surely get an NA
, because z2
has only one element, and you are asking for the 2nd element.
也许这篇文章和我的回答对您有用:使用方括号和数字提取嵌套列表元素?
Perhaps this post and my answer there is useful for you: Extract nested list elements using bracketed numbers and names?
这篇关于在R中索引嵌套列表结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!