2

使用作为一部分的 biofam 数据集TraMineR

library(TraMineR)
data(biofam)
lab <- c("P","L","M","LM","C","LC","LMC","D")
biofam.seq <- seqdef(biofam[,10:25], states=lab)
head(biofam.seq)
     Sequence                                    
1167 P-P-P-P-P-P-P-P-P-LM-LMC-LMC-LMC-LMC-LMC-LMC
514  P-L-L-L-L-L-L-L-L-L-L-LM-LMC-LMC-LMC-LMC    
1013 P-P-P-P-P-P-P-L-L-L-L-L-LM-LMC-LMC-LMC      
275  P-P-P-P-P-L-L-L-L-L-L-L-L-L-L-L             
2580 P-P-P-P-P-L-L-L-L-L-L-L-L-LMC-LMC-LMC       
773  P-P-P-P-P-P-P-P-P-P-P-P-P-P-P-P 

我可以进行聚类分析:

library(cluster)
couts <- seqsubm(biofam.seq, method = "TRATE")
biofam.om <- seqdist(biofam.seq, method = "OM", indel = 3, sm = couts)
clusterward <- agnes(biofam.om, diss = TRUE, method = "ward")
cluster3 <- cutree(clusterward, k = 3)
cluster3 <- factor(cluster3, labels = c("Type 1", "Type 2", "Type 3"))

然而,在这个过程中,来自 biofam.seq 的唯一 id 已被替换为从 1 到 N 的数字列表:

head(cluster3, 10)
[1] Type 1 Type 2 Type 2 Type 2 Type 2 Type 3 Type 3 Type 2 Type 1
[10] Type 2
Levels: Type 1 Type 2 Type 3

现在,我想知道每个簇内有哪些序列,以便我可以应用其他函数来获得每个簇内的平均长度、熵、子序列、相异度等。我需要做的是:

  1. 将旧 ID 映射到新 ID
  2. 将每个簇中的序列插入到单独的序列对象中
  3. 对每个新序列对象运行我想要的统计信息

我怎样才能完成上面列表中的 2 和 3?

4

2 回答 2

1

我想这会回答你的问题。我使用我在这里找到的代码http://www.bristol.ac.uk/cmm/software/support/workshops/materials/solutions-to-r.pdf来创建biofam.seq,因为你的建议都不适合我。

# create data
library(TraMineR)
data(biofam)
bf.states  <- c("Parent", "Left", "Married", "Left/Married", "Child",
                "Left/Child", "Left/Married/Child", "Divorced")
bf.shortlab <- c("P","L","M","LM","C","LC", "LMC", "D")
biofam.seq  <- seqdef(biofam[, 10:25], states = bf.shortlab,
                                       labels = bf.states)

# cluster
library(cluster)
couts <- seqsubm(biofam.seq, method = "TRATE")
biofam.om <- seqdist(biofam.seq, method = "OM", indel = 3, sm = couts)
clusterward <- agnes(biofam.om, diss = TRUE, method = "ward")
cluster3 <- cutree(clusterward, k = 3)
cluster3 <- factor(cluster3, labels = c("Type 1", "Type 2", "Type 3"))

首先,我使用split为每个集群创建一个索引列表,然后我在lapply循环中使用它来创建一个子序列列表biofam.seq

# create a list of sequences
idx.list <- split(seq_len(nrow(biofam)), cluster3)
seq.list <- lapply(idx.list, function(idx)biofam.seq[idx, ])

lapply最后,您可以使用或对每个子序列运行分析sapply

# compute statistics on each sub-sequence (just an example)
cluster.sizes <- sapply(seq.list, FUN = nrow)

whereFUN可以是您通常在单个序列上运行的任何功能。

于 2014-01-25T13:07:26.587 回答
1

例如,第一个集群的状态序列对象可以简单地获得

bio1.seq <- biofam.seq[cluster3=="Type 1",]
summary(bio1.seq)
于 2014-01-28T09:57:21.947 回答