为了模拟的目的,我想随机更改序列数据集中的状态。目标是查看集群质量的不同度量如何在数据中不同程度的结构下表现。
如果我要介绍缺失,TraMineRextras 中有一个方便的seqgen.missing()
功能,但它只会添加缺失状态。我将如何随机选择一部分p
序列并随机插入一个随机选择的字母表元素,其中p_g
,p_l
和p_r
概率将它们插入中间、左侧和右侧?
为了模拟的目的,我想随机更改序列数据集中的状态。目标是查看集群质量的不同度量如何在数据中不同程度的结构下表现。
如果我要介绍缺失,TraMineRextras 中有一个方便的seqgen.missing()
功能,但它只会添加缺失状态。我将如何随机选择一部分p
序列并随机插入一个随机选择的字母表元素,其中p_g
,p_l
和p_r
概率将它们插入中间、左侧和右侧?
下面是一个seq.rand.chg
函数(改编自seqgen.missing
),它将状态变化随机应用于一定比例p.cases
的序列。对于每个随机选择的序列,函数随机改变状态
当p.gaps > 0
, 在0
和p.gaps
的位置之间的比例;
当p.left > 0
和/或p.right > 0
,至多p.left
( p.right
) 比例左(右)位置。
与seqgen.missing
函数一样p.gaps
,p.left
、 和p.right
是每个选定序列中发生变化的案例的最大比例。这些并不完全是您的概率p_g
,p_l
和p_r
。但是应该很容易为此调整功能。
这是功能:
seq.rand.chg <- function(seqdata, p.cases=.1, p.left=.0, p.gaps=0.1, p.right=.0){
n <- nrow(seqdata)
alph <- alphabet(seqdata)
lalph <- length(alph)
lgth <- max(seqlength(seqdata))
nm <- round(p.cases * n, 0)
## selecting cases
idm <- sort(sample(1:n, nm))
rdu.r <- runif(n,min=0,max=p.right)
rdu.g <- runif(n,min=0,max=p.gaps)
rdu.l <- runif(n,min=0,max=p.left)
for (i in idm){
# inner positions
gaps <- sample(1:lgth, round(rdu.g[i] * lgth, 0))
seqdata[i,gaps] <- alph[sample(1:lalph, length(gaps), replace=TRUE)]
# left positions
nl <- round(rdu.l[i] * lgth, 0)
if (nl>0) seqdata[i,1:nl] <- alph[sample(1:lalph, nl, replace=TRUE)]
# right positions
nr <- round(rdu.r[i] * lgth, 0)
if (nr>0) seqdata[i,(lgth-nr+1):lgth] <- alph[sample(1:lalph, nr, replace=TRUE)]
}
return(seqdata)
}
我们用前三个mvad
数据序列来说明函数的用法
library(TraMineR)
data(mvad)
mvad.lab <- c("employment", "further education", "higher education",
"joblessness", "school", "training")
mvad.shortlab <- c("EM", "FE", "HE", "JL", "SC", "TR")
mvad.seq <- seqdef(mvad[, 17:62], states = mvad.shortlab,
labels = mvad.lab, xtstep = 6)
mvad.ori <- mvad.seq[1:3,]
## Changing up to 50% of states in 30% of the sequences
seed=11
mvad.chg <- seq.rand.chg(mvad.ori, p.cases = .3, p.gaps=0.5)
## plotting the outcome
par(mfrow=c(3,1))
seqiplot(mvad.ori, with.legend=FALSE, main="Original sequences")
seqiplot(mvad.chg, with.legend=FALSE, main="After random changes")
seqlegend(mvad.ori, ncol=6 )
我们观察到更改应用于随机选择的第三个序列。