如何获取列表列表的索引

时间:2015-02-06 07:19:03

标签: r structure

以下代码

library(gplots)
mydata <- mtcars
hclustfunc <- function(x) hclust(x, method="complete")
distfunc <- function(x) dist(x,method="euclidean")

# Compute cluster
d.mydata <- distfunc(mydata)
fit.mydata <- hclustfunc(d.mydata)
full_dend <- as.dendrogram(fit.mydata)
full_dend[]

生成此列表列表:

[[1]]
[[1]][[1]]   # <--- How to access this
[1] 31
attr(,"members")
[1] 1
attr(,"height")
[1] 0
attr(,"label")
[1] "Maserati Bora" # <--- of this
attr(,"leaf")
[1] TRUE

[[1]][[2]]
[[1]][[2]][[1]]
[[1]][[2]][[1]][[1]] # <--- How to access this
[1] 17
attr(,"members")
[1] 1
attr(,"height")
[1] 0
attr(,"label")
[1] "Chrysler Imperial" # <--- of this
attr(,"leaf")
[1] TRUE
 ....

有没有办法可以获得每个条目的最低级别索引, 所以最后我想像这样打印出来:

  Maserati Bora : 1.1
  Chrysler Imperial:  1.2.1.1
  ...etc...

或者更好的是数据框,以便我以后可以写入表格:

                      ancestry
  Maserati Bora       1.1
  Chrysler Imperial   1.2.1.1

1 个答案:

答案 0 :(得分:2)

尝试

 library(reshape2)
 lst <- rapply(full_dend, function(x) attr(x, 'label'), how='list')
 m1 <- melt(lst)
 library(gtools)
 m2 <- m1[mixedsort(colnames(m1))]

 ancestry <- apply(m2[-ncol(m2)], 1, function(x) 
               paste(na.omit(x), collapse='.'))
 d1 <- data.frame(names=m1[,'value'], ancestry, stringsAsFactors=FALSE)
 head(d1,3)
 #               names  ancestry
 #1      Maserati Bora       1.1
 #2  Chrysler Imperial   1.2.1.1
 #3 Cadillac Fleetwood 1.2.1.2.1

以下是&#34; lst&#34;

的前几个元素
 lst
 #[[1]]
 #[[1]][[1]]
 #[1] "Maserati Bora"

 #[[1]][[2]]
 #[[1]][[2]][[1]]
 #[[1]][[2]][[1]][[1]]
 #[1] "Chrysler Imperial"

 #[[1]][[2]][[1]][[2]]
 #[[1]][[2]][[1]][[2]][[1]]
 #[1] "Cadillac Fleetwood"