模拟练习数据
set.seed(8888)
id <- rep(1:15,each=10)#id号,1-15重复10次
time<-rep(1:10,15)#时间(天)1-10重复15次
map.raw <- abs((round(rnorm(150,mean = 50,sd = 25))))#随机取150个符合正态分布的平均动脉压
map<-round(ifelse(map.raw>=30,map.raw,map.raw+50))#保证没有小于30的平均动脉压
lac<-round(3-map*0.06+rnorm(150,mean = 0,sd = 0.4)-0.4*time*time+4.3*time,1)#乳酸值
lac.miss.tag<-rbinom(150,1,0.3)#取30%的缺失值
lac<-ifelse(lac.miss.tag==1,NA,lac)
age<-rep(round(abs(rnorm(15,mean = 65,sd = 19))),each=10)
data<- data.frame(id,time,age,map,lac)
abs(x)取x的绝对值
round(x)取x的整数
进行插补
A <- amelia(data,m = 5,ts = "time",cs = "id")
查看插补效果
tscsPlot(A,cs = c(3,4,5,6),var = "lac")
下图红点是插补的值,红线是其置信范围
可见置信范围较大,插补的效果不好
考虑时间因素,重新插补
A2<- amelia(data,m = 5,ts = "time",cs = "id",polytime = 2)
polytime#取0到3之间的整数,表示应在插补模型中包含多项式的幂以说明时间的影响。 设置为0将指示恒定水平,将1指示线性时间效应,将2指示平方效应,而将3指示立方时间效应。
可见插补效果很好
考虑缺失值前后数值影响
lags参数和leads参数
A3<- amelia(data,m = 5,ts = "time",cs = "id",lags = "lac",leads = "lac")
效果也不好
加入先验信息
有时候根据文献和经验,某一个缺失变量具有一定的取值范围
如lac均值为3的患者容易存活,而且其标准差为1.2
使用prior参数
You can provide Amelia with informational priors about the missing observations in your data. To specify priors, pass a four or five column matrix to the priors argument with each row specifying a different priors as such:
one.prior <- c(row, column, mean,standard deviation)
or,
one.prior <- c(row, column, minimum, maximum, confidence).
假设第4例患者存活,我们认为其乳酸水平符合经验
data[data$id==4,]
lac.prior<-matrix(c(31,32,37,38,5,5,5,5,3,3,3,3,1.2,1.2,1.2,1.2),nrow = 4,ncol = 4)
A4<- amelia(data,m = 5,ts = "time",cs = "id",priors = lac.prior)
插补值诊断:插补值是否合理
opar <- par(no.readonly=TRUE)
par(mfrow=c(2,2))
compare.density(A,var = "lac",main = "1")
compare.density(A2,var = "lac",main = "2")
compare.density(A3,var = "lac",main = "3")
compare.density(A4,var = "lac",main = "4")
par(opar)
当红蓝两条曲线重合程度越多时,证明插补越合理
opar <- par(no.readonly=TRUE)
par(mfrow=c(2,2))
overimpute(A,var = "lac",main = "1")
overimpute(A2,var = "lac",main = "2")
overimpute(A3,var = "lac",main = "3")
overimpute(A4,var = "lac",main = "4")
par(opar)
当点越靠近斜线周围时,插补越合理