如何获取列表列表的索引
How to get index of list of list
代码如下
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...
或者更好的数据框,这样我可以稍后写入 table:
ancestry
Maserati Bora 1.1
Chrysler Imperial 1.2.1.1
尝试
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
这是"lst"
的前几个元素
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"
代码如下
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...
或者更好的数据框,这样我可以稍后写入 table:
ancestry
Maserati Bora 1.1
Chrysler Imperial 1.2.1.1
尝试
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
这是"lst"
的前几个元素 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"