### Wald Test Example Placeholder Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/man/NMIwaldtest.Rd This snippet represents the start of the example block provided in the documentation. ```R ############################################################################# ``` -------------------------------- ### Load or Install R Packages Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/man/library_install.Rd Demonstrates how to use library_install to ensure specific packages are loaded, installing them automatically if necessary. ```R # try to load packages PP and MCMCglmm library_install( pkg=c("PP", "MCMCglmm") ) ``` -------------------------------- ### library_install(pkg, ...) Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/man/library_install.Rd Loads a vector of packages and installs any missing ones using install.packages. ```APIDOC ## library_install(pkg, ...) ### Description Loads packages specified in a vector. If any packages are not yet installed, they are automatically installed using the utils::install.packages function. ### Arguments - **pkg** (vector) - Required - A vector containing the names of the packages to be loaded. - **...** (dots) - Optional - Further arguments to be passed to the underlying install.packages function. ### Example library_install(pkg=c("PP", "MCMCglmm")) ``` -------------------------------- ### Install miceadds from GitHub Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/README.md Use this command to install the development version of the package directly from the GitHub repository. ```r devtools::install_github("alexanderrobitzsch/miceadds") ``` -------------------------------- ### Source R files from a directory Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/man/source.all.Rd Example of sourcing all R files containing a specific string pattern within a directory. ```R # define path path <- "c:/myfiles/" # source all files containing the string 'Rex' source.all( path, "Rex" ) ``` -------------------------------- ### Configure PLS imputation methods and arguments Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/man/mice.impute.pls.Rd Setup the imputation methods and specific arguments required for PLS imputation. ```R # choose norm or pmm imputation method pls.impMethod <- as.list( rep("norm", length(impMethod) ) ) names(pls.impMethod) <- names(impMethod) pls.impMethod[ c("IN1","IN6")] <- "pmm" # some arguments for imputation method pls.impMethodArgs <- list( "IN1"=list( "donors"=10 ), "IN2"=list( "ridge2"=1E-4 ) ) ``` -------------------------------- ### Copying an Rcpp function to the working directory Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/man/cxxfunction.copy.Rd This example demonstrates defining an Rcpp function, compiling it with inline::cxxfunction, and then using cxxfunction.copy to save it as a named object. ```R library(Rcpp) library(inline) # define Rcpp file code1 <- " // input array A Rcpp::NumericMatrix AA(A); // Rcpp::IntegerVector dimAA(dimA); int nrows=AA.nrow(); int ncolumns=AA.ncol(); Rcpp::NumericMatrix Alogis(nrows,ncolumns) ; // compute logistic distribution for (int ii=0; ii LM: latent group mean # define predictor matrix predM <- mice::make.predictorMatrix(data=dat) # exclude student ISs predM[, "idstud"] <- 0 # idclass is the cluster identifier predM[, "idclass" ] <- -2 # define imputation methods impMethod <- mice::make.method(data=dat) # initialize with norm impMethod <- rep( "norm", length(impMethod) ) names(impMethod) <- names( imp$method ) impMethod[ c("idstud","idclass")] <- "" #***** # STUDENT LEVEL (Level 1) # Use a random slope model for Dscore and Mscore as the imputation method. # Here, variance homogeneity of residuals is assumed (contrary to # the 2l.norm imputation method in the mice package). impMethod[ c("Dscore", "Mscore") ] <- "2l.pan" predM[ c("Dscore","Mscore"), "misei" ] <- 2 # random slopes on 'misei' predM[, "idclass" ] <- -2 # For imputing 'manote' and 'denote' use contextual effects (i.e. cluster means) # of variables 'misei' and 'migrant' impMethod[ c("denote", "manote") ] <- "2l.contextual.pmm" predM[ c("denote", "manote"), c("misei","migrant")] <- 2 # Use no cluster variable 'idclass' for imputation of 'misei' impMethod[ "misei"] <- "norm" predM[ "misei", "idclass"] <- 0 # use no multilevel imputation model ``` -------------------------------- ### Install miceadds from CRAN Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/README.md Use this command to install the stable version of the package from the Comprehensive R Archive Network. ```r utils::install.packages("miceadds") ``` -------------------------------- ### Perform Wald test on multiply imputed data Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/man/NMIwaldtest.Rd This example shows the workflow of fitting linear models to imputed datasets, extracting the necessary parameters, and applying the MIwaldtest function. ```R # linear regression res2 <- lapply( datlist_imp, FUN=function(data){ miceadds::lm.cluster( data=data, formula=likesc ~ female*migrant + female*books, cluster=idschool ) } ) # extract parameters and covariance matrix qhat <- lapply( res2, FUN=function(rr){ coef(rr) } ) u <- lapply( res2, FUN=function(rr){ vcov(rr) } ) # perform Wald test wres2 <- miceadds::MIwaldtest( qhat, u, Cdes, rdes ) summary(wres2) ``` -------------------------------- ### Generate string combinations with str_C.expand.grid Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/man/str_C.expand.grid.Rd Demonstrates basic usage of str_C.expand.grid with simple lists and optional index permutation. ```R x1 <- list( c("a","b" ), c("t", "r","v") ) str_C.expand.grid( x1 ) ## [1] "at" "bt" "ar" "br" "av" "bv" x1 <- list( c("a","b" ), paste0("_", 1:4 ), c("t", "r","v") ) str_C.expand.grid( x1, indices=c(2,1,3) ) ## [1] "_1at" "_1bt" "_2at" "_2bt" "_3at" "_3bt" "_4at" "_4bt" "_1ar" "_1br" ## [11] "_2ar" "_2br" "_3ar" "_3br" "_4ar" "_4br" "_1av" "_1bv" "_2av" "_2bv" ## [21] "_3av" "_3bv" "_4av" "_4bv" ``` -------------------------------- ### Initialize mice imputation arguments Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/man/mice_inits.Rd Demonstrates how to generate initial imputation settings for a dataset while ignoring specific variables. ```R ############################################################################# # EXAMPLE 1: Inits for mice imputation ############################################################################# data(data.ma04, package="miceadds") dat <- data.ma04 res <- miceadds::mice_inits(dat, ignore=c("group") ) str(res) ``` -------------------------------- ### Create a datlist object Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/man/datlist_create.Rd Initializes a datlist object from an existing dataset. ```R library(BIFIEsurvey) data(data.timss2, package="BIFIEsurvey" ) datlist <- data.timss2 # class datlist obj1 <- miceadds::datlist_create(data.timss2) ``` -------------------------------- ### Remove CF line endings from a file Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/man/crlrem.Rd Example usage of the crlrem function to process a source file and save it as a new file. ```R filename1 <- "rm.arraymult__0.02.cpp" filename2 <- "rm.arraymult__0.03.cpp" crlrem( filename1, filename2 ) ``` -------------------------------- ### Scan from file Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/man/scan.vector.Rd Demonstrates the use of scan0 for reading input. ```R ## the next lines are only commented out to fulfill CRAN checks ## vars2 <- miceadds::scan0() ## female urbgrad groesse Nausg grpgroesse privat ``` -------------------------------- ### Save a data frame using save.Rdata Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/man/save.Rdata.Rd Saves a matrix or data frame to an Rdata file. The example is wrapped in dontrun as it performs file system operations. ```R dfr <- matrix( 2*1:12-3, 4,3 ) save.Rdata( dfr, "dataframe_test" ) ``` -------------------------------- ### Synthesize data using mice imputation methods Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/man/syn.mice.Rd Demonstrates how to integrate mice imputation methods like 'rlm' and 'pmm' into the synthpop synthesis process by defining custom method and argument lists. ```R library(synthpop) #** selection of dataset data(SD2011, package="synthpop") vars <- c("sex","age","ls","smoke") dat <- SD2011[1:1000, vars] dat$ls <- as.numeric(dat$ls) dat$smoke <- 1*(paste(dat$smoke)=="YES") #** default synthesis imp0 <- synthpop::syn(dat) pred <- imp0$predictor.matrix method <- imp0$method #** use mice imputation method 'rlm' for variable 'ls' method[c("ls","smoke")] <- c("mice","mice") mice_fun <- list( ls="rlm", smoke="pmm") mice_args <- list( ls=list( trafo=log, antitrafo=exp) ) #* synthesize data imp <- synthpop::syn( dat, method=method, predictor.matrix=pred, k=2000, m=1, rf.mice_fun=mice_fun, rf.mice_args=mice_args) summary(imp) ``` -------------------------------- ### Calculate Descriptive Statistics with stats0 Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/man/stats0.Rd Demonstrates the usage of various descriptive statistics functions on simulated data, comparing them with standard apply calls. ```R ############################################################################# # EXAMPLE 1: Descriptive statistics toy datasets ############################################################################# #--- simulate vector y and data frame dat set.seed(765) N <- 25 # number of observations y <- stats::rnorm(N) V <- 4 # number of variables dat <- matrix( stats::rnorm( N*V ), ncol=V ) colnames(dat) <- paste0("V",1:V) #-- standard deviation apply( dat, 2, stats::sd ) sd0( dat ) #-- mean apply( dat, 2, base::mean ) mean0( dat ) #-- quantile apply( dat, 2, stats::quantile ) quantile0( dat ) #-- minimum and maximum min0(dat) max0(dat) #*** apply functions to missing data dat1 <- dat dat1[ cbind( c(2,5),2) ] <- NA #-- proportion of missing data prop_miss( dat1 ) #-- MAD statistic stats0( dat, FUN=stats::mad ) #-- SD sd0(y) ``` -------------------------------- ### write.pspp(data, datafile, pspp.path, decmax=6, as.factors=TRUE, use.bat=FALSE) Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/man/write.pspp.Rd Writes a data frame into SPSS format using the PSPP software. Requires a local installation of PSPP. ```APIDOC ## write.pspp ### Description Writes a data frame into SPSS format using the PSPP software. To use this function, download and install PSPP first. ### Parameters - **data** (data frame) - The data frame to be exported. - **datafile** (string) - Name of the output file (without file ending). - **pspp.path** (string) - Path where the PSPP executable is located. - **decmax** (numeric) - Maximum number of digits after decimal. Default is 6. - **as.factors** (logical) - Whether all factors and string entries should be treated as factors in the output file. Default is TRUE. - **use.bat** (logical) - Whether PSPP is executed via a batch file in DOS mode (TRUE) or directly invoked via the system command (FALSE). Default is FALSE. ### Returns A dataset in .sav (SPSS) format. ``` -------------------------------- ### Synthesize fixed values for a variable Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/man/syn.constant.Rd Demonstrates how to use the constant method to synthesize a variable with fixed values in the synthpop package. ```R library(synthpop) #** selection of dataset data(SD2011, package="synthpop") vars <- c("sex","age","ls","smoke") dat <- SD2011[1:1000, vars] dat$ls <- as.numeric(dat$ls) #** default synthesis imp0 <- synthpop::syn(dat) pred <- imp0$predictor.matrix method <- imp0$method #** constant vector method["sex"] <- "constant" fixed_values <- data.frame( sex=rep(dat$sex[c(1,2)], each=1000) ) imp <- synthpop::syn( dat, method=method, k=2000, m=1, rf.fixed_values=fixed_values) table(imp$syn$sex) ``` -------------------------------- ### source.all(path, grepstring, print.source, file_sep) Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/man/source.all.Rd Sources all R files within a specified directory. ```APIDOC ## source.all ### Description Sources all R files within a specified directory based on base::source. ### Parameters - **path** (string) - Required - Path where the files are located. - **grepstring** (string) - Optional - Which strings should be looked for (can be a vector). - **print.source** (logical) - Optional - Whether the source process is printed on the console. - **file_sep** (string) - Optional - String at which file name should be split for looking for most recent files. ``` -------------------------------- ### Three-level data imputation configuration Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/man/mice.impute.ml.lmer.Rd Setup for imputing missing values in a three-level dataset using ml.lmer for level 1 and 2 variables and 2lonly.norm for level 3 variables. ```R data(data.ma07, package="miceadds") dat <- data.ma07 # variables at level 1 (identifier id1): x1 (some missings), x2 (complete) # variables at level 2 (identifier id2): y1 (some missings), y2 (complete) # variables at level 3 (identifier id3): z1 (some missings), z2 (complete) #**************************************************************************** # Imputation model 1 #----- specify levels of variables (only relevent for variables # with missing values) variables_levels <- miceadds:::mice_imputation_create_type_vector( colnames(dat), value="") # leave variables at lowest level blank (i.e., "") variables_levels[ c("y1","y2") ] <- "id2" variables_levels[ c("z1","z2") ] <- "id3" #----- specify predictor matrix predmat <- mice::make.predictorMatrix(data=dat) predmat[, c("id2", "id3") ] <- 0 # set -2 for cluster identifier for level 3 variable z1 # because "2lonly" function is used predmat[ "z1", "id3" ] <- -2 #----- specify imputation methods method <- mice::make.method(data=dat) method[c("x1","y1")] <- "ml.lmer" method[c("z1")] <- "2lonly.norm" #----- specify hierarchical structure of imputation models levels_id <- list() #** hierarchical structure for variable x1 levels_id[["x1"]] <- c("id2", "id3") #** hierarchical structure for variable y1 levels_id[["y1"]] <- c("id3") #----- specify random slopes random_slopes <- list() #** random slopes for variable x1 random_slopes[["x1"]] <- list( "id2"=c("x2"), "id3"=c("y1") ) ``` -------------------------------- ### max0(x, na.rm=TRUE), mean0(x, na.rm=TRUE), min0(x, na.rm=TRUE), sd0(x, na.rm=TRUE), var0(x, na.rm=TRUE) Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/man/stats0.Rd Wrapper functions for calculating maximum, mean, minimum, standard deviation, and variance. ```APIDOC ## max0, mean0, min0, sd0, var0 ### Description Calculates the maximum, mean, minimum, standard deviation, or variance for a vector or data frame. ### Parameters - **x** (Vector/Data Frame) - Required - The input data. - **na.rm** (Logical) - Optional - Indicates whether missing data should be removed (default: TRUE). ``` -------------------------------- ### Process descriptive information from articles Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/man/filename_split.Rd Demonstrates reading correlations and processing data structures using string_to_matrix. ```R data(data.ma08) library(stringr) #**** reading correlations (I) dat <- data.ma08$mat1 miceadds::string_to_matrix(dat, rownames=2, col_elim=c(1,2)) #**** reading correlations including some processing (II) dat0 <- data.ma08$mat2 dat <- dat0[1:14] ``` -------------------------------- ### Write and read a file in fixed width format Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/man/write.fwf2.Rd Demonstrates saving a data frame to a fixed-width file and reading it back into R. ```R path <- "P:/ARb/temp" setwd(path) # define a data frame set.seed(9876) dat <- data.frame( "x"=seq( 1, 21, len=5), "y"=stats::runif( 5 ), "z"=stats::rnorm( 5 ) ) # save data frame in fixed width format format.full <- c(6, 6, 8 ) format.round <- c( 0, 2, 3 ) write.fwf2( dat, format.full=format.full, format.round=format.round, file="testdata" ) # read the data dat1 <- miceadds::read.fwf2( file="testdata.dat", format.full=c(6,6,8), variables=c("x","y","z") ) # check differences between data frames dat - dat1 ``` -------------------------------- ### Impute missing data with linear and robust models Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/man/mice.impute.rlm.Rd Demonstrates setting up imputation methods for different variables using rlm, lm, and lqs, and applying transformations during the imputation process. ```R ############################################################################# # EXAMPLE 1: Some toy example illustrating the methods ############################################################################# library(MASS) library(mice) #-- simulate data set.seed(98) N <- 1000 x <- stats::rnorm(N) z <- 0.5*x + stats::rnorm(N, sd=.7) y <- stats::rnorm(N, mean=.3*x - .2*z, sd=1 ) dat <- data.frame(x,z,y) dat[ seq(1,N,3), c("x","y") ] <- NA dat[ seq(1,N,4), "z" ] <- NA #-- define imputation methods imp <- mice::mice(dat, maxit=0) method <- imp$method method["x"] <- "rlm" method["z"] <- "lm" method["y"] <- "lqs" #-- impute data imp <- mice::mice(dat, method=method) summary(imp) #--- example using transformations dat1$x <- exp(dat1$x) dat1$z <- stats::plogis(dat1$z) trafo <- list(x=log, z=stats::qlogis) antitrafo <- list(x=exp, z=stats::plogis) #- impute with transformations imp2 <- mice::mice(dat1, method=method, m=1, maxit=3, trafo=trafo, antitrafo=antitrafo) print(imp2) ``` -------------------------------- ### Synthesize data with custom formula specifications Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/man/syn_da.Rd Shows how to define conditional models for specific variables and set variable-specific noise levels. ```R data(data.ma09, package="miceadds") dat <- data.ma09 # fixed variables in synthesis fix_vars <- c("PV1MATH", "SEX") # ordinal variables in synthesis ord_vars <- c("FISCED", "MISCED") # variables that should be synthesized syn_vars <- c("AGE","HISEI", "FISCED", "MISCED") # no noise variable for FISCED and MISCED should be specified da_noise <- c(AGE=0.1, HISEI=0.1, FISCED=0, MISCED=0) # define conditional models for some variables formula_syn <- list( AGE=AGE ~ 1 + PV1MATH + SEX + I(PV1MATH^2) + AGE_DA + HISEI_DA, HISEI=HISEI ~ 1 + PV1MATH + SEX + AGE + I(PV1MATH^2) + I(AGE^2) + I(AGE*PV1MATH) + AGE_DA + HISEI_DA ) #-- synthesize data mod <- miceadds::syn_da( dat=dat, syn_vars=syn_vars, fix_vars=fix_vars, ord_vars=ord_vars, da_noise=da_noise, formula_syn=formula_syn, imp_maxit=2, use_pls=TRUE, ncomp=20, exact_regression=TRUE, exact_marginal=TRUE) str(mod) ``` -------------------------------- ### Exporting Imputed Datasets to Disk Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/man/write.mice.imputation.Rd Demonstrates exporting imputed datasets generated by both mice and mice.1chain to local storage. ```R ############################################################################# # EXAMPLE 1: Imputation of nhanes data and write imputed datasets on disk ############################################################################# data(nhanes,package="mice") #********** # Model 1: Imputation using mice imp1 <- mice::mice( nhanes, m=3, maxit=5 ) # write results write.mice.imputation(mi.res=imp1, name="mice_imp1" ) #********** # Model 2: Imputation using mice.1chain imp2 <- miceadds::mice.1chain( nhanes, burnin=10, iter=20, Nimp=4 ) # write results write.mice.imputation(mi.res=imp2, name="mice_imp2" ) ``` -------------------------------- ### Convert between nested and standard dataset lists Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/man/datlist_create.Rd Shows how to create nested dataset lists from standard data and convert between different nested list structures. ```R library(BIFIEsurvey) data(data.timss4, package="BIFIEsurvey" ) datlist <- data.timss4 # object of class nested.datlist datlist1a <- miceadds::nested.datlist_create(datlist) # object of class NestedImputationList datlist1b <- miceadds::NestedImputationList(datlist) # conversion to datlist datlist2a <- miceadds::nested.datlist2datlist(datlist1a) # class datlist datlist2b <- miceadds::nested.datlist2datlist(datlist1b) # class imputationList # convert into a nested list with 2 between nests and 10 within nests datlist3a <- miceadds::datlist2nested.datlist(datlist2a, Nimp=c(2,10) ) datlist3b <- miceadds::datlist2nested.datlist(datlist2b, Nimp=c(4,5) ) ``` -------------------------------- ### syn.formula(y, x, xp, proper=FALSE, syn_formula, syn_fun, syn_args, ...) Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/man/syn.formula.Rd Defines a synthesizing method for synthpop using a formula interface. When used with the 'mice' method in synthpop::syn, arguments should be prefixed with 'rf.' (e.g., rf.syn_formula). ```APIDOC ### Function: syn.formula #### Description Defines a synthesizing method for the synthpop package using a formula interface. This allows for more complex model specifications during the data synthesis process. #### Arguments - **y** (vector) - Original data vector of length n. - **x** (matrix) - Matrix (n x p) of original covariates. - **xp** (matrix) - Matrix (k x p) of synthesised covariates. - **proper** (logical) - Specifies whether proper synthesis should be conducted. Default is FALSE. - **syn_formula** (formula) - A formula object defining the model. - **syn_fun** (function) - Synthesizing method in the synthpop package. - **syn_args** (list) - Function arguments for syn_fun. - **...** - Further arguments to be passed. #### Returns - **vector** - A vector of length k with synthetic values of y. ``` -------------------------------- ### Load and Analyze Internet Dataset Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/man/data.internet.Rd Load the dataset into the R environment and calculate the proportion of missing values for each variable. ```R data(data.internet) # missing proportions colMeans( is.na(data.internet) ) ``` -------------------------------- ### source.Rcpp.all(path, file_names, ext, excl, remove_temp_file) Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/man/source.all.Rd Sources all Rcpp files within a specified directory. ```APIDOC ## source.Rcpp.all ### Description Sources all Rcpp files within a specified directory based on Rcpp::sourceCpp. ### Parameters - **path** (string) - Required - Path where the files are located. - **file_names** (vector) - Optional - Optional vector of (parts of) file names. - **ext** (string) - Optional - File extension for Rcpp files. - **excl** (string) - Optional - String indicating which files should be omitted from sourcing. - **remove_temp_file** (logical) - Optional - Logical indicating whether temporary Rcpp files should be removed. ``` -------------------------------- ### Convert mice and mice.1chain objects to dataset lists Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/man/mids2datlist.Rd Demonstrates converting standard mice and mice.1chain imputation results into a dataset list format. ```R data(nhanes,package="mice") #**** imputation using mice imp1 <- mice::mice( nhanes, m=3, maxit=5 ) # convert mids object into list datlist1 <- miceadds::mids2datlist( imp1 ) #**** imputation using mice.1chain imp2 <- miceadds::mice.1chain( nhanes, burnin=4, iter=20, Nimp=5 ) # convert mids.1chain object into list datlist2 <- miceadds::mids2datlist( imp2 ) ``` -------------------------------- ### print(x) Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/man/mice.nmi.Rd Prints a mids.nmi object. ```APIDOC ## print(x) ### Description Prints an object of class mids.nmi. ### Parameters - **x** (mids.nmi) - Required - Object of class mids.nmi. ``` -------------------------------- ### rcpp_create_header_file(file_name, pack, path) Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/man/source.all.Rd Creates a C++ header file for an Rcpp file. ```APIDOC ## rcpp_create_header_file ### Description Creates a cpp header file for an Rcpp file. ### Parameters - **file_name** (string) - Required - File name. - **pack** (string) - Optional - Optional string for package. - **path** (string) - Optional - Path where the files are located (defaults to getwd()). ``` -------------------------------- ### Synthesizing SD2011 data using mice functionality Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/man/syn_mice.Rd Demonstrates how to synthesize a subset of the SD2011 dataset by defining specific imputation methods and arguments for the synthpop integration. ```R library(synthpop) #** selection of dataset data(SD2011, package="synthpop") vars <- c("sex","age","ls","smoke") dat <- SD2011[1:1000, vars] dat$ls <- as.numeric(dat$ls) #** default synthesis imp0 <- synthpop::syn(dat) pred0 <- imp0$predictor.matrix method0 <- imp0$method #* define imputation methods method <- c(sex="synthpop", age="synthpop", ls="synthpop", smoke="logreg") # only for smoke, an original mice imputation method is used #- define synthpop functions synthpop_fun <- list(sex="constant", age="constant", ls="cart") #- arguments for 'syn.cart' method synthpop_args <- list(ls=list(smoothing="density")) #- fixed values for 'syn.constant' method fixed_values <- dat[,1:2] #- do synthesization imp <- miceadds::syn_mice(dat, m=1, synthpop_fun=synthpop_fun, method=method, pedictorMatrix=pred0, rf.fixed_values=fixed_values, synthpop_args=synthpop_args) summary(imp) ``` -------------------------------- ### Add an index and system time to a data frame Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/man/index.dataframe.Rd Demonstrates adding an index column and a system time column to a data frame. ```R index.dataframe( dfr, systime=TRUE) ``` -------------------------------- ### mice.impute.imputeR.cFun(y, ry, x, Fun=NULL, draw_boot=TRUE, ...) Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/man/mice.impute.imputeR.lmFun.Rd Imputation method for binary variables using functions from the imputeR package. ```APIDOC ## mice.impute.imputeR.cFun ### Description Provides an interface to imputation methods in the imputeR package for binary data. ### Parameters - **y** (vector) - Incomplete data vector of length n. - **ry** (vector) - Missing data pattern (FALSE = missing, TRUE = observed). - **x** (matrix) - Matrix (n x p) of complete covariates. - **Fun** (string) - Name of imputation function in imputeR package (e.g., imputeR::ridgeC). - **draw_boot** (logical) - Whether a Bootstrap sample is taken for sampling model parameters. - **...** (dots) - Further arguments to be passed. ### Returns - A vector of length nmis (sum(!ry)) with imputed values. ``` -------------------------------- ### Simulate multivariate non-normal data with nnig_sim Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/man/nnig_sim.Rd Demonstrates defining input parameters, calculating coefficients, and generating simulated data. ```R ############################################################################# # EXAMPLE 1: Simulating data with nnig_sim function ############################################################################# #* define input parameters Sigma <- matrix( c(1,.5, .2, .5, 1,.7, .2, .7, 1), 3, 3 ) skew <- c(0,1,1) kurt <- c(1,3,3) #* determine coefficients coeff <- miceadds::nnig_coef( Sigma=Sigma, skew=skew, kurt=kurt ) print(coeff) #* simulate data set.seed(2018) Y <- miceadds::nnig_sim( N=2000, coef=coeff) #* check descriptive statistics apply(Y, 2, TAM::weighted_skewness ) apply(Y, 2, TAM::weighted_kurtosis ) ``` -------------------------------- ### Move older files to an archive directory Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/man/files_move.Rd Demonstrates moving files from a source directory to a specified archive subdirectory. ```R ############################################################################# # EXAMPLE 1: Move older files in '__ARCHIVE' directory ############################################################################# # specify path path1 <- "p:/IPN/Projects/PISA/Trend_2015/2__Data/All_Waves/" # specify target directory which is an archive path2 <- file.path( path1, "__ARCHIVE" ) # move files files_move( path1, path2 ) ``` -------------------------------- ### Summarize and print model comparisons Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/man/pool_mi.Rd Display summaries and print results for various model objects to compare performance. ```R summary(res1) summary(res2) summary(res3) summary(res4) summary(res5) summary(res6b) summary(res6c) print(res6e) print(res7) ``` -------------------------------- ### Format console output with output.format1 Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/man/output.format1.Rd Displays a custom label surrounded by a repeated string pattern on the console. ```R output.format1(stringtype="*'", label="HELLO WORLD", stringlength=20) ## *'*'*'*'*'*'*'*'*'*'*'*'*'*'*'*'*'*'*'*' ## HELLO WORLD ``` -------------------------------- ### Simulate multivariate normal data with zero variance Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/man/ma_rmvnorm.Rd Demonstrates generating 10 samples from a two-dimensional distribution where the first dimension has zero variance. ```R ############################################################################# # EXAMPLE 1: Two-dimensional simulation with zero variance at dimension 1 ############################################################################# sigma <- matrix( c(0,0,0,1), nrow=2, ncol=2) miceadds::ma_rmvnorm( n=10, sigma=sigma ) ``` -------------------------------- ### Create and Analyze Nested Imputed Datasets Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/man/NestedImputationList.Rd Demonstrates the workflow of performing nested multiple imputation, converting the result into a NestedImputationList, and pooling linear model estimates. ```R ############################################################################# # EXAMPLE 1: Nested multiple imputation and conversion into an object of class # NestedImputationList ############################################################################# 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 <- miceadds::mice.nmi( datlist, m=3, maxit=2 ) summary(imp1) # create object of class NestedImputationList datlist1 <- miceadds::mids2datlist( imp1 ) datlist1 <- miceadds::NestedImputationList( datlist1 ) # estimate linear model using with res1 <- with( datlist1, stats::lm( ASMMAT ~ female + migrant ) ) # pool results mres1 <- mitools::MIcombine( res1 ) summary(mres1) coef(mres1) vcov(mres1) ``` -------------------------------- ### summary.mids.1chain(object) Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/man/mice.1chain.Rd Provides a summary of a mids.1chain object. ```APIDOC ## summary.mids.1chain ### Description Summarizes the results of a mice.1chain imputation process. ### Parameters - **object** (mids.1chain) - Required - The object to summarize. ``` -------------------------------- ### Apply custom functions to datlist objects Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/man/with.miceadds.Rd Shows how to use the with method for datlist objects to apply custom functions across imputed datasets. ```R # with method for datlist imp1 <- miceadds::datlist_create(imp) res2b <- with( imp1, fun=function(data){ dfr <- data.frame("M"=colMeans(data), "Q5"=apply( data, 2, stats::quantile, .05 ), "Q95"=apply( data, 2, stats::quantile, .95 ) ) return(dfr) } ) withPool_MI(res2b) ``` -------------------------------- ### Configure and execute multilevel imputation Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/man/mice.impute.2l.latentgroupmean.ML.Rd Sets up imputation methods and predictor matrices for contextual effects and latent group means before running the mice imputation process. ```R # Variable migrant: contextual effects of Dscore and misei impMethod[ "migrant"] <- "2l.contextual.pmm" predM[ "migrant", c("Dscore", "misei" ) ] <- 2 predM[ "migrant", "idclass" ] <- -2 #**** # CLASS LEVEL (Level 2) # impute 'sprengel' and 'groesse' at the level of classes impMethod[ "sprengel"] <- "2lonly.pmm2" impMethod[ "groesse"] <- "2lonly.norm2" predM[ c("sprengel","groesse"), "idclass" ] <- -2 # manifest group mean for Mscore impMethod[ "M.Mscore" ] <- "2l.groupmean" # latent group mean for Mscore impMethod[ "LM.Mscore" ] <- "2l.latentgroupmean.ml" predM[ "M.Mscore", "Mscore" ] <- 2 # covariates for latent group mean of 'Mscore' predM[ "LM.Mscore", "Mscore" ] <- 2 predM[ "LM.Mscore", c( "Dscore", "sprengel" ) ] <- 1 # do imputations imp <- mice::mice( dat, predictorMatrix=predM, m=3, maxit=4, method=impMethod, allow.na=TRUE, pan.iter=100) ``` -------------------------------- ### Estimate Models with mitml Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/man/pool_mi.Rd Convert data to mitml.list format and estimate regression models using the mitml workflow. ```R #*** complete model estimation and inference in mitml # convert into object of class mitml.list ml02 <- mitml::as.mitml.list( data.ma02) # estimate regression mod7 <- with( ml02, stats::lm( read ~ hisei + female ) ) ``` -------------------------------- ### load.files(files, type=NULL, path=getwd(), ...) Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/man/load.data.Rd Loads multiple files into a single data frame. ```APIDOC ## load.files ### Description Loads multiple files and combines them into a single data frame. ### Parameters - **files** (vector) - Required - Vector of file names to be loaded. - **type** (string) - Optional - The file type/extension. - **path** (string) - Optional - Directory from which the datasets should be loaded. Defaults to getwd(). - **...** (dots) - Optional - Further arguments passed to the underlying loading functions. ``` -------------------------------- ### Convert nested lists to flat lists and back Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/man/nestedList2List.Rd Demonstrates the conversion of a nested list structure into a flat list and the subsequent reconstruction of the nested structure using different looping parameters. ```R ############################################################################# # EXAMPLE 1: List conversions using a small example ############################################################################# # define a nestedList nestedList <- as.list(1:3) nestedList[[1]] <- as.list( 2:4 ) nestedList[[2]] <- as.list( 34 ) nestedList[[3]] <- as.list( 4:9 ) # convert a nested list into a list v2 <- miceadds::nestedList2List( nestedList) ## reconvert list v2 into a nested list, looping within first v3 <- miceadds::List2nestedList(v2, N_between=5) # looping between first v4 <- miceadds::List2nestedList(v2, N_between=5, loop_within=FALSE) ``` -------------------------------- ### Jomo wrapper function usage Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/man/data.graham.Rd Demonstrates the basic syntax for using the jomo wrapper function for imputation. ```R imp1c1 <- jomo::jomo(Y=dat, nburn=100, nbetween=10, nimp=M) ``` -------------------------------- ### Clean and Convert Strings to Matrix Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/man/filename_split.Rd Demonstrates cleaning variable names by replacing spaces and converting string data into a matrix format. ```R # substitute "*" dat <- gsub("*", "", dat, fixed=TRUE ) # replace blanks in variable names s1 <- stringr::str_locate(dat, "[A-z] [A-z]") start <- s1[,"start"] + 1 for (ss in 1:length(start) ){ if ( ! is.na( start[ss] ) ){ substring( dat[ss], start[ss], start[ss] ) <- "_" } } # character matrix miceadds::string_to_matrix(dat) # numeric matrix containing correlations miceadds::string_to_matrix(dat, rownames=2, col_elim=c(1,2), as_numeric=TRUE, diag_val=1, extend=TRUE ) #** reading means and SDs miceadds::string_to_matrix(dat0[ c(15,16)], rownames=1, col_elim=c(1), as_numeric=TRUE ) ``` ```R #**** reading correlations (III) dat <- data.ma08$mat3 dat <- gsub(" age ", "_age_", dat, fixed=TRUE ) miceadds::string_to_matrix(dat, rownames=2, col_elim=c(1,2), as_numeric=TRUE, diag_val=1, extend=TRUE ) ``` ```R #**** reading correlations (IV) dat <- data.ma08$mat4 <- dat0 # remove spaces in variable names dat <- gsub(" age ", "_age_", dat, fixed=TRUE ) s1 <- stringr::str_locate_all(dat, "[A-z,.] [A-z]") NL <- length(dat) for (ss in 1:NL ){ NR <- nrow(s1[[ss]]) if (NR>1){ start <- s1[[ss]][2,1]+1 if ( ! is.na( start ) ){ substring( dat[ss], start, start ) <- "_" } } } miceadds::string_to_matrix(dat, rownames=2, col_elim=c(1,2), as_numeric=TRUE, diag_val=1, extend=TRUE ) ``` -------------------------------- ### Simulate univariate data with Fleishman polynomial Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/man/fleishman_sim.Rd Demonstrates calculating coefficients and simulating data using either pre-computed coefficients or direct moment inputs. ```R ############################################################################# # EXAMPLE 1: Simulating values with Fleishman polynomial ############################################################################# #* define mean, standard deviation, skewness and kurtosis mean <- .75 sd <- 2 skew <- 1 kurt <- 3 #* compute coefficients of Fleishman polynomial coeff <- miceadds::fleishman_coef(mean=mean, sd=sd, skew=skew, kurt=kurt) print(coeff) # sample size N <- 1000 set.seed(2018) #* simulate values based on estimated coefficients X <- miceadds::fleishman_sim(N=N, coef=coeff) #* simulate values based on input of moments X <- miceadds::fleishman_sim(N=N, mean=mean, sd=sd, skew=skew, kurt=kurt) ``` -------------------------------- ### Exporting mids object to MLwiN Source: https://github.com/alexanderrobitzsch/miceadds/blob/master/man/mids2mlwin.Rd Demonstrates the conversion of imputed nhanes data into MLwiN-compatible files. ```R data(nhanes) imp <- mice::mice(nhanes) # write files to MLwiN mids2mlwin(imp, file.prefix="nhanes" ) ```