#############################################################################
# EXAMPLE 1: One chain nhanes data | application of 'with' and 'within'
#############################################################################
library(mice)
data(nhanes, package="mice")
set.seed(9090)
# nhanes data in one chain
imp <- mice.1chain( nhanes , burnin=5 , iter=40 , Nimp=4 )
# apply linear regression
res <- with( imp , expr = lm( hyp ~ age + bmi ) )
summary(res)
# pool results
summary(pool(res))
# calculate some descriptive statistics
res2 <- with( imp , expr = c( mean(hyp) , sd(age) ) )
res2
# convert mids object into an object of class imputationList
datlist <- mids2datlist( imp )
datlist <- mitools::imputationList(datlist)
# define formulas for modification of the data frames in imputationList object
datlist2 <- within.imputationList( datlist , {
age.D3 <- 1*(age == 3)
hyp_chl <- hyp * chl
} )
# look at modified dataset
head( datlist2$imputations[[1]] )
#############################################################################
# EXAMPLE 2: Nested multiple imputation and application of with/within methods
#############################################################################
library(BIFIEsurvey)
data(data.timss2 , package="BIFIEsurvey" )
datlist <- data.timss2
# remove first four variables
M <- length(datlist)
for (ll in 1:M){
datlist[[ll]] <- datlist[[ll]][ , -c(1:4) ]
}
# nested multiple imputation using mice
imp1 <- mice.nmi( datlist , m=4 , maxit=3 )
summary(imp1)
# apply linear model and use summary method for all analyses of imputed datasets
res1 <- with( imp1 , lm( ASMMAT ~ migrant + female ) )
summary(res1)
# convert mids.nmi object into an object of class NestedImputationList
datlist1 <- mids2datlist( imp1 )
datlist1 <- NestedImputationList( datlist1 )
# use with function
res1b <- with( datlist1 , glm( ASMMAT ~ migrant + female ) )
# use within function for data transformations
datlist2 <- within( datlist1 , {
highsc <- 1*(ASSSCI > 600)
books_dum <- 1*(books>=3)
rm(scsci) # remove variable scsci
} )
Run the code above in your browser using DataLab