content
stringlengths 0
14.9M
| filename
stringlengths 44
136
|
---|---|
## File Name: BIFIE.BIFIEcdata2BIFIEdata.R
## File Version: 0.15
#--- conversion of BIFIEcdata to BIFIEdata object
BIFIE.BIFIEcdata2BIFIEdata <- function( bifieobj, varnames=NULL, impdata.index=NULL )
{
if ( ! bifieobj$cdata ){
stop( "You may want to use 'BIFIE.BIFIEdata2BIFIEcdata'\n")
}
#*** select some imputed datasets or some variables
bifieobj <- BIFIE.cdata.select( bifieobj=bifieobj, varnames=varnames,
impdata.index=impdata.index )
#*** conversion to BIFIEdata object
bifieobj$datalistM <- bifiesurvey_rcpp_bifiecdata2bifiedata(
datalistM_ind=as.matrix(bifieobj$datalistM_ind),
datalistM_imputed=as.matrix(bifieobj$datalistM_imputed),
Nimp=bifieobj$Nimp, dat1=as.matrix(bifieobj$dat1),
datalistM_impindex=as.matrix(bifieobj$datalistM_impindex) )$datalistM
bifieobj$cdata <- FALSE
bifieobj$datalistM_imputed <- NULL
bifieobj$datalistM_impindex <- NULL
bifieobj$datalistM_ind <- NULL
bifieobj$wgtrep <- as.matrix(bifieobj$wgtrep)
return(bifieobj)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE.BIFIEcdata2BIFIEdata.R
|
## File Name: BIFIE.BIFIEdata2datalist.R
## File Version: 0.19
#--- converts a BIFIEdata object into a list of multiply imputed datasets
BIFIE.BIFIEdata2datalist <- function( bifieobj, varnames=NULL,
impdata.index=NULL, as_data_frame=FALSE )
{
Nimp <- bifieobj$Nimp
NMI <- bifieobj$NMI
bifieobj <- BIFIEdata.select(bifieobj=bifieobj, varnames=varnames,
impdata.index=impdata.index )
if (bifieobj$cdata){
bifieobj <- BIFIE.BIFIEcdata2BIFIEdata( bifieobj=bifieobj)
}
datalistM <- bifieobj$datalistM
variables <- bifieobj$variables
cndat1 <- colnames(bifieobj$dat1)
N <- bifieobj$N
Nimp <- bifieobj$Nimp
datalist <- as.list(1:Nimp)
for (ii in 1:Nimp){
dat0 <- datalistM[ (ii-1)*N + 1:N, ]
colnames(dat0) <- cndat1
datalist[[ii]] <- as.data.frame(dat0)
}
if ((Nimp==1) & as_data_frame){
datalist <- datalist[[1]]
}
return(datalist)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE.BIFIEdata2datalist.R
|
## File Name: BIFIE.bifiedata2bifiecdata.R
## File Version: 2.22
#--- conversion of BIFIEdata to BIFIEcdata
BIFIE.BIFIEdata2BIFIEcdata <- function( bifieobj, varnames=NULL, impdata.index=NULL )
{
if ( bifieobj$cdata ){
stop( "You may want to use 'BIFIE.BIFIEcdata2BIFIEdata'\n")
}
#*** select some imputed datasets or some variables
bifieobj <- BIFIE.data.select( bifieobj=bifieobj, varnames=varnames,
impdata.index=impdata.index )
#*** data conversion
res1 <- bifiesurvey_rcpp_bifiedata2bifiecdata( datalistM=bifieobj$datalistM,
Nimp=bifieobj$Nimp )
bifieobj$cdata <- TRUE
bifieobj$datalistM <- NULL
bifieobj$datalistM_ind <- res1$datalistM_ind
colnames(bifieobj$datalistM_ind) <- bifieobj$varnames
bifieobj$datalistM_imputed <- res1$datalistM_imputed
bifieobj$datalistM_impindex <- res1$datalistM_impindex
bifieobj$time <- Sys.time()
return(bifieobj)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE.bifiedata2bifiecdata.R
|
## File Name: BIFIE.by.R
## File Version: 1.571
#######################################################################
# BIFIE.by function
BIFIE.by <- function( BIFIEobj, vars, userfct, userparnames=NULL,
group=NULL, group_values=NULL, se=TRUE, use_Rcpp=TRUE )
{
s1 <- Sys.time()
cl <- match.call()
bifieobj <- BIFIEobj
if (bifieobj$cdata){
varnames <- unique( c( vars, group, "one") )
bifieobj <- BIFIE.BIFIEcdata2BIFIEdata( bifieobj, varnames=varnames )
}
FF <- Nimp <- bifieobj$Nimp
N <- bifieobj$N
dat1 <- bifieobj$dat1
wgt <- bifieobj$wgt
wgtrep <- bifieobj$wgtrep
varnames <- bifieobj$varnames
RR <- bifieobj$RR
datalistM <- bifieobj$datalistM
fayfac <- bifieobj$fayfac
if (RR==1){ RR <- 0 }
if ( ! se ){
wgtrep <- matrix( wgt, ncol=1 )
RR <- 0
}
vars_index <- unlist( sapply( vars, FUN=function(vv){
which( varnames==vv ) }, simplify=TRUE ) )
# vars values
VV <- length(vars)
wgt_ <- matrix( wgt, ncol=1 )
if ( is.null( group) ){ nogroup <- TRUE } else { nogroup <- FALSE }
cat( paste0( "|", paste0( rep("*", FF), collapse=""), "|\n" ))
if (nogroup){
group <- "one"
group_values <- c(1)
}
#@@@@***
group_index <- match( group, varnames )
#@@@@***
if ( is.null(group_values ) ){
t1 <- bifie_table( datalistM[, group_index ] )
group_values <- sort( as.numeric( paste( names(t1) ) ))
}
#@@@@***
res00 <- BIFIE_create_pseudogroup( datalistM, group, group_index, group_values )
res00$datalistM -> datalistM
res00$group_index -> group_index
res00$GR -> GR
res00$group_values -> group_values
res00$group -> group
#@@@@***
#****
# pure R implementation
if ( ! use_Rcpp ){
res <- BIFIE_by_helper_pureR(
group_values, userfct, datalistM,
N, vars_index, wgt_, wgtrep, Nimp, RR, fayfac,
group_index, userparnames
)
}
#****
# Rcpp implementation
if ( use_Rcpp ){
res <- bifie_by( datalistM, wgt_, wgtrep, vars_index - 1, fayfac,
Nimp, group_index - 1, group_values, userfct)
}
NP <- res$NP
GG <- length(group_values)
ZZ <- NP
if (is.null( userparnames ) ){
userparnames <- paste0("parm",1:NP)
}
dfr <- data.frame( "parm"=rep( userparnames, GG )
)
if (! nogroup){
dfr$groupvar <- group
dfr$groupval <- rep( group_values, each=ZZ )
}
dfr$Ncases <- rep( rowMeans( res$ncasesM ), each=ZZ )
dfr$Nweight <- rep( rowMeans( res$sumwgtM ), each=ZZ )
dfr <- create_summary_table( res_pars=res$parsL,
parsM=res$parsM, parsrepM=res$parsrepM,
dfr=dfr, BIFIEobj=BIFIEobj )
dfr <- clean_summary_table( dfr=dfr, RR=RR, se=se, Nimp=Nimp )
# create vector of parameter names
parnames <- paste0( dfr$parm, "_", dfr$groupvar, dfr$groupval )
#@@@@***
# multiple groupings
dfr <- BIFIE_table_multiple_groupings( dfr, res00 )
#@@@@***
#*************************** OUTPUT ***************************************
s2 <- Sys.time()
timediff <- c( s1, s2 ) #, paste(s2-s1 ) )
res1 <- list( "stat"=dfr,
"output"=res, "timediff"=timediff,
"N"=N, "Nimp"=Nimp, "RR"=RR, "fayfac"=fayfac, "GG"=GG,
"NMI"=BIFIEobj$NMI, "Nimp_NMI"=BIFIEobj$Nimp_NMI,
"parnames"=parnames, "CALL"=cl)
class(res1) <- "BIFIE.by"
return(res1)
}
###################################################################################
####################################################################################
# summary for BIFIE.by function
summary.BIFIE.by <- function( object, digits=4, ... )
{
BIFIE.summary(object)
cat("Statistical Inference for User Defined Function \n")
obji <- object$stat
print_object_summary( obji, digits=digits )
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE.by.R
|
## File Name: BIFIE.cdata.select.R
## File Version: 1.13
#--- selection variables or datasets in BIFIEcdata objects
BIFIE.cdata.select <- function( bifieobj, varnames=NULL, impdata.index=NULL ){
if ( ! bifieobj$cdata ){
stop("Use 'BIFIE.data.select' or the general function 'BIFIEdata.select'")
}
# retain variable "one"
varnames0 <- bifieobj$varnames
if ( ! is.null(varnames) ){
varnames <- union( varnames, intersect( "one", varnames0) )
}
#******* do some variable checking
if ( ! is.null(varnames) ){
h1 <- setdiff( varnames, bifieobj$varnames )
if ( length(h1) > 0 ){
stop( paste0( "Following variables not in BIFIEdata object:\n ",
paste0( h1, collapse=" " ) ) )
}
}
#******** select some imputed datasets
if ( ! is.null(impdata.index ) ){
i1 <- impdata.index
bifieobj$datalistM_imputed <- bifieobj$datalistM_imputed[, i1, drop=FALSE]
bifieobj$Nimp <- length(i1)
}
#********* select some variables
if ( ! is.null( varnames) ){
dfr1 <- data.frame( "varnames"=bifieobj$varnames,
"index"=seq(1,length(bifieobj$varnames) ) )
dfr1$selectvars <- 1 * ( dfr1$varnames %in% varnames )
dfr1 <- dfr1[ dfr1$selectvars==1, ]
bifieobj$datalistM_ind <- bifieobj$datalistM_ind[, dfr1$index ]
i1 <- bifieobj$datalistM_impindex[,2] %in% ( dfr1$index - 1 )
bifieobj$datalistM_imputed <- bifieobj$datalistM_imputed[ i1,, drop=FALSE]
bifieobj$datalistM_impindex <- bifieobj$datalistM_impindex[ i1,, drop=FALSE]
impindex2 <- match( bifieobj$datalistM_impindex[,2], dfr1$index - 1 ) - 1
bifieobj$datalistM_impindex[,2] <- impindex2
bifieobj$dat1 <- bifieobj$dat1[, dfr1$index, drop=FALSE]
bifieobj$varnames <- bifieobj$varnames[ dfr1$index ]
# process variable list
bifieobj$variables <- bifieobj$variables[ dfr1$index,, drop=FALSE]
}
bifieobj$Nvars <- ncol(bifieobj$dat1)
return(bifieobj)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE.cdata.select.R
|
## File Name: BIFIE.correl.R
## File Version: 0.471
#######################################################################
# Correlations and covariances
BIFIE.correl <- function( BIFIEobj, vars, group=NULL, group_values=NULL, se=TRUE ){
#****
s1 <- Sys.time()
cl19 <- match.call()
bifieobj <- BIFIEobj
if (bifieobj$cdata){
varnames <- unique( c( vars, group, "one") )
bifieobj <- BIFIE.BIFIEcdata2BIFIEdata( bifieobj, varnames=varnames )
}
FF <- Nimp <- bifieobj$Nimp
N <- bifieobj$N
dat1 <- bifieobj$dat1
wgt <- bifieobj$wgt
wgtrep <- bifieobj$wgtrep
varnames <- bifieobj$varnames
RR <- bifieobj$RR
datalistM <- bifieobj$datalistM
fayfac <- bifieobj$fayfac
if (RR==1){ RR <- 0 }
if ( ! se ){
wgtrep <- matrix( wgt, ncol=1 )
RR <- 0
}
vars_index <- unlist( sapply( vars, FUN=function(vv){
which( varnames==vv ) }, simplify=TRUE) )
# vars values
VV <- length(vars)
wgt_ <- matrix( wgt, ncol=1 )
if ( is.null( group) ){ nogroup <- TRUE } else { nogroup <- FALSE }
cat(paste0( "|", paste0( rep("*", FF), collapse=""), "|\n" ))
if (nogroup){
group <- "one"
group_values <- c(1)
}
#@@@@***
group_index <- match( group, varnames )
#@@@@***
if ( is.null(group_values ) ){
t1 <- bifie_table( datalistM[, group_index ] )
group_values <- sort( as.numeric( paste( names(t1) ) ))
}
#@@@@***
res00 <- BIFIE_create_pseudogroup( datalistM, group, group_index, group_values )
res00$datalistM -> datalistM
res00$group_index -> group_index
res00$GR -> GR
res00$group_values -> group_values
res00$group -> group
#@@@@***
#**************************************************************************#
# Rcpp call
res <- bifie_correl( datalistM, wgt_, as.matrix(wgtrep), vars_index -1, fayfac,
Nimp, group_index - 1, group_values)
GG <- length(group_values)
itempair_index <- res$itempair_index + 1
ZZ <- nrow(itempair_index )
dfr <- data.frame( "var1"=rep( vars[ itempair_index[,1] ], each=GG ),
"var2"=rep( vars[ itempair_index[,2] ], each=GG )
)
if (! nogroup){
dfr$groupvar <- group
dfr$groupval <- rep( group_values, ZZ )
}
dfr$Ncases <- rep( rowMeans( res$ncases1M ), ZZ )
dfr$Nweight <- rep( rowMeans( res$sumwgt1M ), ZZ )
dfr$cor <- res$cor1$pars
dfr$cor_SE <- res$cor1$pars_se
dfr$t <- round( dfr$cor / dfr$cor_SE, 2 )
dfr$df <- rubin_calc_df( res$cor1, Nimp )
# dfr$p <- pnorm( - abs( dfr$t ) ) * 2
dfr$p <- stats::pt( - abs( dfr$t ), df=dfr$df) * 2
dfr$cor_fmi <- res$cor1$pars_fmi
dfr$cor_VarMI <- res$cor1$pars_varBetween
dfr$cor_VarRep <- res$cor1$pars_varWithin
#******************
# NMI
if ( BIFIEobj$NMI ){
res1a <- res1 <- BIFIE_NMI_inference_parameters( parsM=res$cor1M, parsrepM=res$cor1repM,
fayfac=fayfac, RR=RR, Nimp=Nimp,
Nimp_NMI=BIFIEobj$Nimp_NMI, comp_cov=FALSE )
dfr$cor_fmi <- dfr$cor_VarMI <- NULL
dfr$cor <- res1$pars
dfr$cor_SE <- res1$pars_se
dfr$t <- round( dfr$cor / dfr$cor_SE, 2 )
dfr$df <- res1$df
dfr$p <- stats::pt( - abs( dfr$t ), df=dfr$df) * 2
dfr$cor_fmi <- res1$pars_fmi
dfr$cor_fmi_St1 <- res1$pars_fmiB
dfr$cor_fmi_St2 <- res1$pars_fmiW
dfr$cor_VarMI_St1 <- res1$pars_varBetween1
dfr$cor_VarMI_St2 <- res1$pars_varBetween2
dfr$cor_VarRep <- res1$pars_varWithin
}
dfr <- clean_summary_table( dfr, RR, se, Nimp )
# i1 <- match( dfr$var1, vars )
# i2 <- match( dfr$var2, vars )
dfr <- dfr[ dfr$var1 !=dfr$var2, ]
#@@@@***
# multiple groupings
dfr <- BIFIE_table_multiple_groupings( dfr, res00 )
#@@@@***
dfr.cor <- dfr
dfr <- data.frame( "var1"=rep( vars[ itempair_index[,1] ], each=GG ),
"var2"=rep( vars[ itempair_index[,2] ], each=GG )
)
if (! nogroup){
dfr$groupvar <- group
dfr$groupval <- rep( group_values, ZZ )
}
dfr$Ncases <- rep( rowMeans( res$ncases1M ), ZZ )
dfr$Nweight <- rep( rowMeans( res$sumwgt1M ), ZZ )
dfr$cov <- res$cov1$pars
dfr$cov_SE <- res$cov1$pars_se
dfr$cov_df <- rubin_calc_df( res$cov1, Nimp )
dfr$cov_fmi <- res$cov1$pars_fmi
dfr$cov_VarMI <- res$cov1$pars_varBetween
dfr$cov_VarRep <- res$cov1$pars_varWithin
if ( BIFIEobj$NMI ){
res1b <- res1 <- BIFIE_NMI_inference_parameters( parsM=res$cov1M, parsrepM=res$cov1repM,
fayfac=fayfac, RR=RR, Nimp=Nimp,
Nimp_NMI=BIFIEobj$Nimp_NMI, comp_cov=FALSE )
dfr$cov_fmi <- dfr$cov_VarMI <- NULL
dfr$cov <- res1$pars
dfr$cov_SE <- res1$pars_se
dfr$t <- round( dfr$cov / dfr$cov_SE, 2 )
dfr$df <- res1$df
dfr$p <- stats::pt( - abs( dfr$t ), df=dfr$df) * 2
dfr$cov_fmi <- res1$pars_fmi
dfr$cov_fmi_St1 <- res1$pars_fmiB
dfr$cov_fmi_St2 <- res1$pars_fmiW
dfr$cov_VarMI_St1 <- res1$pars_varBetween1
dfr$cov_VarMI_St2 <- res1$pars_varBetween2
dfr$cov_VarRep <- res1$pars_varWithin
}
dfr <- clean_summary_table( dfr, RR, se, Nimp )
#@@@@***
# multiple groupings
dfr <- BIFIE_table_multiple_groupings( dfr, res00 )
#@@@@***
dfr.cov <- dfr
#*****
# construct list of correlation matrices
ml <- as.list(1:GG)
names(ml) <- paste0(group,group_values)
#*** correlation matrix
ml0 <- ml
cl <- res$cor1_matrix
for (gg in 1:GG){
ml0[[gg]] <- cl[, 1:VV + (gg-1 )*VV ]
colnames(ml0[[gg]]) <- rownames(ml0[[gg]]) <- vars
}
cor_matrix <- ml0
#*** covariance matrix
ml0 <- ml
cl <- res$cov1_matrix
for (gg in 1:GG){
ml0[[gg]] <- cl[, 1:VV + (gg-1 )*VV ]
colnames(ml0[[gg]]) <- rownames(ml0[[gg]]) <- vars
}
cov_matrix <- ml0
# create vector of parameter names
nogroupL <- rep( nogroup, nrow(dfr) )
parnames <- paste0( dfr$var1, "_", dfr$var2,
ifelse( ! nogroupL, paste0("_", dfr$groupvar ), "" ),
ifelse( ! nogroupL, paste0( "_", dfr$groupval ), "" )
)
#*************************** OUTPUT ***************************************
s2 <- Sys.time()
timediff <- c( s1, s2 ) #, paste(s2-s1 ) )
res1 <- list( "stat.cor"=dfr.cor, "stat.cov"=dfr.cov,
"output"=res, "cor_matrix"=cor_matrix,
"cov_matrix"=cov_matrix,
"timediff"=timediff,
"N"=N, "Nimp"=Nimp, "RR"=RR, "fayfac"=fayfac,
"NMI"=BIFIEobj$NMI, "Nimp_NMI"=BIFIEobj$Nimp_NMI,
"itempair_index"=itempair_index, "GG"=GG,
"parnames"=parnames, "CALL"=cl19)
if ( BIFIEobj$NMI ){
res$output_cor <- res1a
res$output_cov <- res1b
}
class(res1) <- "BIFIE.correl"
return(res1)
}
###################################################################################
####################################################################################
# summary for BIFIE.correl function
summary.BIFIE.correl <- function( object, digits=4, ... )
{
BIFIE.summary(object)
cat("Statistical Inference for Correlations \n")
obji <- object$stat.cor
print_object_summary( obji, digits=digits )
cat("\nCorrelation Matrices \n\n")
obji <- object$cor_matrix
GG <- object$GG
for (gg in 1:GG){
obji[[gg]] <- round( obji[[gg]], digits=digits)
}
print(obji)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE.correl.R
|
## File Name: BIFIE.crosstab.R
## File Version: 0.441
#######################################################################
# cross tabulation
BIFIE.crosstab <- function( BIFIEobj, vars1, vars2,
vars_values1=NULL, vars_values2=NULL,
group=NULL, group_values=NULL, se=TRUE ){
#****
s1 <- Sys.time()
cl <- match.call()
bifieobj <- BIFIEobj
vars1 <- vars1[1]
vars2 <- vars2[1]
if (bifieobj$cdata){
varnames <- unique( c( vars1, vars2, group, "one") )
bifieobj <- BIFIE.BIFIEcdata2BIFIEdata( bifieobj, varnames=varnames )
}
FF <- Nimp <- bifieobj$Nimp
N <- bifieobj$N
dat1 <- bifieobj$dat1
wgt <- bifieobj$wgt
wgtrep <- bifieobj$wgtrep
varnames <- bifieobj$varnames
RR <- bifieobj$RR
datalistM <- bifieobj$datalistM
fayfac <- bifieobj$fayfac
if (RR==1){ RR <- 0 }
if ( ! se ){
wgtrep <- matrix( wgt, ncol=1 )
RR <- 0
}
vars_index1 <- which( varnames==vars1 )
vars_index2 <- which( varnames==vars2 )
# vars values
if ( is.null(vars_values1 ) ){
t1 <- bifie_table( datalistM[, vars_index1 ] )
vars_values1 <- sort( as.numeric( paste( names(t1) ) ))
}
if ( is.null(vars_values2 ) ){
t1 <- bifie_table( datalistM[, vars_index2 ] )
vars_values2 <- sort( as.numeric( paste( names(t1) ) ))
}
wgt_ <- matrix( wgt, ncol=1 )
if ( is.null( group) ){ nogroup <- TRUE } else { nogroup <- FALSE }
cat(paste0( "|", paste0( rep("*", FF), collapse=""), "|\n" ))
if (nogroup){
group <- "one"
group_values <- c(1)
}
#@@@@***
group_index <- match( group, varnames )
#@@@@***
if ( is.null(group_values ) ){
t1 <- bifie_table( datalistM[, group_index ] )
group_values <- sort( as.numeric( paste( names(t1) ) ))
}
#@@@@***
res00 <- BIFIE_create_pseudogroup( datalistM, group, group_index, group_values )
res00$datalistM -> datalistM
res00$group_index -> group_index
res00$GR -> GR
res00$group_values -> group_values
res00$group -> group
#@@@@***
GG <- length(group_values)
#**************************************************************************#
# Rcpp call
res <- bifie_crosstab( datalistM, wgt_, wgtrep, vars_values1,
vars_index1 - 1, vars_values2, vars_index2 - 1, fayfac,
Nimp, group_index - 1, group_values )
ZZ <- nrow(res$ctparsM)
design_pars <- res$design_pars
VV1 <- length(vars_values1)
VV2 <- length(vars_values2)
#*********
# joint distributions
dfr1 <- data.frame("var1"=vars1[1], "varval1"=design_pars[,1] )
dfr1$var2 <- vars2[1]
dfr1$varval2 <- design_pars[,2]
dfr1$group <- group
dfr1$groupval <- design_pars[,3]
XX1 <- nrow(dfr1)
dfr1$Ncases <- rowMeans( res$ncasesM )
dfr1$Nweight <- rowMeans( res$sumwgtM )
XX2 <- 3*XX1
## // probs_joint ZZ
## // probs_rowcond ZZ
## // probs_colcond ZZ
## // probs_rowmarg VV1*GG
## // probs_colmarg VV2*GG
dfr1 <- data.frame("prob"=rep( c("joint", "rowcond", "colcond"), each=XX1 ),
dfr1[ rep(1:XX1, 3 ), ] )
dfr1$est <- res$ctparsL$pars[ 1:XX2 ]
dfr1$SE <- res$ctparsL$pars_se[ 1:XX2 ]
dfr1$fmi <- res$ctparsL$pars_fmi[ 1:XX2 ]
dfr1$df <- rubin_calc_df( res$ctparsL, Nimp, indices=1:XX2 )
dfr1$VarMI <- res$ctparsL$pars_varBetween[ 1:XX2 ]
dfr1$VarRep <- res$ctparsL$pars_varWithin[ 1:XX2 ]
rownames(dfr1) <- NULL
parnames <- paste0( dfr1$prob, "_", dfr1$var1, dfr1$val1, "_",
dfr1$var2, dfr1$val2, "_", dfr1$group, dfr1$groupval )
if (BIFIEobj$NMI ){
res1 <- BIFIE_NMI_inference_parameters( parsM=res$ctparsM[1:XX2,], parsrepM=res$ctparsrepM[1:XX2,],
fayfac=fayfac, RR=RR, Nimp=Nimp,
Nimp_NMI=BIFIEobj$Nimp_NMI, comp_cov=FALSE )
dfr1$est <- res1$pars
dfr1$SE <- res1$pars_se
# dfr$t <- round( dfr$perc / dfr$perc_SE, 2 )
dfr1$df <- res1$df
# dfr$p <- pt( - abs( dfr$t ), df=dfr$df) * 2
dfr1$fmi <- res1$pars_fmi
dfr1$fmi_St1 <- res1$pars_fmiB
dfr1$fmi_St2 <- res1$pars_fmiW
dfr1$VarMI <- res1$pars_varBetween1 + res1$pars_varBetween2
dfr1$VarMI_St1 <- res1$pars_varBetween1
dfr1$VarMI_St2 <- res1$pars_varBetween2
dfr1$VarRep <- res1$pars_varWithin
}
#*****
# marginal distributions
XX3 <- GG*(VV1+VV2)
dfr2 <- data.frame( "prob"=c( rep( "rowmarg", VV1*GG), rep( "colmarg", VV2*GG) ) )
dfr2$var <- c( rep(vars1,VV1*GG), rep(vars2,VV2*GG) )
dfr2$varval <- c( rep( vars_values1, GG ), rep( vars_values2, GG ) )
dfr2$group <- group
dfr2$groupval <- c( rep( group_values, each=VV1 ), rep( group_values, each=VV2 ) )
l1 <- seq( XX2+1, XX2 + XX3 )
dfr2$est <- res$ctparsL$pars[ l1 ]
dfr2$SE <- res$ctparsL$pars_se[ l1 ]
dfr2$fmi <- res$ctparsL$pars_fmi[ l1 ]
dfr2$df <- rubin_calc_df( res$ctparsL, Nimp, indices=l1)
dfr2$VarMI <- res$ctparsL$pars_varBetween[ l1 ]
dfr2$VarRep <- res$ctparsL$pars_varWithin[ l1 ]
parnames2 <- paste0( dfr2$prob, "_", dfr2$var, dfr2$val, "_",
dfr2$group, dfr2$groupval )
parnames <- c( parnames, parnames2 )
if (BIFIEobj$NMI ){
res1 <- BIFIE_NMI_inference_parameters( parsM=res$ctparsM[ l1,], parsrepM=res$ctparsrepM[ l1,],
fayfac=fayfac, RR=RR, Nimp=Nimp,
Nimp_NMI=BIFIEobj$Nimp_NMI, comp_cov=FALSE )
dfr2$est <- res1$pars
dfr2$SE <- res1$pars_se
# dfr$t <- round( dfr$perc / dfr$perc_SE, 2 )
dfr2$df <- res1$df
# dfr$p <- stats::pt( - abs( dfr$t ), df=dfr$df) * 2
dfr2$fmi <- res1$pars_fmi
dfr2$fmi_St1 <- res1$pars_fmiB
dfr2$fmi_St2 <- res1$pars_fmiW
dfr2$VarMI <- res1$pars_varBetween1 + res1$pars_varBetween2
dfr2$VarMI_St1 <- res1$pars_varBetween1
dfr2$VarMI_St2 <- res1$pars_varBetween2
dfr2$VarRep <- res1$pars_varWithin
}
#*****
# effect sizes
## // w_es 2*GG
## // gamma_es GG
## // lambda 3*GG
## // kruskal_tau 3*GG
XX4 <- nrow(dfr1) + nrow(dfr2)
XX5 <- (2+1+3+3)*GG
dfr3 <- data.frame( "parm"=c( rep("w",GG), rep("V",GG),
rep("gamma",GG),
rep(c("lambda", "lambda_X","lambda_Y"),GG),
rep( c("tau","tau_X","tau_Y"), GG ) ) )
dfr3$group <- group
dfr3$groupval <- c(rep(group_values,1), rep(group_values, 1), rep(group_values,1),
rep(group_values,each=3), rep(group_values,each=3) )
l1 <- seq( XX4+1, XX4 + XX5 )
dfr3$est <- res$ctparsL$pars[ l1 ]
dfr3$SE <- res$ctparsL$pars_se[ l1 ]
dfr3$fmi <- res$ctparsL$pars_fmi[ l1 ]
dfr3$df <- rubin_calc_df( res$ctparsL, Nimp, indices=l1)
dfr3$VarMI <- res$ctparsL$pars_varBetween[ l1 ]
dfr3$VarRep <- res$ctparsL$pars_varWithin[ l1 ]
if (BIFIEobj$NMI ){
res1 <- BIFIE_NMI_inference_parameters( parsM=res$ctparsM[ l1,], parsrepM=res$ctparsrepM[ l1,],
fayfac=fayfac, RR=RR, Nimp=Nimp,
Nimp_NMI=BIFIEobj$Nimp_NMI, comp_cov=FALSE )
dfr3$est <- res1$pars
dfr3$SE <- res1$pars_se
# dfr$t <- round( dfr$perc / dfr$perc_SE, 2 )
dfr3$df <- res1$df
# dfr$p <- stats::pt( - abs( dfr$t ), df=dfr$df) * 2
dfr3$fmi <- res1$pars_fmi
dfr3$fmi_St1 <- res1$pars_fmiB
dfr3$fmi_St2 <- res1$pars_fmiW
dfr3$VarMI <- res1$pars_varBetween1 + res1$pars_varBetween2
dfr3$VarMI_St1 <- res1$pars_varBetween1
dfr3$VarMI_St2 <- res1$pars_varBetween2
dfr3$VarRep <- res1$pars_varWithin
}
parnames3 <- paste0( dfr3$parm, "_",
dfr3$group, dfr3$groupval )
parnames <- c( parnames, parnames3 )
if ( ( ! se ) & ( RR==0 ) ){
dfr1$df <- dfr1$SE <- dfr1$fmi <- dfr1$VarMI <- dfr1$VarRep <- NULL
dfr2$df <- dfr2$SE <- dfr2$fmi <- dfr2$VarMI <- dfr2$VarRep <- NULL
dfr3$df <- dfr3$SE <- dfr3$fmi <- dfr3$VarMI <- dfr3$VarRep <- NULL
}
if ( Nimp==1 ){
dfr1$fmi <- dfr1$VarMI <-NULL
dfr2$fmi <- dfr2$VarMI <- NULL
dfr3$fmi <- dfr3$VarMI <- NULL
}
# create vector of parameter names
# nogroupL <- rep( nogroup, nrow(dfr) )
# parnames <- paste0( dfr$var, "_", dfr$varval,
# ifelse( ! nogroupL, paste0( "_", dfr$groupvar, "_" ), "" ),
# ifelse( ! nogroupL, dfr$groupval, "" ) )
# parnames <- NULL
# compute ad hoc chi square statistics (without resampling)
ncases_gg <- res$ncases_ggM
l1 <- seq( XX4+1, XX4 + GG)
wes <- res$ctparsM[l1,]
chisquare <- wes^2 * ncases_gg
p_chi2 <- (VV1-1)*(VV2-1)
p_chi2 <- 1-stats::pchisq( chisquare, df=p_chi2 )
dfr4 <- data.frame("group"=group, "groupval"=group_values )
for (ii in 1:GG){
m1 <- miceadds::micombine.chisquare( dk=chisquare[ii,], df=(VV1-1)*(VV2-1),
display=FALSE )
dfr4[ii,"chi2"] <- m1["D"]
dfr4[ii, "df" ] <- m1["df"]
dfr4[ ii, "p"] <- m1["p"]
}
#@@@@***
# multiple groupings
dfr1 <- BIFIE_table_multiple_groupings( dfr1, res00 )
#@@@@***
#@@@@***
# multiple groupings
dfr2 <- BIFIE_table_multiple_groupings( dfr2, res00 )
#@@@@***
#*************************** OUTPUT ***************************************
s2 <- Sys.time()
timediff <- c( s1, s2 ) #, paste(s2-s1 ) )
res1 <- list( "stat.probs"=dfr1, "stat.marg"=dfr2,
"stat.es"=dfr3, "output"=res, "timediff"=timediff,
"N"=N, "Nimp"=Nimp, "RR"=RR, "fayfac"=fayfac,
"NMI"=BIFIEobj$NMI, "Nimp_NMI"=BIFIEobj$Nimp_NMI,
"parnames"=parnames, "CALL"=cl )
class(res1) <- "BIFIE.crosstab"
return(res1)
}
###################################################################################
####################################################################################
# summary for BIFIE.crosstab function
summary.BIFIE.crosstab <- function( object, digits=3, ... )
{
BIFIE.summary(object)
cat("Joint and Conditional Probabilities\n")
obji <- object$stat.probs
print_object_summary( obji, digits=digits )
cat("\nMarginal Probabilities\n")
obji <- object$stat.marg
print_object_summary( obji, digits=digits )
cat("\nEffect Sizes\n")
obji <- object$stat.es
print_object_summary( obji, digits=digits )
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE.crosstab.R
|
## File Name: BIFIE.data.R
## File Version: 1.473
# Convert a list of multiply imputed datasets into an object of class BIFIEdata
BIFIE.data <- function( data.list, wgt=NULL, wgtrep=NULL, fayfac=1,
pv_vars=NULL, pvpre=NULL, cdata=FALSE, NMI=FALSE )
{
cl <- match.call()
#**** handling pv_vars
if ( ! is.null(pv_vars) ){
if ( is.null(pvpre) ){
jktype <- "JK_TIMSS"
} else {
jktype <- "RW_PISA"
}
if (!is.null(pvpre)){
cn_data <- colnames(data.list)
pv_vars <- BIFIE_data_select_pv_vars(pvpre=pvpre, cn_data=cn_data)
}
data.list <- BIFIE_data_pv_vars_create_datlist(pvpre=pvpre, pv_vars=pv_vars,
jktype=jktype, data=data.list)
}
# subroutine for preparation of nested multiple imputations
res0 <- BIFIE_data_nested_MI( data.list=data.list, NMI=NMI )
data.list <- res0$data.list
Nimp_NMI <- res0$Nimp_NMI
if ( ( is.list( data.list ) ) & ( is.data.frame( data.list) ) ){
h1 <- data.list
data.list <- list( 1 )
data.list[[1]] <- h1
}
FF <- length( data.list)
Nimp <- FF
if ( sum( colnames(data.list[[1]]) %in% "one" ) > 0 ){
cat("Variable 'one' in datasets is replaced by a constant variable")
cat(" containing only ones!\n" )
for (ii in 1:Nimp){
data.list[[ii]][, "one"] <- NULL
}
}
N <- nrow( data.list[[1]] )
V <- ncol( data.list[[1]] )
dat1 <- data.list[[1]]
cn <- c( colnames(dat1), "one" )
N <- nrow(dat1)
p1 <- sapply( 1:V, FUN=function(vv){ is.numeric( dat1[,vv] ) } )
notnum <- which( ! p1 )
datalistM <- matrix( NA, nrow=N*Nimp, V + 1)
cat("+++ Generate BIFIE.data object\n")
cat(paste0( "|", paste0( rep("*", FF), collapse=""), "|\n|" ))
#****
# weights
if ( is.character(wgt) & ( length(wgt)==1 ) ){
wgt <- data.list[[1]][, wgt ]
}
if ( is.null(wgt) ){ wgt <- rep(1,N) }
wgt <- as.numeric( wgt )
if ( is.null(wgtrep) ){ wgtrep <- matrix( wgt, nrow=N, ncol=1 ) }
wgtrep <- as.matrix( wgtrep )
for (ff in 1:FF){ # imputed dataset ff
dat1 <- data.list[[ff]]
for (vv in notnum){
dat1[,vv] <- as.numeric( dat1[,vv] )
}
dat1$one <- 1
dat1 <- as.matrix( dat1)
datalistM[ 1:N + N*(ff-1), ] <- dat1
cat("-") ; flush.console()
}
cat("|\n")
wgtrep <- as.matrix(wgtrep)
res <- list( "datalistM"=datalistM, "wgt"=wgt, "wgtrep"=wgtrep,
"Nimp"=Nimp, "N"=N, "dat1"=dat1, "varnames"=cn, "fayfac"=fayfac,
"RR"=ncol(wgtrep), "time"=Sys.time(), "CALL"=cl )
res$NMI <- NMI
res$Nimp_NMI <- Nimp_NMI
res$cdata <- FALSE
class(res) <- "BIFIEdata"
#***** variable names and transformations
VV <- length(res$varnames)
res$Nvars <- VV
dfr2 <- data.frame( "index"=1:VV, "variable"=res$varnames,
"variable_orig"=res$varnames, "source"="indata")
res$variables <- dfr2
if ( cdata ){
res <- BIFIE.BIFIEdata2BIFIEcdata( bifieobj=res, varnames=NULL )
}
return(res)
}
#**************** print method ***********************
print.BIFIEdata <- function(x,...){
cat("Object of class 'BIFIEdata'\nCall: ")
print( x$CALL )
#*** multiply imputed data
if ( ! x$NMI ){
cat("MI data with", x$Nimp,"datasets\n")
}
#*** nested multiply imputed data
if ( x$NMI ){
v1 <- paste0( "NMI data with ", x$Nimp_NMI[1]," between datasets and ",
x$Nimp_NMI[2], " within datasets\n")
cat(v1)
}
v1 <- paste0( x$RR, " replication weights with fayfac=",
round(x$fayfac,3), " \n" )
cat(v1)
v1 <- paste0( x$N, " cases and ", x$Nvars, " variables \n" )
cat(v1)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE.data.R
|
## File Name: BIFIE.data.boot.R
## File Version: 0.20
###########################################################
# BIFIE.data objects for bootstrap designs
BIFIE.data.boot <- function( data, wgt=NULL, pv_vars=NULL,
Nboot=500, seed=.Random.seed, cdata=FALSE)
{
cl <- match.call()
#*** list of multiply imputed datasets
if ( ( is.list(data) ) & ( ! is.data.frame(data) ) ){
dataL <- data
data <- dataL[[1]]
} else {
dataL <- data
}
data <- as.data.frame( data )
if ( ! is.null(seed) ){
set.seed( seed )
}
# normalize weights
if ( is.null(wgt) ){
wgt <- "_wgt2"
data[, wgt ] <- rep( 1, nrow(data) )
}
wgtname <- wgt
wgt <- data[, wgt ]
N <- length(wgt)
wgt <- N * wgt / sum(wgt)
# cumulated weights
cumwgt <- cumsum(wgt)
# random numbers
rand_wgt <- N*matrix( stats::runif(N*Nboot), nrow=N, ncol=Nboot )
#****
# apply bootstrap subfunction
cat("+++ Generate bootstrap samples\n"); utils::flush.console()
datarep <- bifiesurvey_rcpp_bootstrap( cumwgt=cumwgt, rand_wgt=rand_wgt)$wgtM
RR <- Nboot
addname <- 10^( floor( log( RR+.5, 10 ) ) + 1 )
colnames(datarep) <- paste0("w_fstr", substring( paste0(addname +1:RR),2) )
datarep <- sum( wgt )/N * datarep
#******** generate replicated datasets for datasets
if ( is.null( pv_vars) ){
datalist <- dataL
}
if ( ! is.null( pv_vars )){
dfr <- NULL
VV <- length(pv_vars)
for (vv in 1:VV){
vv1 <- pv_vars[vv]
ind.vv1 <- which( substring( colnames(data), 1, nchar( vv1 ) )==pv_vars[vv] )
Nimp <- length(ind.vv1)
dfr2 <- data.frame( "variable"=vv1, "var_index"=vv, "data_index"=ind.vv1,
"impdata_index"=1:Nimp )
dfr <- rbind( dfr, dfr2 )
}
sel_ind <- setdiff( 1:( ncol(data) ), dfr$data_index )
data0 <- data[, sel_ind ]
V0 <- ncol(data0)
newvars <- seq( V0+1, V0+VV )
datalist <- as.list( 1:Nimp )
for (ii in 1:Nimp ){
dat1 <- data.frame( data0, data[, dfr[ dfr$impdata_index==ii, "data_index" ] ] )
colnames(dat1)[ newvars ] <- pv_vars
datalist[[ii]] <- dat1
}
}
fayfac <- 1/Nboot
#*** create BIFIE.data object
bifiedat <- BIFIE.data( datalist, wgt=data[, wgtname ],
wgtrep=datarep, fayfac=fayfac, cdata=cdata)
bifiedat$CALL <- cl
return(bifiedat)
}
###############################################################################
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE.data.boot.R
|
## File Name: BIFIE.data.jack.R
## File Version: 1.703
#--- BIFIE.data objects for designs with jackknife zones
BIFIE.data.jack <- function( data, wgt=NULL, jktype="JK_TIMSS", pv_vars=NULL,
jkzone=NULL, jkrep=NULL, jkfac=NULL, fayfac=NULL,
wgtrep="W_FSTR", pvpre=paste0("PV",1:5), ngr=100,
seed=.Random.seed,
cdata=FALSE )
{
cl <- match.call()
# subroutine for preparation of nested multiple imputations
# res0 <- BIFIE_data_nested_MI( data.list=data.list, NMI=NMI )
# data.list <- res0$data.list
# Nimp_NMI <- res0$Nimp_NMI
fayfac0 <- fayfac
if ( ( ! is.null(wgtrep) ) & ( is.null(fayfac) ) ){
fayfac <- 1
}
#*** list of multiply imputed datasets
if ( ( is.list(data) ) & ( ! is.data.frame(data) ) ){
dataL <- data
data <- dataL[[1]]
} else {
dataL <- data
}
data <- as.data.frame( data )
#*** using fixed jackknife zones
if (jktype=="JK_GROUP"){
N <- nrow(data)
if ( is.null(wgt) ){
data$wgt <- rep(1,N)
wgt <- "wgt"
}
data$jkrep <- rep(0,N)
jkrep <- "jkrep"
fayfac <- ngr / ( ngr - 1 )
jkfac <- 0
}
#*** defaults for jackknife creation: random groups
if (jktype=="JK_RANDOM"){
N <- nrow(data)
if ( is.null(wgt) ){
data$wgt <- rep(1,N)
wgt <- "wgt"
}
if ( ! is.null(seed) ){
set.seed( seed )
indzone <- sample(1:N)
} else {
indzone <- 1:N
}
jkzone <- 1:N
N1 <- N / ngr
jkzone <- floor( jkzone / ( N1 + 1E-5 ) ) + 1
jkzone <- jkzone[indzone]
jkrep <- rep(0,N)
data$jkzone <- jkzone
jkzone <- "jkzone"
data$jkrep <- jkrep
jkrep <- "jkrep"
fayfac <- ngr / ( ngr - 1 )
jkfac <- 0
}
#**** defaults for TIMSS
if (jktype %in% c("JK_TIMSS","JK_TIMSS2") ){
if ( is.null(jkrep) ){
jkrep <- "JKREP"
}
if ( is.null(jkzone) ){
jkzone <- "JKZONE"
}
if ( is.null(wgt) ){
wgt <- "TOTWGT"
}
jkfac <- 2
}
#**** defaults for PISA
if (jktype=="RW_PISA"){
jkrep <- NULL
jkzone <- NULL
if ( is.null(wgt)){
wgt <- "W_FSTUWT"
}
jkfac <- NULL
cn_data <- colnames(data)
repvars <- grep( wgtrep, cn_data )
RR <- length(repvars)
pv_vars <- BIFIE_data_select_pv_vars(pvpre, cn_data )
datarep <- data[, repvars ]
RR <- ncol(datarep)
fayfac <- 1 / RR / ( 1 - .5)^2
data <- data[, - repvars ]
}
#**** generate replicate weights
if ( jktype %in% c("JK_TIMSS", "JK_GROUP", "JK_RANDOM", "JK_TIMSS2") ) {
# redefine jackknife zones
jkzones1 <- unique( data[,jkzone] )
data[,jkzone] <- match( data[,jkzone], jkzones1)
#***********
RR <- max( data[,jkzone] )
prblen <- 10
prbar <- BIFIE.progressbar( ops=RR, prblen=prblen )
cat("+++ Generate replicate weights\n")
cat(paste0("|", paste0(rep("*",prblen), collapse=""), "|\n|"))
utils::flush.console()
addname <- 10^( floor( log( RR+.5, 10 ) ) + 1 )
data[, jkzone ] <- match( data[, jkzone ], unique( data[, jkzone] ) )
datarep <- bifiesurvey_rcpp_jackknife_timss( wgt=data[,wgt], jkzone=data[,jkzone]-1,
jkrep=data[,jkrep], RR=RR, jkfac=jkfac, prbar=prbar )
colnames(datarep) <- paste0("w_fstr", substring( paste0(addname +1:RR),2) )
# adjustments for JK_TIMSS2 type
if (jktype=="JK_TIMSS2"){
datarep0 <- bifiesurvey_rcpp_jackknife_timss( wgt=data[,wgt], jkzone=data[,jkzone]-1,
jkrep=1 - data[,jkrep], RR=RR, jkfac=jkfac, prbar=prbar )
colnames(datarep0) <- paste0("w_fstr", substring( paste0(addname +1:RR),2) )
datarep <- cbind( datarep, datarep0 )
ind_rep <- unlist( sapply( 1:RR, FUN=function(rr){ rr + c(0,RR) },
simplify=FALSE) )
datarep <- datarep[, ind_rep ]
addname <- 10^( floor( log( 2*RR+.5, 10 ) ) + 1 )
colnames(datarep) <- paste0("w_fstr", substring( paste0(addname +1:(2*RR)),2) )
RR <- 2*RR
fayfac <- .5
}
cat("|\n")
}
#******** generate replicated datasets for datasets
if ( is.null( pv_vars) ){
datalist <- dataL
}
#--------------------------------------------------
if ( ! is.null( pv_vars )){
datalist <- BIFIE_data_pv_vars_create_datlist( pvpre=pvpre, pv_vars=pv_vars,
jktype=jktype, data=data )
} # end pv_vars
#--------------------------------------------------
if ( ! is.null(fayfac0) ){
fayfac <- fayfac0
}
#*** create BIFIE.data object
bifiedat <- BIFIE.data( datalist, wgt=data[, wgt ], wgtrep=datarep, fayfac=fayfac,
cdata=cdata, NMI=FALSE )
bifiedat$CALL <- cl
return(bifiedat)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE.data.jack.R
|
## File Name: BIFIE.data.select.R
## File Version: 1.23
#######################################################################
# selection variables or datasets in BIFIEcdata objects
BIFIE.data.select <- function( bifieobj, varnames=NULL, impdata.index=NULL )
{
if ( bifieobj$cdata ){
stop("Use 'BIFIE.cdata.select' or the general function 'BIFIEdata.select'")
}
# retain variable "one"
varnames0 <- bifieobj$varnames
if ( ! is.null(varnames) ){
varnames <- union( varnames, intersect( "one", varnames0) )
}
#******** select some imputed datasets
if ( ! is.null(impdata.index ) ){
i1 <- impdata.index - 1
N <- bifieobj$N
ind <- NULL
for (ii in i1){
vec <- ii*N + ( 1:N )
ind <- c(ind, vec)
}
bifieobj$datalistM <- bifieobj$datalistM[ ind,, drop=FALSE]
bifieobj$Nimp <- length(i1)
}
#********* select some variables
if ( ! is.null(varnames) ){
dfr1 <- data.frame( "varnames"=bifieobj$varnames, "index"=seq(1,length(bifieobj$varnames) ) )
dfr1$selectvars <- 1 * ( dfr1$varnames %in% varnames )
dfr1 <- dfr1[ dfr1$selectvars==1, ]
bifieobj$datalistM <- bifieobj$datalistM[, dfr1$index, drop=FALSE]
bifieobj$dat1 <- bifieobj$dat1[, dfr1$index, drop=FALSE]
bifieobj$varnames <- bifieobj$varnames[ dfr1$index ]
# process variable list
bifieobj$variables <- bifieobj$variables[ dfr1$index, ]
}
bifieobj$Nvars <- ncol(bifieobj$dat1)
return(bifieobj)
}
############################################################################
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE.data.select.R
|
## File Name: BIFIE.data.transform.R
## File Version: 1.304
#--- transforming data in BIFIE.data object
BIFIE.data.transform <- function( bifieobj, transform.formula, varnames.new=NULL )
{
varnames <- bifieobj$varnames
transform.formula <- stats::as.formula( transform.formula )
# add "+0" input in formula
transform.formula <- BIFIE_data_transform_process_formula(transform.formula=transform.formula)
# select variables which should be transformed
vars <- all.vars(transform.formula)
ind_vars <- unlist( sapply( vars, FUN=function(vv){ which( varnames==vv ) } ) )
# check whether all variables are included in the BIFIEdata object
h1 <- setdiff( vars, varnames )
if ( length(h1)>0 ){
stop( "Following variables are not in the BIFIEdata object: \n\n ", paste( h1, collapse=" " ) )
}
#***--- distinction BIFIEdata and BIFIEcdata
cdata <- bifieobj$cdata
if ( ! cdata ){
dfr <- as.data.frame( bifieobj$datalistM[, ind_vars] )
colnames(dfr) <- vars
}
if ( cdata ){
dfr1 <- BIFIE.BIFIEcdata2BIFIEdata( bifieobj, varnames=vars )
dfr <- as.data.frame( dfr1$datalistM )
colnames(dfr) <- dfr1$varnames
}
N <- bifieobj$N
N1 <- bifieobj$Nimp * N
N2 <- ncol( bifieobj$dat1)
dfr_long <- dfr
Nimp <- bifieobj$Nimp
#*** check whether some variables should be removed in original BIFIE.data object
if ( ! is.null( varnames.new) ){
varnames.old <- bifieobj$varnames
select_vars <- setdiff( varnames.old, varnames.new )
bifieobj <- BIFIEdata.select( bifieobj, varnames=select_vars )
# removed variables
rm_vars <- intersect( varnames.old, varnames.new )
if ( length(rm_vars) > 0 ){
cat( paste0("Removed ", length(rm_vars),
" original variables: ", paste0( rm_vars, collapse=" " ), "\n") )
}
varnames <- bifieobj$varnames
}
#*** construction of new variables
M1_long <- NULL
for (ii in 1:Nimp){
dfr <- as.data.frame( dfr_long[ ( ii-1)*N + 1:N, ] )
colnames(dfr) <- colnames(dfr_long)
rownames(dfr) <- 1:N
M1 <- stats::model.matrix( transform.formula, dfr )
varnames.added <- colnames(M1)
varsindex.added <- seq( N2 + 1, N2 + ncol(M1) )
M1.new <- matrix( NA, nrow=N, ncol=ncol(M1) )
colnames(M1.new) <- varnames.added
VV <- ncol(M1)
M1.new[ match( rownames(M1),rownames(dfr) ), ] <- M1
M1_long <- rbind( M1_long, M1.new )
}
# resulting object is M1.new
M1.new <- M1_long
#***---
varnames.added1 <- varnames.added
if ( ! is.null(varnames.new) ){
V21 <- length(varnames.added)
V22 <- length(varnames.new)
varnames.added[ seq(1, min(V21,V22)) ] <- varnames.new[ seq(1,min(V21,V22) ) ]
}
varnames1 <- c( varnames, varnames.added )
#***--- distinction between BIFIEdata and BIFIEcdata
if ( ! cdata ){
bifieobj$datalistM <- as.matrix( cbind( bifieobj$datalistM, M1.new ) )
colnames(bifieobj$datalistM) <- NULL
bifieobj$dat1 <- as.matrix( bifieobj$datalistM[ seq( N*(Nimp-1) + 1, Nimp*N ),,drop=FALSE])
colnames(bifieobj$dat1) <- varnames1
}
if ( cdata ){
M1.new <- as.matrix(M1.new)
VV2 <- ncol(bifieobj$dat1)
# create indicators
res2 <- bifiesurvey_rcpp_bifiedata2bifiecdata( datalistM=M1.new, Nimp=bifieobj$Nimp )
datalistM_ind <- res2$datalistM_ind
datalistM_imputed <- res2$datalistM_imputed
datalistM_impindex <- res2$datalistM_impindex
datalistM_impindex[,2] <- datalistM_impindex[,2] + VV2
bifieobj$datalistM_imputed <- rbind( bifieobj$datalistM_imputed, datalistM_imputed )
dat1 <- as.matrix( M1.new[ seq( N*(Nimp-1) + 1, Nimp*N ), ])
bifieobj$dat1 <- cbind( bifieobj$dat1, dat1 )
colnames(bifieobj$dat1) <- varnames1
bifieobj$datalistM_impindex <- rbind( bifieobj$datalistM_impindex, datalistM_impindex )
bifieobj$datalistM_ind <- cbind( bifieobj$datalistM_ind, datalistM_ind )
}
#*** include variable names
bifieobj$varnames <- varnames1
bifieobj$varnames.added <- varnames.added
bifieobj$varsindex.added <- varsindex.added
cat( paste0( "Included ", VV, " variables: ", paste0( varnames.added, collapse=" " ), "\n") )
#*** add variable names in list
dfr3 <- bifieobj$variables
VV2 <- length(bifieobj$varnames.added)
n0 <- max( dfr3$index )
dfr3[, "variable"] <- bifieobj$varnames[ seq( 1, nrow(dfr3) ) ]
dfr2 <- data.frame( "index"=n0 + 1:VV2,
"variable"=varnames.added,
"variable_orig"=varnames.added1,
"source"=paste0(as.character(transform.formula), collapse=" "))
dfr3 <- rbind( dfr3, dfr2)
dfr3 -> bifieobj$variables
bifieobj$Nvars <- ncol(bifieobj$dat1)
return( bifieobj )
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE.data.transform.R
|
## File Name: BIFIE.derivedParameters.R
## File Version: 0.386
#--- statistical inference for derived parameters
BIFIE.derivedParameters <- function( BIFIE.method, derived.parameters, type=NULL )
{
cl <- match.call()
s1 <- Sys.time()
object <- res1 <- BIFIE.method
parnames <- res1$parnames
Nimp <- res1$Nimp
RR <- res1$RR
# extract replicated parameters
parsres <- extract.replicated.pars( BIFIE.method=res1, type=type )
pars0 <- parsres$parsM
pars0.rep <- parsres$parsrepM
rownames(pars0) <- parnames
rownames(pars0.rep) <- parnames
#- handle formulas
allformulas <- derived.parameters[[1]]
FF <- length(derived.parameters)
if (FF>1){
for (ff in 2:FF){
t1 <- stats::terms(allformulas)
t2 <- paste( c( attr( t1, "term.labels" ),
attr( stats::terms( derived.parameters[[ff]] ), "term.labels" ) ), collapse=" + " )
allformulas <- stats::as.formula( paste( " ~ 0 + ", t2 ) )
}
} else {
t1 <- stats::terms(allformulas)
t2 <- attr( t1, "term.labels" )
allformulas <- stats::as.formula( paste( " ~ 0 + ", t2 ) )
}
# create matrices of derived parameters
der.pars <- stats::model.matrix( allformulas, as.data.frame( t(pars0) ) )
colnames(der.pars) <- names(derived.parameters)
der.pars.rep <- stats::model.matrix( allformulas, as.data.frame( t(pars0.rep) ) )
colnames(der.pars.rep) <- names(derived.parameters)
fayfac <- res1$fayfac
NP <- ncol(der.pars)
Cdes <- diag(NP)
Ccols <- which( colSums( abs( Cdes) ) > 0 )
parsM <- as.matrix( t( der.pars ) )
parsrepM <- as.matrix( t( der.pars.rep ) )
rdes <- rep(0,NP)
#- global Wald test
res0 <- res <- bifiesurvey_rcpp_wald_test( parsM=parsM, parsrepM=parsrepM,
Cdes=Cdes, rdes=rdes, Ccols=Ccols-1, fayfac=fayfac )
res_wald <- data.frame( "D1"=res$D1, "D2"=res$D2, "df1"=res$df,
"D1_df2"=round(res$nu2,1), "D2_df2"=round(res$nu3,1),
"D1_p"=res$p_D1, "D2_p"=res$p_D2 )
var_w <- res0$var_w
var_b <- res0$var_b
# total variance
var_tot <- var_w + ( 1 + 1/Nimp ) * var_b
parmlabel <- names(derived.parameters)
# parameters and standard errors
stat <- data.frame( "parmlabel"=parmlabel, "coef"=rowMeans( parsM ),
"se"=sqrt( diag( var_tot ) ) )
# pars_fmi[pp]=( 1.0 + 1/Nimp2) * pars_varBetween[pp] / pow(pars_se[pp] + eps,2.0) ;
eps <- 1E-10
stat$t <- stat$coef / stat$se
stat$df <- rubin_calc_df2( B=diag(var_b), W=diag(var_w), Nimp, digits=2)
stat$p <- 2*stats::pt( - abs(stat$t), df=stat$df )
stat$fmi <- ( 1+1/Nimp) * diag(var_b) / ( stat$se^2 + eps )
stat$VarMI <- diag( var_b )
stat$VarRep <- diag( var_w )
rownames(stat) <- NULL
if (BIFIE.method$NMI){
Nimp_NMI <- BIFIE.method$Nimp_NMI
res0 <- BIFIE_NMI_inference_parameters( parsM, parsrepM, fayfac,
RR, Nimp, Nimp_NMI, comp_cov=FALSE )
stat$coef <- res0$pars
stat$se <- res0$pars_se
stat$df <- res0$df
stat$t <- res0$pars / res0$pars_se
stat$p <- 2*stats::pt( - abs(stat$t), df=stat$df )
stat$fmi <- res0$pars_fmi
stat$VarMI <- res0$pars_varBetween1 + res0$pars_varBetween2
stat$fmi_St1 <- res0$pars_fmiB
stat$fmi_St2 <- res0$pars_fmiW
}
s2 <- Sys.time()
timediff <- c( s1, s2 ) #, paste(s2-s1 ) )
res <- list( stat=stat, coef=rowMeans( parsM ),
se=sqrt(diag(var_tot)), vcov=var_tot, Nimp=Nimp, fayfac=fayfac,
N=res1$N, RR=res1$RR, NMI=BIFIE.method$NMI, Nimp_NMI=BIFIE.method$Nimp_NMI,
allformulas=allformulas, CALL=cl, timediff=timediff,
derived.parameters=derived.parameters, parsM=parsM, parsrepM=parsrepM,
parnames=names(derived.parameters), res_wald=res_wald )
class(res) <- "BIFIE.derivedParameters"
return(res)
}
#--- summary for BIFIE.derivedParameters function
summary.BIFIE.derivedParameters <- function( object, digits=4, ... )
{
BIFIE.summary(object)
cat("Formulas for Derived Parameters \n\n")
FF <- length( object$derived.parameters)
for (ff in 1:FF){
cat( paste0( object$parnames[ff], " :=", " ",
BIFIEsurvey_print_term_formula( formula=object$derived.parameters[[ff]] )), "\n")
}
cat("\nStatistical Inference for Derived Parameters \n\n")
obji <- object$stat
print_object_summary( obji, digits=digits )
#- Wald test
cat("\n")
BIFIE_waldtest_summary_print_test_statistics(object=object, digits=digits,
value_name="res_wald")
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE.derivedParameters.R
|
## File Name: BIFIE.ecdf.R
## File Version: 0.36
#######################################################################
# empirical distribution function
BIFIE.ecdf <- function( BIFIEobj, vars, breaks=NULL, quanttype=1,
group=NULL, group_values=NULL )
{
#****
s1 <- Sys.time()
cl <- match.call()
bifieobj <- BIFIEobj
if (bifieobj$cdata){
varnames <- unique( c( vars, group, "one") )
bifieobj <- BIFIE.BIFIEcdata2BIFIEdata( bifieobj, varnames=varnames )
}
FF <- Nimp <- bifieobj$Nimp
N <- bifieobj$N
dat1 <- bifieobj$dat1
wgt <- bifieobj$wgt
wgtrep <- bifieobj$wgtrep
varnames <- bifieobj$varnames
RR <- bifieobj$RR
datalistM <- bifieobj$datalistM
fayfac <- bifieobj$fayfac
se <- FALSE
if (RR==1){ RR <- 0 }
if ( ! se ){
wgtrep <- matrix( wgt, ncol=1 )
RR <- 0
}
vars_index <- unlist( sapply( vars, FUN=function(vv){
which( varnames==vv ) }, simplify=FALSE) )
# vars values
VV <- length(vars)
wgt_ <- matrix( wgt, ncol=1 )
if ( is.null( group) ){ nogroup <- TRUE } else { nogroup <- FALSE }
cat(paste0( "|", paste0( rep("*", FF), collapse=""), "|\n" ))
if (nogroup){
group <- "one"
group_values <- c(1)
}
#@@@@***
group_index <- match( group, varnames )
#@@@@***
if ( is.null(group_values ) ){
t1 <- bifie_table( vec=datalistM[, group_index ] )
group_values <- sort( as.numeric( paste( names(t1) ) ))
}
#@@@@***
res00 <- BIFIE_create_pseudogroup( datalistM, group, group_index, group_values )
res00$datalistM -> datalistM
res00$group_index -> group_index
res00$GR -> GR
res00$group_values -> group_values
res00$group -> group
#@@@@***
if ( is.null(breaks) ){
breaks <- as.numeric(seq( 0, 1, .01 ))
}
maxval <- round( max( dat1[, vars_index ], na.rm=TRUE ) * 100 )
#**************************************************************************#
# Rcpp call
res <- bifie_ecdf( datalist=datalistM, wgt1=wgt_, wgtrep=wgtrep, vars_index=vars_index-1,
fayfac=fayfac, NI=Nimp, group_index1=group_index-1, group_values=group_values,
breaks=breaks, quanttype=quanttype, maxval=maxval )
#--- process output
res <- bifie_ecdf_postproc_output( res=res, group_values=group_values, breaks=breaks,
VV=VV, res00=res00, vars=vars, group=group )
ecdf_ <- res$ecdf_
stat <- res$stat
#@@@@***
# multiple groupings
stat <- BIFIE_table_multiple_groupings( dfr=stat, res00=res00 )
#@@@@***
#*************************** OUTPUT ***************************************
s2 <- Sys.time()
timediff <- c( s1, s2 )
res1 <- list( ecdf=ecdf_, stat=stat, output=res, timediff=timediff,
N=N, Nimp=Nimp, RR=RR, fayfac=fayfac,
NMI=BIFIEobj$NMI, Nimp_NMI=BIFIEobj$Nimp_NMI,
CALL=cl )
class(res1) <- "BIFIE.ecdf"
return(res1)
}
###################################################################################
####################################################################################
# summary for BIFIE.ecdf function
summary.BIFIE.ecdf <- function( object, digits=4, ... )
{
BIFIE.summary(object)
cat("Empirical Distribution Function \n")
obji <- object$ecdf
print_object_summary( obji, digits=digits )
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE.ecdf.R
|
## File Name: BIFIE.freq.R
## File Version: 0.531
#######################################################################
# frequency tables
BIFIE.freq <- function( BIFIEobj, vars, group=NULL, group_values=NULL, se=TRUE ){
#****
s1 <- Sys.time()
cl <- match.call()
bifieobj <- BIFIEobj
if (bifieobj$cdata){
varnames <- unique( c( vars, group, "one") )
bifieobj <- BIFIE.BIFIEcdata2BIFIEdata( bifieobj, varnames=varnames )
}
FF <- Nimp <- bifieobj$Nimp
N <- bifieobj$N
dat1 <- bifieobj$dat1
wgt <- bifieobj$wgt
wgtrep <- bifieobj$wgtrep
varnames <- bifieobj$varnames
RR <- bifieobj$RR
datalistM <- bifieobj$datalistM
fayfac <- bifieobj$fayfac
if (RR==1){ RR <- 0 }
if ( ! se ){
wgtrep <- matrix( wgt, ncol=1 )
RR <- 0
}
vars_index <- unlist( sapply( vars, FUN=function(vv){
which( varnames==vv ) } ) )
# vars values
VV <- length(vars)
vars_info <- list(1:VV)
for (vv in 1:VV){
t1 <- bifie_table( datalistM[, vars_index[vv] ] )
vars_info[[vv]] <- sort( as.numeric( paste0(names(t1) )))
}
vars_values_numb <- unlist( lapply( vars_info, FUN=function(uu){ length(uu) } ) )
vars_values <- matrix(NA, nrow=max(vars_values_numb), ncol=VV)
for (vv in 1:VV){
vars_values[ seq(1,vars_values_numb[vv] ), vv ] <- vars_info[[vv]]
}
wgt_ <- matrix( wgt, ncol=1 )
if ( is.null( group) ){ nogroup <- TRUE } else { nogroup <- FALSE }
cat(paste0( "|", paste0( rep("*", FF), collapse=""), "|\n" ))
if (nogroup){
group <- "one"
group_values <- c(1)
}
# group_index <- which( varnames %in% group )
#@@@@***
group_index <- match( group, varnames )
#@@@@***
if ( is.null(group_values ) ){
t1 <- bifie_table( datalistM[, group_index ] )
group_values <- sort( as.numeric( paste( names(t1) ) ))
}
#@@@@***
res00 <- BIFIE_create_pseudogroup( datalistM, group, group_index, group_values )
res00$datalistM -> datalistM
res00$group_index -> group_index
res00$GR -> GR
res00$group_values -> group_values
res00$group -> group
#@@@@***
#**************************************************************************#
# Rcpp call
res <- bifie_freq( datalistM, wgt_, as.matrix(wgtrep), vars_index -1, fayfac,
Nimp, group_index - 1, group_values, as.matrix(vars_values),
vars_values_numb )
GG <- res$outlist$GG
dfr <- data.frame( "var"=rep( rep( vars, vars_values_numb ), each=GG ) )
VV <- length(vars)
varval <- unlist( sapply( 1:VV, FUN=function(vv){
# vv <- 1
rep( vars_values[ 1:vars_values_numb[vv], vv ], GG )
}, simplify=FALSE ) )
dfr$varval <- varval
if (! nogroup){
dfr$groupvar <- group
dfr$groupval <- rep( rep( group_values, VV), rep(vars_values_numb,each=GG) )
}
dfr$Ncases <- rowMeans( res$ncases1M )
dfr$Nweight <- res$perc1$pars
# percentages
dfr$perc <- res$perc2$pars
dfr$perc_SE <- res$perc2$pars_se
# dfr$perc_t <- round( dfr$perc / dfr$perc_SE, 2 )
dfr$perc_fmi <- res$perc2$pars_fmi
dfr$perc_df <- rubin_calc_df( res$perc2, Nimp, indices=NULL)
dfr$perc_VarMI <- res$perc2$pars_varBetween
dfr$perc_VarRep <- res$perc2$pars_varWithin
if (BIFIEobj$NMI ){
res1 <- BIFIE_NMI_inference_parameters( parsM=res$perc2M, parsrepM=res$perc2repM,
fayfac=fayfac, RR=RR, Nimp=Nimp,
Nimp_NMI=BIFIEobj$Nimp_NMI, comp_cov=FALSE )
dfr$perc <- res1$pars
dfr$perc_SE <- res1$pars_se
# dfr$t <- round( dfr$perc / dfr$perc_SE, 2 )
dfr$perc_df <- res1$df
# dfr$p <- stats::pt( - abs( dfr$t ), df=dfr$df) * 2
dfr$perc_fmi <- res1$pars_fmi
dfr$perc_fmi_St1 <- res1$pars_fmiB
dfr$perc_fmi_St2 <- res1$pars_fmiW
dfr$perc_VarMI <- res1$pars_varBetween1 + res1$pars_varBetween2
dfr$perc_VarMI_St1 <- res1$pars_varBetween1
dfr$perc_VarMI_St2 <- res1$pars_varBetween2
dfr$perc_VarRep <- res1$pars_varWithin
}
if ( ( ! se ) & ( RR==0 ) ){
dfr$perc_df <- dfr$perc_SE <- dfr$perc_fmi <- dfr$perc_VarMI <- dfr$perc_VarRep <- NULL
}
if ( Nimp==1 ){
dfr$perc_fmi <- dfr$perc_VarMI <- NULL
}
# create vector of parameter names
nogroupL <- rep( nogroup, nrow(dfr) )
parnames <- paste0( dfr$var, "_", dfr$varval,
ifelse( ! nogroupL, paste0( "_", dfr$groupvar, "_" ), "" ),
ifelse( ! nogroupL, dfr$groupval, "" ) )
#@@@@***
# multiple groupings
dfr <- BIFIE_table_multiple_groupings( dfr, res00 )
#@@@@***
#*************************** OUTPUT ***************************************
s2 <- Sys.time()
timediff <- c( s1, s2 ) #, paste(s2-s1 ) )
res1 <- list( "stat"=dfr, "output"=res, "timediff"=timediff,
"N"=N, "Nimp"=Nimp, "RR"=RR, "fayfac"=fayfac,
"NMI"=BIFIEobj$NMI, "Nimp_NMI"=BIFIEobj$Nimp_NMI,
"parnames"=parnames, "CALL"=cl )
class(res1) <- "BIFIE.freq"
return(res1)
}
###################################################################################
####################################################################################
# summary for BIFIE.freq function
summary.BIFIE.freq <- function( object, digits=3, ... )
{
BIFIE.summary(object)
cat("Relative Frequencies \n")
obji <- object$stat
print_object_summary( obji, digits=digits )
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE.freq.R
|
## File Name: BIFIE.hist.R
## File Version: 0.287
#--- Histogram
BIFIE.hist <- function( BIFIEobj, vars, breaks=NULL,
group=NULL, group_values=NULL )
{
s1 <- Sys.time()
cl <- match.call()
bifieobj <- BIFIEobj
if (bifieobj$cdata){
varnames <- unique( c( vars, group, "one") )
bifieobj <- BIFIE.BIFIEcdata2BIFIEdata( bifieobj, varnames=varnames )
}
FF <- Nimp <- bifieobj$Nimp
N <- bifieobj$N
dat1 <- bifieobj$dat1
wgt <- bifieobj$wgt
wgtrep <- bifieobj$wgtrep
varnames <- bifieobj$varnames
RR <- bifieobj$RR
datalistM <- bifieobj$datalistM
fayfac <- bifieobj$fayfac
vars <- vars[1]
vars_index <- unlist( sapply( vars, FUN=function(vv){
which( varnames==vv ) } ) )
if ( is.null(breaks) ){
requireNamespace("grDevices")
x <- dat1[, vars_index ]
breaks <- pretty(x, n=grDevices::nclass.Sturges(x))
}
RR <- 0
# vars values
VV <- length(vars)
wgt_ <- matrix( wgt, ncol=1 )
if ( is.null( group) ){ nogroup <- TRUE } else { nogroup <- FALSE }
cat(paste0( "|", paste0( rep("*", FF), collapse=""), "|\n" ))
if (nogroup){
group <- "one"
group_values <- c(1)
}
#@@@@***
group_index <- match( group, varnames )
#@@@@***
if ( is.null(group_values ) ){
t1 <- bifie_table( datalistM[, group_index ] )
group_values <- sort( as.numeric( paste( names(t1) ) ))
}
#@@@@***
res00 <- BIFIE_create_pseudogroup( datalistM, group, group_index, group_values )
res00$datalistM -> datalistM
res00$group_index -> group_index
res00$GR -> GR
res00$group_values -> group_values
res00$group -> group
#@@@@***
#--- Rcpp call
res <- bifie_hist( datalist=datalistM, wgt1=wgt_, wgtrep=wgtrep,
vars_index=vars_index-1, fayfac=fayfac, NI=Nimp,
group_index1=group_index-1, group_values=group_values, breaks=breaks )
# create histogram objects
GG <- length(group_values)
histobj <- list(1:GG)
BB <- res$BB
for (gg in 1:GG){
h1 <- list( breaks=res$breaks, counts=res$sumwgt[ ( gg-1)*BB + 1:BB ],
density=res$density_vec[ ( gg-1)*BB + 1:BB ], mids=res$mids )
h1$xname <- paste0( vars, "_", group, group_values[gg] )
if ( stats::sd( diff(res$mids) ) < .000001 ){ h1$equidist <- TRUE } else { h1$equidist <- FALSE }
class(h1) <- "histogram"
histobj[[gg]] <- h1
}
names(histobj) <- paste0( vars, "_", group, group_values )
#*************************** OUTPUT ***************************************
s2 <- Sys.time()
timediff <- c( s1, s2 )
res1 <- list( histobj=histobj, output=res, timediff=timediff,
N=N, Nimp=Nimp, RR=RR, fayfac=fayfac, NMI=BIFIEobj$NMI,
Nimp_NMI=BIFIEobj$Nimp_NMI, GG=GG, CALL=cl)
class(res1) <- "BIFIE.hist"
return(res1)
}
#** summary for BIFIE.hist function
summary.BIFIE.hist <- function( object, ... )
{
BIFIE.summary(object)
}
#** plot function
plot.BIFIE.hist <- function( x, ask=TRUE, ... )
{
requireNamespace("graphics")
res <- x
GG <- res$GG
for (gg in 1:GG){
graphics::plot(res$histobj[[gg]], ... )
graphics::par(ask=ask)
}
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE.hist.R
|
## File Name: BIFIE.lavaan.survey.R
## File Version: 0.642
BIFIE.lavaan.survey <- function(lavmodel, svyrepdes, lavaan_fun="sem",
lavaan_survey_default=FALSE, fit.measures=NULL, ...)
{
CALL <- match.call()
s1 <- Sys.time()
NMI <- FALSE
#* define fit statistics
fit.measures <- BIFIE_lavaan_survey_define_fit_measures(fit.measures=fit.measures)
#* handle design
is_survey_design <- FALSE
NMI <- FALSE
Nimp_NMI <- NULL
variables <- NULL
if ( inherits(svyrepdes,"svyrep.design") ){
svyrepdes0 <- svyrepdes
data0 <- as.data.frame(svyrepdes$variables)
Nimp <- 1
fayfac <- svyrepdes0$scale
lavaan_survey_default <- TRUE
RR <- ncol(svyrepdes0$repweights)
is_survey_design <- TRUE
}
if ( inherits(svyrepdes,"svyimputationList") ){
svyrepdes0 <- svyrepdes$designs[[1]]
data0 <- as.data.frame(svyrepdes0$variables)
Nimp <- length(svyrepdes$designs)
fayfac <- svyrepdes0$scale
RR <- ncol(svyrepdes0$repweights)
is_survey_design <- TRUE
}
if ( inherits(svyrepdes,"BIFIEdata") ){
data0 <- svyrepdes$dat1
Nimp <- svyrepdes$Nimp
fayfac <- svyrepdes$fayfac
NMI <- svyrepdes$NMI
if (NMI){
lavaan_survey_default <- FALSE
}
Nimp_NMI <- svyrepdes$Nimp_NMI
svyrepdes$NMI <- FALSE
RR <- svyrepdes$RR
if (lavaan_survey_default){
svyrepdes <- BIFIEdata2svrepdesign(bifieobj=svyrepdes)
} else {
variables <- BIFIE_lavaan_survey_define_variables(lavmodel=lavmodel,
svyrepdes=svyrepdes)
datalist <- BIFIE.BIFIEdata2datalist(bifieobj=svyrepdes, varnames=variables)
}
}
N <- nrow(data0)
#- fit initial lavaan model
lav_fun <- BIFIE_lavaan_survey_define_lavaan_function(lavaan_fun=lavaan_fun)
lavmodel__ <- lavmodel
args <- list(x="lavmodel__", value=lavmodel, pos=1)
res <- do.call(what="assign", args=args)
lavfit <- lav_fun(lavmodel__, data=data0, ...)
class_lav <- class(lavfit)
lavfit_coef <- BIFIE_lavaan_coef(object=lavfit)
npar <- length(lavfit_coef)
#* wrapper to lavaan.survey
if (lavaan_survey_default){
res <- BIFIE_lavaan_survey_lavaan_survey(lavaan.fit=lavfit, survey.design=svyrepdes)
fitstat <- BIFIE_lavaan_fitMeasures(object=res, fit.measures=fit.measures)
results <- BIFIE_lavaan_coef(object=res)
variances <- BIFIE_lavaan_vcov(object=res)
} else {
results <- list()
variances <- list()
fitstat <- list()
partable <- list()
svyrepdes0 <- NULL
for (ii in 1:Nimp){ #-- loop over imputations
svyrepdes0 <- BIFIE_lavaan_survey_extract_dataset(svyrepdes=svyrepdes,
ii=ii, variables=variables, svyrepdes0=svyrepdes0,
datalist=datalist)
res <- BIFIE_lavaan_survey_lavaan_survey(lavaan.fit=lavfit,
survey.design=svyrepdes0)
results[[ii]] <- BIFIE_lavaan_coef(object=res)
variances[[ii]] <- BIFIE_lavaan_vcov(object=res)
fitstat[[ii]] <- BIFIE_lavaan_fitMeasures(object=res, fit.measures=fit.measures)
partable[[ii]] <- res@ParTable
}
results <- bifie_extend_list_length2(x=results)
variances <- bifie_extend_list_length2(x=variances)
# combine fit statistics
fitstat <- BIFIE_lavaan_survey_combine_fit_measures(fitstat=fitstat, Nimp=Nimp)
if (! NMI){
# inference parameters for multiply imputed datasets
inf_res <- BIFIE_mitools_MIcombine(results=results, variances=variances)
} else {
# nested multiply imputed datasets
inf_res <- BIFIE_lavaan_survey_NMIcombine(results=results,
variances=variances, Nimp_NMI=Nimp_NMI)
}
#--- include merged parameters
res@Fit@x <- as.vector(inf_res$coefficients)
vcov1 <- res@vcov
vcov1$vcov <- as.matrix(inf_res$variance)
res@vcov <- vcov1
# combine results for lavaan parameter table
partable <- BIFIE_lavaan_survey_combine_partable(partable=partable,
Nimp=Nimp, inf_res=inf_res)
res@ParTable <- partable
}
#-- output
s2 <- Sys.time()
time <- c(s1, s2)
res1 <- list(lavfit=res, fitstat=fitstat, CALL=CALL, time=time,
NMI=NMI, fayfac=fayfac, N=N, Nimp=Nimp, Nimp_NMI=Nimp_NMI, RR=RR,
results=results, variances=variances, partable=partable )
class(res1) <- "BIFIE.lavaan.survey"
return(res1)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE.lavaan.survey.R
|
## File Name: BIFIE.linreg.R
## File Version: 0.586
#--- Linear regression
BIFIE.linreg <- function( BIFIEobj, dep=NULL, pre=NULL,
formula=NULL, group=NULL, group_values=NULL, se=TRUE )
{
s1 <- Sys.time()
cl <- match.call()
bifieobj <- BIFIEobj
if (bifieobj$cdata){
formula_vars <- NULL
if (! is.null(formula) ){
formula_vars <- all.vars( formula )
}
varnames <- unique( c( dep, pre, group, "one", formula_vars ) )
bifieobj <- BIFIE.BIFIEcdata2BIFIEdata( bifieobj, varnames=varnames )
}
FF <- Nimp <- bifieobj$Nimp
N <- bifieobj$N
dat1 <- bifieobj$dat1
wgt <- bifieobj$wgt
wgtrep <- bifieobj$wgtrep
varnames <- bifieobj$varnames
RR <- bifieobj$RR
datalistM <- bifieobj$datalistM
fayfac <- bifieobj$fayfac
#*** look for formula objects
if ( ! is.null( formula) ){
cat("|*** Data Preparation ")
utils::flush.console()
bifieobj2 <- datalistM
colnames(bifieobj2) <- varnames
if ( is.null(group) ){ group <- "one" ; group_values <- 1 }
bifieobj2 <- as.data.frame( bifieobj2 )
m1 <- stats::model.matrix(formula, data=bifieobj2)
m0 <- m1
m1 <- matrix( NA, nrow=nrow(bifieobj2), ncol=ncol(m0) )
m1[ match( rownames(m0),rownames(bifieobj2) ), ] <- m0
colnames(m1) <- colnames(m0)
#****
dep <- rownames( attr( stats::terms(formula),"factors") )[1]
pre <- colnames( m1 )
datalistM <- as.matrix( cbind( bifieobj2[, dep ], m1, bifieobj2[,group] ) )
varnames <- c( dep, pre, group )
cat("\n")
}
if (RR==1){ RR <- 0 }
if ( ! se ){
wgtrep <- matrix( wgt, ncol=1 )
RR <- 0
}
dep_index <- unlist( sapply( dep, FUN=function(vv){
which( varnames==vv ) } ) )
pre_index <- unlist( sapply( pre, FUN=function(vv){
which( varnames==vv ) } ) )
# vars values
VV <- length(pre)
wgt_ <- matrix( wgt, ncol=1 )
if ( is.null( group) ){ nogroup <- TRUE } else { nogroup <- FALSE }
cat(paste0( "|", paste0( rep("*", FF), collapse=""), "|\n" ))
if (nogroup){
group <- "one"
group_values <- c(1)
}
#@@@@***
group_index <- match( group, varnames )
#@@@@***
if ( is.null(group_values ) ){
t1 <- bifie_table( datalistM[, group_index ] )
group_values <- sort( as.numeric( paste( names(t1) ) ))
}
#@@@@***
res00 <- BIFIE_create_pseudogroup( datalistM, group, group_index, group_values )
res00$datalistM -> datalistM
res00$group_index -> group_index
res00$GR -> GR
res00$group_values -> group_values
res00$group -> group
#@@@@***
#---- Rcpp call of linear regression function
res <- bifiesurvey_rcpp_linreg( datalist=datalistM, wgt1=wgt_, wgtrep=as.matrix(wgtrep),
dep_index=dep_index-1, pre_index=pre_index-1, fayfac=fayfac,
NI=Nimp, group_index1=group_index-1, group_values=group_values )
GG <- length(group_values)
# ZZ <- nrow(itempair_index )
ZZ <- 2*VV+2
p1 <- c( rep("b",VV), c("sigma", "R^2"), rep("beta",VV) )
p2 <- c( pre, c(NA,NA), pre )
dfr <- data.frame( "parameter"=rep(p1,GG) )
dfr$var <- rep(p2,GG)
if (! nogroup){
dfr$groupvar <- group
dfr$groupval <- rep( group_values, each=ZZ )
}
dfr$Ncases <- rep( rowMeans( res$ncasesM ), each=ZZ )
dfr$Nweight <- rep( rowMeans( res$sumwgtM ), each=ZZ )
dfr <- create_summary_table( res_pars=res$regrcoefL,
parsM=res$regrcoefM, parsrepM=res$regrcoefrepM,
dfr=dfr, BIFIEobj=BIFIEobj )
dfr <- clean_summary_table( dfr=dfr, RR=RR, se=se, Nimp=Nimp )
# create vector of parameter names
nogroupL <- rep( nogroup, nrow(dfr) )
parnames <- paste0( dfr$parameter, "_", dfr$var,
ifelse( ! nogroupL, paste0( "_", dfr$groupvar, "_" ), "" ),
ifelse( ! nogroupL, dfr$groupval, "" ) )
#@@@@***
# multiple groupings
dfr <- BIFIE_table_multiple_groupings( dfr, res00 )
#@@@@***
#****** OUTPUT
s2 <- Sys.time()
timediff <- c( s1, s2 ) #, paste(s2-s1 ) )
res1 <- list( "stat"=dfr, "output"=res, "timediff"=timediff,
"N"=N, "Nimp"=Nimp, "RR"=RR, "fayfac"=fayfac,
"NMI"=BIFIEobj$NMI, "Nimp_NMI"=BIFIEobj$Nimp_NMI,
"GG"=GG, "parnames"=parnames, "CALL"=cl)
class(res1) <- "BIFIE.linreg"
return(res1)
}
#--- summary for BIFIE.linreg function
summary.BIFIE.linreg <- function( object, digits=4, ... )
{
BIFIE.summary(object)
cat("Statistical Inference for Linear Regression \n\n")
obji <- object$stat
print_object_summary( obji, digits=digits )
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE.linreg.R
|
## File Name: BIFIE.logistreg.R
## File Version: 0.435
#-- logistic regression
BIFIE.logistreg <- function( BIFIEobj, dep=NULL, pre=NULL,
formula=NULL, group=NULL, group_values=NULL, se=TRUE,
eps=1E-8, maxiter=100)
{
s1 <- Sys.time()
cl <- match.call()
bifieobj <- BIFIEobj
if (bifieobj$cdata){
formula_vars <- NULL
if (! is.null(formula) ){
formula_vars <- all.vars( formula )
}
varnames <- unique( c( dep, pre, group, "one", formula_vars ) )
bifieobj <- BIFIE.BIFIEcdata2BIFIEdata( bifieobj, varnames=varnames )
}
FF <- Nimp <- bifieobj$Nimp
N <- bifieobj$N
dat1 <- bifieobj$dat1
wgt <- bifieobj$wgt
wgtrep <- bifieobj$wgtrep
varnames <- bifieobj$varnames
RR <- bifieobj$RR
datalistM <- bifieobj$datalistM
fayfac <- bifieobj$fayfac
#*** look for formula objects
if ( ! is.null( formula) ){
cat("|*** Data Preparation ")
utils::flush.console()
bifieobj2 <- datalistM
colnames(bifieobj2) <- varnames
if ( is.null(group) ){ group <- "one" ; group_values <- 1 }
bifieobj2 <- as.data.frame( bifieobj2 )
m1 <- stats::model.matrix(formula, data=bifieobj2)
m0 <- m1
m1 <- matrix( NA, nrow=nrow(bifieobj2), ncol=ncol(m0) )
m1[ match( rownames(m0),rownames(bifieobj2) ), ] <- m0
colnames(m1) <- colnames(m0)
dep <- rownames( attr( stats::terms(formula),"factors") )[1]
pre <- colnames( m1 )
datalistM <- as.matrix( cbind( bifieobj2[, dep ], m1, bifieobj2[,group] ) )
varnames <- c( dep, pre, group )
cat("\n")
}
if (RR==1){ RR <- 0 }
if ( ! se ){
wgtrep <- matrix( wgt, ncol=1 )
RR <- 0
}
dep_index <- unlist( sapply( dep, FUN=function(vv){
which( varnames==vv ) } ) )
pre_index <- unlist( sapply( pre, FUN=function(vv){
which( varnames==vv ) } ) )
# vars values
VV <- length(pre)
wgt_ <- matrix( wgt, ncol=1 )
if ( is.null( group) ){ nogroup <- TRUE } else { nogroup <- FALSE }
cat(paste0( "|", paste0( rep("*", FF), collapse=""), "|\n" ))
if (nogroup){
group <- "one"
group_values <- c(1)
}
#@@@@***
group_index <- match( group, varnames )
#@@@@***
if ( is.null(group_values) ){
t1 <- bifie_table( datalistM[, group_index ] )
group_values <- sort( as.numeric( paste( names(t1) ) ))
}
#@@@@***
res00 <- BIFIE_create_pseudogroup( datalistM, group, group_index, group_values )
res00$datalistM -> datalistM
res00$group_index -> group_index
res00$GR -> GR
res00$group_values -> group_values
res00$group -> group
#@@@@***
#--- Rcpp call to logistic regression
res <- bifiesurvey_rcpp_logistreg( datalist=datalistM, wgt1=wgt_,
wgtrep=as.matrix(wgtrep), dep_index=dep_index-1, pre_index=pre_index-1,
fayfac=fayfac, NI=Nimp, group_index1=group_index-1, group_values=group_values,
eps=eps, maxiter=maxiter )
GG <- length(group_values)
ZZ <- VV+1
p1 <- c( rep("b",VV), "R2" )
p2 <- c( pre, "NA" )
dfr <- data.frame( "parameter"=rep(p1,GG) )
dfr$var <- rep(p2,GG)
if (! nogroup){
dfr$groupvar <- group
dfr$groupval <- rep( group_values, each=ZZ )
}
dfr$Ncases <- rep( rowMeans( res$ncasesM ), each=ZZ )
dfr$Nweight <- rep( rowMeans( res$sumwgtM ), each=ZZ )
dfr <- create_summary_table( res_pars=res$regrcoefL,
parsM=res$regrcoefM, parsrepM=res$regrcoefrepM,
dfr=dfr, BIFIEobj=BIFIEobj )
dfr <- clean_summary_table( dfr=dfr, RR=RR, se=se, Nimp=Nimp )
# create vector of parameter names
nogroupL <- rep( nogroup, nrow(dfr) )
parnames <- paste0( dfr$parameter, "_", dfr$var,
ifelse( ! nogroupL, paste0( "_", dfr$groupvar, "_" ), "" ),
ifelse( ! nogroupL, dfr$groupval, "" ) )
#@@@@***
# multiple groupings
dfr <- BIFIE_table_multiple_groupings( dfr, res00 )
#@@@@***
#*************************** OUTPUT ***************************************
s2 <- Sys.time()
timediff <- c(s1, s2)
res1 <- list( stat=dfr, output=res, timediff=timediff,
N=N, Nimp=Nimp, RR=RR, fayfac=fayfac,
NMI=BIFIEobj$NMI, Nimp_NMI=BIFIEobj$Nimp_NMI,
GG=GG, parnames=parnames, CALL=cl)
class(res1) <- "BIFIE.logistreg"
return(res1)
}
# summary for BIFIE.linreg function
summary.BIFIE.logistreg <- function( object, digits=4, ... )
{
BIFIE.summary(object)
cat("Statistical Inference for Logistic Regression \n")
obji <- object$stat
print_object_summary( obji, digits=digits )
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE.logistreg.R
|
## File Name: BIFIE.mva.R
## File Version: 0.331
#######################################################################
# Missing value analysis
BIFIE.mva <- function( BIFIEobj, missvars, covariates=NULL, se=TRUE )
{
s1 <- Sys.time()
bifieobj <- BIFIEobj
cl <- match.call()
if ( ! bifieobj$cdata ){
varnames <- unique( c(missvars, covariates ) )
bifieobj <- BIFIE.BIFIEdata2BIFIEcdata( bifieobj, varnames )
}
if ( is.null(covariates) ){
covariates <- "one"
}
if ( is.null(covariates) ){
N <- bifieobj$N
transform.formula <- paste0( "~ 0 + I ( stats::runif( ", N, ", 0, 1E-10) ) " )
bifieobj <- BIFIE.data.transform( bifieobj, transform.formula, "_null" )
covariates <- bifieobj$varnames.added
se <- FALSE
}
FF <- Nimp <- bifieobj$Nimp
N <- bifieobj$N
dat1 <- bifieobj$dat1
wgt <- bifieobj$wgt
wgtrep <- bifieobj$wgtrep
varnames <- bifieobj$varnames
RR <- bifieobj$RR
datalistM <- bifieobj$datalistM
fayfac <- bifieobj$fayfac
# start with a compact BIFIEdata object
varnames <- unique( c(missvars, covariates ) )
# assume that bifieobj is already in cdata format
# define selected response indicators
missvars_index <- match( missvars, colnames(bifieobj$dat1) )
datalistM_ind_sel <- bifieobj$datalistM_ind[, missvars_index, drop=FALSE ]
respvars <- paste0("resp_", missvars )
colnames(datalistM_ind_sel) <- respvars
VVadd <- length(respvars )
varnames1 <- c( varnames, respvars )
bifieobj$datalistM_ind <- cbind( bifieobj$datalistM_ind, datalistM_ind_sel )
bifieobj$dat1 <- cbind( bifieobj$dat1, datalistM_ind_sel )
bifieobj$Nvars <- bifieobj$Nvars + VVadd
bifieobj$varnames <- c( bifieobj$varnames, respvars )
# select dataset
bifieobj <- BIFIE.BIFIEcdata2BIFIEdata( bifieobj, varnames=varnames1 )
RR <- bifieobj$RR
do_test <- TRUE
if (RR < 2 ){
wgtrep <- bifieobj$wgtrep
do_test <- FALSE
wgtrep <- cbind( wgtrep, wgtrep + stats::runif( nrow(wgtrep), 0, 1E-4) )
bifieobj$wgtrep <- wgtrep
bifieobj$RR <- 2
}
if ( is.null( covariates) ){
do_test <- FALSE
se <- FALSE
covariates <- "one"
}
if (RR==1){ RR <- 0 }
if ( ! se ){
N11 <- length(wgt)
wgtrep <- matrix( NA, nrow=N11, ncol=2 )
wgtrep[,1] <-wgt
eps <- 1E-8
wgtrep[,2] <- wgt + stats::runif(N11, -eps,eps)
RR <- 0
bifieobj$wgtrep <- wgtrep
bifieobj$RR <- ncol(wgtrep)
}
#*****
# collect results
VV <- length(respvars)
CVV <- length(covariates)
res_list <- list(1:VV)
dfr <- NULL
RR <- bifieobj$RR
for (vv in 1:VV){
rvv <- respvars[vv]
res.vv <- as.list(1:2)
names(res.vv) <- c("stat", "dstat")
res <- BIFIE.univar( bifieobj, vars=covariates, group=rvv,
group_values=0:1 )
res.vv$stat <- res$stat
res1 <- BIFIE.univar.test( res, wald_test=FALSE )
res.vv$dstat <- res1$stat.dstat
res_list[[vv]] <- res.vv
# collect results
dfr.vv <- data.frame( "respvar"=rep(rvv,CVV) )
dfr.vv$missprop <- res$stat$Nweight[1] / ( res$stat$Nweight[1] + res$stat$Nweight[2] )
dfr.vv$covariate <- covariates
if ( do_test ){
dfr.vv$d <- res1$stat.dstat$d
dfr.vv$d_SE <- res1$stat.dstat$d_SE
dfr.vv$t <- res1$stat.dstat$t
dfr.vv$p <- res1$stat.dstat$p
}
dfr.vv$M_resp <- res$stat$M[ seq(2,2*CVV, 2 ) ]
dfr.vv$M_miss <- res$stat$M[ seq(1,2*CVV, 2 ) ]
dfr.vv$SD_resp <- res$stat$SD[ seq(2,2*CVV, 2 ) ]
dfr.vv$SD_miss <- res$stat$SD[ seq(1,2*CVV, 2 ) ]
dfr <- rbind( dfr, dfr.vv )
}
if ( covariates[1]=="_null" ){ se <- FALSE }
if ( ! do_test ){
RR <- 0
}
if ( ( ! se ) | ( RR==0 ) ){
dfr$t <- dfr$p <- dfr$d_SE <- NULL
}
if ( covariates[1] %in% c("_null","one") ){
dfr$covariate <- dfr$d <- dfr$M_resp <- NULL
dfr$M_miss <- dfr$SD_resp <- dfr$SD_miss <- NULL
}
#***** OUTPUT
s2 <- Sys.time()
timediff <- c( s1, s2 ) #, paste(s2-s1 ) )
res1 <- list( "stat.mva"=dfr, "res_list"=res_list,
"timediff"=timediff,
"N"=N, "Nimp"=Nimp, "RR"=RR, "fayfac"=fayfac,
"NMI"=BIFIEobj$NMI, "Nimp_NMI"=BIFIEobj$Nimp_NMI,
"CALL"=cl )
class(res1) <- "BIFIE.mva"
return(res1)
}
###################################################################################
####################################################################################
# summary for BIFIE.mva function
summary.BIFIE.mva <- function( object, digits=4, ... )
{
BIFIE.summary(object)
cat("Missing Value Analysis \n")
obji <- object$stat.mva
print_object_summary( obji, digits=digits )
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE.mva.R
|
## File Name: BIFIE.pathmodel.R
## File Version: 1.321
#--- path model
BIFIE.pathmodel <- function( BIFIEobj, lavaan.model, reliability=NULL,
group=NULL, group_values=NULL, se=TRUE )
{
requireNamespace("TAM")
s1 <- Sys.time()
cl <- match.call()
bifieobj <- BIFIEobj
dat <- bifieobj$dat1
# lavaanify syntax
lavpartable <- TAM::lavaanify.IRT( lavmodel=lavaan.model, data=dat )$lavpartable
vars <- colnames(dat)
lav1 <- lavpartable[ lavpartable$op %in% c("=~", "~"), ]
lav.vars <- unique( c( lav1$lhs, lav1$rhs ) )
NV <- length(lav.vars)
# observed variables
obs.vars <- intersect( vars, lav.vars )
# latent variables
lat.vars <- setdiff( lav.vars, obs.vars )
# create model matrix for latent variables
NLV <- length(lat.vars)
L <- matrix( 0, nrow=NLV, ncol=NV )
rownames(L) <- lat.vars
colnames(L) <- lav.vars
if (NLV>0){
for (vv in 1:NLV){
lav.vv <- lav1[ ( lav1$op=="=~" ) & ( lav1$lhs==lat.vars[vv] ), ]
L[ vv, lav.vv$rhs ] <- ifelse( is.na(lav.vv$ustart), 1, lav.vv$ustart )
}
}
L_row_index <- match( rownames(L), lav.vars )
# model matrix for regressions
lav2 <- lav1[ lav1$op=="~", ]
dep <- unique( lav2$lhs )
NR <- length(dep)
R <- matrix( 0, nrow=NR, ncol=NV )
rownames(R) <- dep
colnames(R) <- lav.vars
for (vv in 1:NR){
lav.vv <- lav1[ ( lav1$op=="~" ) & ( lav1$lhs==dep[vv] ), "rhs"]
R[ vv, lav.vv ] <- 1
}
R_row_index <- match( rownames(R), lav.vars )
# matrix B with regression coefficients
B <- matrix(0,nrow=NV, ncol=NV)
rownames(B) <- colnames(B) <- lav.vars
for (vv in 1:NR){
B[ rownames(R)[vv], ] <- R[vv, ]
}
# error variances and covariances
E <- matrix( 0, nrow=NV, ncol=NV )
rownames(E) <- colnames(E) <- lav.vars
lav2 <- lavpartable[ lavpartable$op=="~~", ]
lav2 <- stats::na.omit( lav2 )
NG <- nrow(lav2)
if (NG > 0){
for ( gg in 1:NG){
E[ lav2$lhs[gg], lav2$rhs[gg] ] <- lav2$ustart[gg]
}
}
# compute matrix power for pathe coefficients
ind <- 0
Bpow <- B
Bpowsum <- Bpow
for (kk in 1:100){
Bpow <- Bpow %*% B
Bpowsum <- Bpowsum + Bpow
ind <- ind + 1
if ( sum( Bpow ) < 1E-10 ){ break }
}
maxpow <- ind
ind.vars <- colnames(B)[ which( colSums( B ) > 0 ) ]
M1 <- matrix( ind.vars, ncol=1 )
for (oo in 1:maxpow){
NM1 <- nrow(M1)
M2 <- NULL
for (mm in 1:NM1){
v1 <- rownames(B)[ B[, colnames(B)==paste(M1[ mm, oo ]) ] > 0 ]
if (oo>1 ){ v1 <- c( "", v1 ) }
M1mm <- t(M1[ mm, 1:oo ])
HV <- length(v1)
H1 <- matrix( "", nrow=HV, ncol=oo+1 )
H1[, oo+1 ] <- v1
H1[, 1:oo ] <- matrix( M1mm, nrow=HV, ncol=oo, byrow=TRUE )
M2 <- rbind(M2, H1 )
}
M1 <- M2
}
M1_index <- matrix( 0, nrow(M1), ncol(M1) )
for (mm in 1:ncol(M1) ){
M1_index[, mm ] <- match( M1[,mm], lav.vars )
}
# compute total effects
tot_paths <- t( apply( M1, 1, FUN=function(ll){
vv <- ll[ ll !="" ]
N1 <- length(vv)
c( paste0( vv[1], "->", vv[N1] ), N1 )
} ) )
tot_paths <- as.data.frame( tot_paths )
tot_paths2 <- tot_paths[ as.numeric(paste(tot_paths[,2])) > 2, ]
paths <- unique( paste(tot_paths2[,1 ] ) )
tot_paths$pathindex <- match( paste(tot_paths[,1]), paths ) + nrow(M1)
if ( mean( is.na(tot_paths$pathindex ) ) < 1 ){
NP0 <- max( tot_paths$pathindex, na.rm=TRUE)
} else {
NP0 <- nrow(M1)
}
coeff_index <- cbind( tot_paths$pathindex, M1_index )
NV <- ncol(Bpowsum)
indices <- which( Bpowsum > 0 )
if (bifieobj$cdata){
varnames <- unique( c( obs.vars, group, "one" ) )
bifieobj <- BIFIE.BIFIEcdata2BIFIEdata( bifieobj, varnames=varnames )
}
FF <- Nimp <- bifieobj$Nimp
N <- bifieobj$N
dat1 <- bifieobj$dat1
wgt <- bifieobj$wgt
wgtrep <- bifieobj$wgtrep
varnames <- bifieobj$varnames
RR <- bifieobj$RR
datalistM <- bifieobj$datalistM
fayfac <- bifieobj$fayfac
vars_index <- match( lav.vars, colnames(dat1) )
# unreliability
unreliability <- rep(0, NV)
names(unreliability) <- lav.vars
unreliability[ match( names(reliability), lav.vars) ] <- 1 - reliability
NL <- nrow(L)
if (NL==0 ){
L <- matrix( 0, nrow=1, ncol=NV)
colnames(L) <- lav.vars
}
tot_paths <- data.frame( tot_paths, "pathindex2"=tot_paths$pathindex )
tot_paths$pathindex2 <- match( tot_paths$pathindex2,
stats::na.omit(unique( tot_paths$pathindex2 )) ) + NP0
tot_paths$pathindex2[ as.numeric(paste(tot_paths[,2])) <=2 ] <- NA
if ( mean( is.na(tot_paths$pathindex2 ) ) < 1 ){
NP0 <- max( tot_paths$pathindex2, na.rm=TRUE)
} else {
NP0 <- nrow(M1)
}
coeff_index1 <- cbind( coeff_index[,1], tot_paths$pathindex2, coeff_index[,-1] )
wgt_ <- matrix( wgt, ncol=1 )
if ( is.null( group) ){ nogroup <- TRUE } else { nogroup <- FALSE }
cat(paste0( "|", paste0( rep("*", FF), collapse=""), "|\n" ))
if (nogroup){
group <- "one"
group_values <- c(1)
}
#@@@@***
group_index <- match( group, varnames )
#@@@@***
if ( is.null(group_values ) ){
t1 <- bifie_table( datalistM[, group_index ] )
group_values <- sort( as.numeric( paste( names(t1) ) ))
}
#@@@@***
res00 <- BIFIE_create_pseudogroup( datalistM, group, group_index, group_values )
res00$datalistM -> datalistM
res00$group_index -> group_index
res00$GR -> GR
res00$group_values -> group_values
res00$group -> group
#@@@@***
if (RR==1){ RR <- 0 }
if ( ! se ){
wgtrep <- matrix( wgt, ncol=1 )
RR <- 0
}
#**** estimate path model
res <- bifiesurvey_rcpp_pathmodel( datalist=datalistM, wgt1=wgt_, wgtrep=wgtrep,
vars_index=vars_index-1, fayfac=fayfac, NI=Nimp, group_index1=group_index-1,
group_values=group_values, L=L, L_row_index=L_row_index-1,
NL=NL, E=E, R=R, R_row_index=R_row_index-1,
coeff_index=coeff_index1, NP0=NP0, unreliability=unreliability )
GG <- length(group_values)
#*** create parameter labels
p0 <- paste(M1[,1])
for (vv in seq(2,ncol(M1) ) ){
p0 <- ifelse( M1[,vv] !="", paste0( p0, "->", M1[,vv] ), p0 )
}
p1 <- ifelse( tot_paths[,2]=="2", paste0(M1[,2], "~", M1[,1] ), p0 )
p2 <- unique( paste(tot_paths[ ! is.na( tot_paths$pathindex ), 1 ]) )
p2 <- gsub( "->", "-+>", p2 )
p1 <- c( p1, p2 )
p2 <- unique( paste(tot_paths[ ! is.na( tot_paths$pathindex2 ), 1 ]) )
p2 <- gsub( "->", "-~>", p2 )
p1 <- c( p1, p2 )
p1 <- c( p1, paste0(p1, "_stand") )
p1 <- c( p1, paste0( rownames(R), "_R2" ) )
p1 <- c( p1, paste0( rownames(R), "_ResidVar" ) )
dfr <- data.frame( "parameter"=rep(p1,GG) )
dfr$type <- ""
ZZ <- length(p1)
if (! nogroup){
dfr$groupvar <- group
dfr$groupval <- rep( group_values, each=ZZ )
}
dfr$Ncases <- rep( res$ncases[,1], each=ZZ )
dfr$Nweight <- rep( res$sumwgt[,1], each=ZZ )
dfr <- create_summary_table( res_pars=res$parsL,
parsM=res$parsM, parsrepM=res$parsrepM,
dfr=dfr, BIFIEobj=BIFIEobj )
dfr <- clean_summary_table( dfr=dfr, RR=RR, se=se, Nimp=Nimp )
dfr[ grep( "_R2", paste(dfr$parameter) ), "type"] <- "RSquared"
dfr[ grep( "_ResidVar", paste(dfr$parameter) ), "type"] <- "ResidVar"
dfr[ grep( "~", paste(dfr$parameter) ), "type"] <- "RegrCoeff"
ind <- grep( "->", paste(dfr$parameter) )
if ( length(ind) > 0 ){
dfr[ ind, "type"] <- "PathCoeff"
}
ind <- grep( "-+>", paste(dfr$parameter), fixed=TRUE )
if ( length(ind) > 0 ){
dfr[ ind, "type"] <- "TotalEff"
}
ind <- grep( "-~>", paste(dfr$parameter), fixed=TRUE )
if ( length(ind) > 0 ){
dfr[ ind, "type"] <- "IndEff"
}
# create vector of parameter names
nogroupL <- rep( nogroup, nrow(dfr) )
parnames <- paste0( dfr$parameter, "_",
ifelse( ! nogroupL, paste0( "_", dfr$groupvar, "_" ), "" ),
ifelse( ! nogroupL, dfr$groupval, "" ) )
#@@@@***
# multiple groupings
dfr <- BIFIE_table_multiple_groupings( dfr, res00 )
#@@@@***
#*************************** OUTPUT ***************************************
s2 <- Sys.time()
timediff <- c( s1, s2 )
res1 <- list( stat=dfr, output=res, timediff=timediff,
N=N, Nimp=Nimp, RR=RR, fayfac=fayfac,
NMI=BIFIEobj$NMI, Nimp_NMI=BIFIEobj$Nimp_NMI,
GG=GG, parnames=parnames, lavaan.model=lavaan.model,
reliability=reliability, CALL=cl)
class(res1) <- "BIFIE.pathmodel"
return(res1)
}
#-- summary for BIFIE.pathmodel function
summary.BIFIE.pathmodel <- function( object, digits=4, ... )
{
BIFIE.summary(object)
#- model specification
BIFIE_pathmodel_summary_print_model_specification(object=object, digits=digits)
# estimated parameters
cat("Statistical Inference for Path Model \n\n")
obji <- object$stat
print_object_summary( obji, digits=digits )
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE.pathmodel.R
|
## File Name: BIFIE.progressbar.R
## File Version: 0.09
#--- Computation of a progress bar
BIFIE.progressbar <- function( ops, prblen )
{
prb <- prblen
vec <- seq(1, ops)
vec[ ops ] <- ops - 0.1
NR <- ops / prb
m1 <- vec %% NR
pr1 <- 1 * ( diff(m1) < 0 )
pr1 <- c( 1, pr1 )
# returns a vector of zeroes and one indicating
# iteration of a move in th progress bar
return(pr1)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE.progressbar.R
|
## File Name: BIFIE.summary.R
## File Version: 0.231
BIFIE.summary <- function(object, print.time=TRUE)
{
cat("------------------------------------------------------------\n")
BIFIE_print_package_description(pack="BIFIEsurvey")
if ( inherits(object,"BIFIE.lavaan.survey") ){
BIFIE_print_package_description(pack="lavaan")
BIFIE_print_package_description(pack="lavaan.survey")
}
#* function
cat( paste0("\nFunction '", class(object) ) )
if ( inherits(object,"BIFIE.waldtest") ){
cat( paste0( "' for BIFIE method '", object$class.BIFIE.method ) )
}
cat("'" )
cat("\n\nCall:\n", paste(deparse(object$CALL), sep="\n", collapse="\n"),
"\n\n", sep="")
cat( "Date of Analysis:", paste( object$time[1] ), "\n" )
if (print.time){
cat("Computation time:", print(object$time[2] - object$time[1] ), "\n\n")
} else {
cat("\n")
}
if ( ! object$NMI ){
cat("Multiply imputed dataset\n\n")
}
if ( object$NMI ){
cat("Nested multiply imputed dataset\n\n")
}
cat( "Number of persons", "=", object$N, "\n" )
# cat( "Number of imputed datasets=", object$Nimp, "\n" )
if ( ! object$NMI){
cat( "Number of imputed datasets", "=", object$Nimp, "\n" )
}
if ( object$NMI){
cat( "Number of imputed between-nest datasets", "=", object$Nimp_NMI[1], "\n" )
cat( "Number of imputed within-nest datasets", "=", object$Nimp_NMI[2], "\n" )
}
cat( "Number of Jackknife zones per dataset", "=", object$RR, "\n" )
cat( "Fay factor", "=", round( object$fayfac, 5 ), "\n\n" )
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE.summary.R
|
## File Name: BIFIE.survey.R
## File Version: 0.228
BIFIE.survey <- function(svyrepdes, survey.function, ...)
{
CALL <- match.call()
s1 <- Sys.time()
NMI <- FALSE
Nimp_NMI <- NULL
svrepdes <- svyrepdes
if ( inherits(svyrepdes,"BIFIEdata") ){
data0 <- svyrepdes$dat1
N <- nrow(data0)
Nimp <- svyrepdes$Nimp
fayfac <- svyrepdes$fayfac
NMI <- svyrepdes$NMI
Nimp_NMI <- svyrepdes$Nimp_NMI
svyrepdes$NMI <- FALSE
RR <- svyrepdes$RR
wgt <- svyrepdes$wgt
wgtrep <- svyrepdes$wgtrep
variables <- NULL
args <- list(...)
for (vv in c("formula", "x")){
if ( vv %in% names(args)){
args_vv <- args[[vv]]
if (inherits(args_vv,"formula") ){
variables <- all.vars(args_vv)
}
}
}
datalist <- BIFIE.BIFIEdata2datalist( bifieobj=svyrepdes, varnames=variables)
}
if ( inherits(svyrepdes,"svyimputationList") ){
res <- svrepdesign_extract_data(svrepdesign=svrepdes$designs[[1]])
N <- res$N
RR <- res$RR
fayfac <- res$fayfac
Nimp <- length(svrepdes$designs)
}
#* loop over imputations
if ( inherits(svyrepdes, c("BIFIEdata", "svyimputationList") ) ){
res <- list()
svyrep_ii <- NULL
for (ii in 1:Nimp){
if ( inherits(svyrepdes,"BIFIEdata") ){
svyrep_ii <- BIFIE_lavaan_survey_extract_dataset( svyrepdes=svyrepdes,
ii=ii, variables=NULL, svyrepdes0=svyrep_ii, datalist=datalist)
}
if ( inherits(svyrepdes,"svyimputationList") ){
svyrep_ii <- svrepdes$designs[[ii]]
}
args <- list(...)
args$design <- svyrep_ii
res[[ii]] <- do.call( what=survey.function, args=args)
}
results <- res
results <- bifie_extend_list_length2(x=results)
}
if (! NMI){
#*** statistical inference using mitools package
stat <- BIFIE_mitools_MIcombine(results=results)
} else {
#*** nested multiply imputed dataset
stat <- BIFIE_NMIcombine_results(results=results, Nimp_NMI=Nimp_NMI, package="stats")
}
#-- output
s2 <- Sys.time()
time <- c(s1, s2)
res1 <- list(stat=stat, CALL=CALL, time=time, NMI=NMI, fayfac=fayfac, N=N,
Nimp=Nimp, RR=RR, results=results, Nimp_NMI=Nimp_NMI)
class(res1) <- "BIFIE.survey"
return(res1)
}
#-- summary function
summary.BIFIE.survey <- function( object, digits=3, ... )
{
BIFIE.summary(object)
cat("Estimated Parameters\n")
summary(object$stat, digits=digits)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE.survey.R
|
## File Name: BIFIE.twolevelreg.R
## File Version: 0.583
#--- BIFIE.twolevelreg
BIFIE.twolevelreg <- function( BIFIEobj, dep, formula.fixed, formula.random,
idcluster, wgtlevel2=NULL, wgtlevel1=NULL, group=NULL,
group_values=NULL, recov_constraint=NULL, se=TRUE,
globconv=1E-6, maxiter=1000)
{
#****
s1 <- Sys.time()
cl <- match.call()
bifieobj <- BIFIEobj
#********
# extract variables
if (bifieobj$cdata){
formula_vars <- c( all.vars( formula.fixed ),
all.vars( formula.random ) )
varnames <- unique( c( dep, group, "one", idcluster, formula_vars,
wgtlevel1, wgtlevel2 ) )
bifieobj <- BIFIE.BIFIEcdata2BIFIEdata( bifieobj, varnames=varnames )
}
# extract values
FF <- Nimp <- bifieobj$Nimp
N <- bifieobj$N
dat1 <- bifieobj$dat1
wgt <- bifieobj$wgt
wgtrep <- bifieobj$wgtrep
varnames <- bifieobj$varnames
RR <- bifieobj$RR
datalistM <- bifieobj$datalistM
fayfac <- bifieobj$fayfac
# create datalist
datalistM <- as.data.frame( datalistM )
colnames(datalistM) <- bifieobj$varnames
bifieobj2 <- datalistM
#*********** X predictor matrix
m1 <- stats::model.matrix( formula.fixed, datalistM )
m0 <- m1
xnames <- colnames(m1)
m1 <- matrix( NA, nrow=nrow(bifieobj2), ncol=ncol(m0) )
m1[ match( rownames(m0),rownames(bifieobj2) ), ] <- m0
colnames(m1) <- colnames(m0)
X_list <- as.matrix( m1 )
#************* Z predictor matrix
m1 <- stats::model.matrix( formula.random, datalistM )
m0 <- m1
znames <- colnames(m1)
m1 <- matrix( NA, nrow=nrow(bifieobj2), ncol=ncol(m0) )
m1[ match( rownames(m0),rownames(bifieobj2) ), ] <- m0
colnames(m1) <- colnames(m0)
Z_list <- as.matrix( m1 )
#*************** y outcome values
y_list <- as.vector( bifieobj2[, dep ] )
globconv <- stats::var(y_list, na.rm=TRUE) * globconv
#*************** collect cluster identifiers
dat1 <- bifieobj$dat1
idcluster0 <- idcluster
clusters <- unique( dat1[, idcluster0 ] )
idcluster <- match( dat1[, idcluster0 ], clusters )
#************ weights
eps <- max(wgt)*1E-10
wgttot <- wgt + eps
wgtlev2_full <- dat1[, wgtlevel2 ]
wgtlev2 <- stats::aggregate( wgtlev2_full, list(idcluster), mean )[,2]
eps <- 1E-10 * max( wgtlev2)
wgtlev2 <- wgtlev2 + eps
if ( is.null(wgtlevel1) ){
wgtlev1 <- wgttot / ( wgtlev2_full + eps )
} else {
wgtlev1 <- dat1[, wgtlevel1 ]
}
wgtrep1 <- wgtrep
#****** groups
if ( is.null( group) ){
nogroup <- TRUE
} else {
nogroup <- FALSE
}
if (nogroup){
group <- "one"
group_values <- c(1)
}
# group vector
group_vec <- dat1[, group ]
if ( is.null(group_values ) ){
t1 <- bifie_table( datalistM[, group ] )
group_values <- sort( as.numeric( paste( names(t1) ) ))
}
# use groups
group_vec <- match( group_vec, group_values )
group_values0 <- group_values
group_values <- seq( 1, length( unique( group_values) ) )
group_vec <- as.numeric( group_vec)
group_values <- as.numeric( group_values)
# constraints for random effects covariance
# recov_constraint
is_rcov_constraint <- 1
NRC <- nrow(recov_constraint)
if ( is.null(recov_constraint)){
recov_constraint <- matrix( 0, nrow=1,ncol=3)
is_rcov_constraint <- 0
NRC <- 0
}
recov_constraint[,1:2] <- recov_constraint[,1:2] - 1
if ( ! se ){
wgtrep1 <- matrix( wgt, ncol=1 )
RR <- 0
}
#**** display stopping message if clustering variable is not ordered
ordered_clusters <- sum( diff(idcluster) < 0 )==0
if ( ! ordered_clusters){
cat("Cluster identifiers must be ordered ")
cat("for applying 'BIFIE.twolevelreg'!\n")
stop()
}
#*********** estimate multilevel model
res <- bifie_mla2( X_list, Z_list, y_list, wgttot, wgtlev2, wgtlev1,
globconv, maxiter, group_vec - 1, group_values - 1, idcluster - 1,
wgtrep1, Nimp, fayfac, recov_constraint, is_rcov_constraint )
# dimensions
NX <- ncol(X_list)
NZ <- ncol(Z_list)
NC <- length(clusters)
GG <- length(group_values)
NP <- res$NP
parnames <- paste0( "beta_", xnames )
for (ii in 1:NZ){
for (jj in 1:NZ){
if (ii==jj){
v1 <- paste0( "Var_", znames[ii] )
}
if (ii<jj){
v1 <- paste0( "Cov_", znames[ii], znames[jj] )
}
if (ii>jj){
v1 <- paste0( "Cor_", znames[ii], znames[jj] )
}
parnames <- c( parnames, v1 )
}
}
parnames <- c( parnames, "ResidVar")
parnames <- c( parnames, "ExplVar_Lev2_Fixed" )
parnames <- c( parnames, "ExplVar_Lev2_Random" )
parnames <- c( parnames, "ResidVar_Lev2" )
parnames <- c( parnames, "ExplVar_Lev1_Fixed" )
parnames <- c( parnames, "ExplVar_Lev1_Random" )
parnames <- c( parnames, "ResidVar_Lev1" )
parnames <- c( parnames, "Var_Total" )
parnames <- c( parnames, "R2_Lev2" )
parnames <- c( parnames, "R2_Lev1" )
parnames <- c( parnames, "R2_Total" )
parnames <- c( parnames, "ICC_Uncond" )
parnames <- c( parnames, "ICC_UncondWB" )
parnames <- c( parnames, "ICC_Cond" )
#*******************
# parameter table
p1 <- parnames
dfr <- data.frame( "parameter"=rep(p1,GG))
ZZ <- NP
if (! nogroup){
dfr$groupvar <- group
dfr$groupval <- rep( group_values0, each=ZZ )
}
dfr <- create_summary_table( res_pars=res$parsL,
parsM=res$parsM, parsrepM=res$parsrepM,
dfr=dfr, BIFIEobj=BIFIEobj )
dfr <- clean_summary_table( dfr=dfr, RR=RR, se=se, Nimp=Nimp )
# create vector of parameter names
nogroupL <- rep( nogroup, nrow(dfr) )
parnames <- paste0( dfr$parameter,
ifelse( ! nogroupL, paste0( "_", dfr$groupvar, "_" ), "" ),
ifelse( ! nogroupL, dfr$groupval, "" ) )
rownames(dfr) <- parnames
#***************************
# inference with mitools
fvcovM <- res$fvcov
vcov0 <- matrix(0, nrow=GG*NX, ncol=GG*NX)
vcov.list <- as.list(1:Nimp)
for (ii in 1:Nimp){
vcov1 <- vcov0
for (gg in 1:GG){
ind1 <- 1:NX + (gg-1)*NX
vcov1[ ind1, ind1 ] <- fvcovM[ ind1, 1:NX + (ii-1)*NX ]
}
vcov.list[[ii]] <- vcov1
}
parsM <- res$parsM
NP <- nrow(parsM) / GG
parsM0 <- matrix( 0, nrow=NX*GG, ncol=Nimp)
parnames_sel <- NULL
for (gg in 1:GG){
parsM0[ 1:NX + (gg-1)*NX, ] <- parsM[ 1:NX + (gg-1)*NP, ]
parnames_sel <- c( parnames_sel, parnames[ 1:NX + (gg-1)*NP ] )
}
parsM <- parsM0
pars.list <- as.list(1:Nimp)
for (ii in 1:Nimp){
pars.list[[ii]] <- parsM[,ii]
names(pars.list[[ii]] ) <- parnames_sel
}
if (Nimp==1){
pars.list <- list( pars.list[[1]], pars.list[[1]] )
vcov.list <- list( vcov.list[[1]], vcov.list[[1]] )
}
micombs <- BIFIE_mitools_MIcombine( results=pars.list, variances=vcov.list )
if ( ! se ){
dfr$SE <- dfr$fmi <- dfr$VarRep <- NA
v1 <- diag( micombs$variance )
dfr[ parnames_sel, "SE" ] <- sqrt( v1 )
dfr$t <- round( dfr$est / dfr$SE, 2 )
dfr$p <- stats::pnorm( - abs( dfr$t ) ) * 2
dfr[ parnames_sel, "fmi" ] <- micombs$missinfo
dfr$VarMI <- dfr$fmi * dfr$SE^2
dfr$VarRep <- (1-dfr$fmi) * dfr$SE^2
}
#**** variance decompositions
vardecomp <- list( Sigma_W_yXM=res$Sigma_W_yXM, Sigma_B_yXM=res$Sigma_B_yXM,
Sigma_W_yZM=res$Sigma_W_yZM, Sigma_B_yZM=res$Sigma_B_yZM,
totmean_yXM=res$totmean_yXM, totmean_yZM=res$totmean_yZM )
#*************************** OUTPUT ***************************************
s2 <- Sys.time()
timediff <- c( s1, s2 )
res1 <- list( stat=dfr, output=res,
timediff=timediff, Npers=res$Npers, Nclusters=res$Nclusters,
N=N, Nimp=Nimp, RR=RR, fayfac=fayfac,
NMI=BIFIEobj$NMI, Nimp_NMI=BIFIEobj$Nimp_NMI,
GG=GG, micombs=micombs, se=se,
parnames=parnames, parnames_sel=parnames_sel,
vardecomp=vardecomp, idcluster_table=res$idcluster_table,
CALL=cl)
class(res1) <- "BIFIE.twolevelreg"
return(res1)
}
# summary for BIFIE.linreg function
summary.BIFIE.twolevelreg <- function( object, digits=4, ... )
{
BIFIE.summary(object)
cat( paste0( "Number of persons:"), object$Npers, "\n")
cat( paste0( "Number of clusters:"), object$Nclusters, "\n\n")
cat("Statistical Inference for Two-Level Linear Regression \n\n")
obji <- object$stat
rownames(obji) <- NULL
print_object_summary( obji, digits=digits )
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE.twolevelreg.R
|
## File Name: BIFIE.univar.R
## File Version: 1.844
#--- univariate statistics
BIFIE.univar <- function( BIFIEobj, vars, group=NULL, group_values=NULL, se=TRUE ){
#****
s1 <- Sys.time()
cl <- match.call()
bifieobj <- BIFIEobj
if (bifieobj$cdata){
varnames <- unique( c( vars, group, "one") )
bifieobj <- BIFIE.BIFIEcdata2BIFIEdata( bifieobj, varnames=varnames )
}
FF <- Nimp <- bifieobj$Nimp
N <- bifieobj$N
dat1 <- bifieobj$dat1
wgt <- bifieobj$wgt
wgtrep <- bifieobj$wgtrep
varnames <- bifieobj$varnames
RR <- bifieobj$RR
datalistM <- bifieobj$datalistM
fayfac <- bifieobj$fayfac
if (RR==1){ RR <- 0 }
if ( ! se ){
wgtrep <- matrix( wgt, ncol=1 )
RR <- 0
}
vars_index <- unlist( sapply( vars, FUN=function(vv){
which( varnames==vv ) } ) )
wgt_ <- matrix( wgt, ncol=1 )
if ( is.null( group) ){
nogroup <- TRUE } else {
nogroup <- FALSE
}
cat(paste0( "|", paste0( rep("*", FF), collapse=""), "|\n" ))
if (nogroup){
group <- "one"
group_values <- c(1)
}
#@@@@***
group_index <- match( group, varnames )
#@@@@***
if ( is.null(group_values ) ){
t1 <- bifie_table( datalistM[, group_index ] )
group_values <- sort( as.numeric( paste( names(t1) ) ))
}
#@@@@***
res00 <- BIFIE_create_pseudogroup( datalistM, group, group_index, group_values )
res00$datalistM -> datalistM
res00$group_index -> group_index
res00$GR -> GR
res00$group_values -> group_values
res00$group -> group
#@@@@***
#****************** no grouping variable **********************************#
if ( nogroup ){
res <- univar_multiple_V2group( datalistM, wgt_, wgtrep, vars_index-1,
fayfac, Nimp, group_index-1, group_values )
GG <- length(group_values)
VV <- length(vars)
dfr <- data.frame( "var"=rep(vars,each=GG),
"Nweight"=rowMeans(res$sumweightM),
"Ncases"=rowMeans( res$ncasesM),
"M"=res$mean1, "M_SE"=res$mean1_se )
dfr$M_df <- round( (Nimp-1)*( 1 + (Nimp*res$mean1_varWithin )/ ( Nimp+1) / res$mean1_varBetween )^2, 2 )
vv <- "M_df"
dfr[,vv] <- ifelse( dfr[,vv] > 1000, Inf, dfr[,vv] )
dfr$M_t <- dfr$M / dfr$M_SE
dfr$M_p <- 2* stats::pt( - abs( dfr$M_t), df=dfr$M_df )
dfr0 <- data.frame( "M_fmi"=res$mean1_fmi,
"M_VarMI"=res$mean1_varBetween, "M_VarRep"=res$mean1_varWithin,
"SD"=res$sd1, "SD_SE"=res$sd1_se )
dfr <- cbind( dfr, dfr0 )
dfr$SD_df <- round( (Nimp-1)*( 1 + (Nimp*res$sd1_varWithin )/ ( Nimp+1) / res$sd1_varBetween )^2, 2 )
vv <- "SD_df"
dfr[,vv] <- ifelse( dfr[,vv] > 1000, Inf, dfr[,vv] )
dfr$SD_t <- dfr$M / dfr$SD_SE
dfr$SD_p <- 2*stats::pt( - abs( dfr$SD_t), df=dfr$SD_df )
dfr0 <- data.frame( "SD_fmi"=res$sd1_fmi, "SD_VarMI"=res$sd1_varBetween, "SD_VarRep"=res$sd1_varWithin
)
if (BIFIEobj$NMI ){
# M
res1 <- BIFIE_NMI_inference_parameters( parsM=res$mean1M, parsrepM=res$mean1repM,
fayfac=fayfac, RR=RR, Nimp=Nimp,
Nimp_NMI=BIFIEobj$Nimp_NMI, comp_cov=FALSE )
dfr$M <- res1$pars
dfr$M_SE <- res1$pars_se
dfr$M_df <- res1$df
dfr$M_t <- res1$pars / res1$pars_se
dfr$M_p <- 2*stats::pt( - abs( dfr$M_t), df=res1$df )
dfr$M_fmi <- res1$pars_fmi
dfr$M_VarMI <- res1$pars_varBetween1 + res1$pars_varBetween2
dfr$M_VarRep <- res1$pars_varWithin
# SD
res1 <- BIFIE_NMI_inference_parameters( parsM=res$sd1M, parsrepM=res$sd1repM,
fayfac=fayfac, RR=RR, Nimp=Nimp,
Nimp_NMI=BIFIEobj$Nimp_NMI, comp_cov=FALSE )
dfr$SD <- res1$pars
dfr$SD_SE <- res1$pars_se
dfr$SD_df <- res1$df
dfr$SD_t <- res1$pars / res1$pars_se
dfr$SD_p <- 2*stats::pt( - abs( dfr$SD_t), df=res1$df )
dfr$SD_fmi <- res1$pars_fmi
dfr$SD_VarMI <- res1$pars_varBetween1 + res1$pars_varBetween2
dfr$SD_VarRep <- res1$pars_varWithin
}
}
#****************** with grouping variable ********************************#
if ( ! nogroup ){
res <- univar_multiple_V2group( datalistM, wgt_, wgtrep, vars_index - 1, fayfac, Nimp,
group_index - 1, group_values )
GG <- length(group_values)
VV <- length(vars)
dfr <- data.frame( "var"=rep(vars,each=GG),
"groupvar"=group,
"groupval"=rep(group_values, VV ),
"Nweight"=rep( rowMeans(res$sumweightM), VV ),
"Ncases"=res$ncases,
"M"=res$mean1, "M_SE"=res$mean1_se )
dfr$M_df <- round( (Nimp-1)*( 1 + (Nimp*res$mean1_varWithin )/ ( Nimp+1) / res$mean1_varBetween )^2, 2 )
vv <- "M_df"
dfr[,vv] <- ifelse( dfr[,vv] > 1000, Inf, dfr[,vv] )
dfr$M_t <- dfr$M / dfr$M_SE
dfr$M_p <- 2*stats::pt( - abs( dfr$M_t), df=dfr$M_df )
dfr <- data.frame( dfr, "M_fmi"=res$mean1_fmi, "M_VarMI"=res$mean1_varBetween, "M_VarRep"=res$mean1_varWithin,
"SD"=res$sd1, "SD_SE"=res$sd1_se )
dfr$SD_df <- round( (Nimp-1)*( 1 + (Nimp*res$sd1_varWithin )/ ( Nimp+1) / res$sd1_varBetween )^2, 2 )
vv <- "SD_df"
dfr[,vv] <- ifelse( dfr[,vv] > 1000, Inf, dfr[,vv] )
dfr$SD_t <- dfr$M / dfr$SD_SE
dfr$SD_p <- 2*stats::pt( - abs( dfr$SD_t), df=dfr$SD_df )
dfr <- data.frame( dfr,"SD_fmi"=res$sd1_fmi, "SD_VarMI"=res$sd1_varBetween, "SD_VarRep"=res$sd1_varWithin
)
if (BIFIEobj$NMI ){
# M
res1 <- BIFIE_NMI_inference_parameters( parsM=res$mean1M, parsrepM=res$mean1repM,
fayfac=fayfac, RR=RR, Nimp=Nimp,
Nimp_NMI=BIFIEobj$Nimp_NMI, comp_cov=FALSE )
dfr$M <- res1$pars
dfr$M_SE <- res1$pars_se
dfr$M_df <- res1$df
dfr$M_t <- res1$pars / res1$pars_se
dfr$M_p <- 2*stats::pt( - abs( dfr$M_t), df=res1$df )
dfr$M_fmi <- res1$pars_fmi
dfr$M_VarMI <- res1$pars_varBetween1 + res1$pars_varBetween2
dfr$M_VarRep <- res1$pars_varWithin
# SD
res1 <- BIFIE_NMI_inference_parameters( parsM=res$sd1M, parsrepM=res$sd1repM,
fayfac=fayfac, RR=RR, Nimp=Nimp,
Nimp_NMI=BIFIEobj$Nimp_NMI, comp_cov=FALSE )
dfr$SD <- res1$pars
dfr$SD_SE <- res1$pars_se
dfr$SD_df <- res1$df
dfr$SD_t <- res1$pars / res1$pars_se
dfr$SD_p <- 2*pt( - abs( dfr$SD_t), df=res1$df )
dfr$SD_fmi <- res1$pars_fmi
dfr$SD_VarMI <- res1$pars_varBetween1 + res1$pars_varBetween2
dfr$SD_VarRep <- res1$pars_varWithin
}
}
if ( ( ! se ) & ( RR==0 ) ){
dfr$M_SE <- dfr$M_fmi <- dfr$M_VarMI <- dfr$M_VarRep <- dfr$M_t <- dfr$M_df <- dfr$M_p <- NULL
dfr$SD_SE <- dfr$SD_fmi <- dfr$SD_VarMI <- dfr$SD_VarRep <-
dfr$SD_t <- dfr$SD_df <- dfr$SD_p <-NULL
}
if ( Nimp==1 ){
dfr$M_fmi <- dfr$M_VarMI <- NULL
dfr$SD_fmi <- dfr$SD_VarMI <- NULL
}
#****
# statistics for mean and SD
v1 <- c("var", "groupvar", "groupval", "Nweight", "Ncases" )
v1 <- intersect( v1, colnames(dfr) )
cdfr <- colnames(dfr)
stat_M <- dfr[, c( v1, cdfr[ substring( cdfr, 1,1)=="M" ] ) ]
stat_SD <- dfr[, c( v1, cdfr[ substring( cdfr, 1,2)=="SD" ] ) ]
# create vector of parameter names
nogroupL <- rep( nogroup, nrow(dfr) )
parnames <- paste0( dfr$var,
ifelse( ! nogroupL, paste0( "_", dfr$groupvar, "_" ), "" ),
ifelse( ! nogroupL, dfr$groupval, "" ) )
#@@@@***
# multiple groupings
dfr <- BIFIE_table_multiple_groupings( dfr, res00 )
#@@@@***
stat_M <- BIFIE_table_multiple_groupings( stat_M, res00 )
stat_SD <- BIFIE_table_multiple_groupings( stat_SD, res00 )
#*************************** OUTPUT ***************************************
s2 <- Sys.time()
timediff <- c( s1, s2 ) #, paste(s2-s1 ) )
res1 <- list( stat=dfr, stat_M=stat_M, stat_SD=stat_SD,
output=res, timediff=timediff,
N=N, Nimp=Nimp, RR=RR, fayfac=fayfac, parnames=parnames,
NMI=BIFIEobj$NMI, Nimp_NMI=BIFIEobj$Nimp_NMI, se=se,
GG=GG, VV=VV, vars=vars, group=group, CALL=cl)
class(res1) <- "BIFIE.univar"
return(res1)
}
# summary for BIFIE.univar function
summary.BIFIE.univar <- function( object, digits=3, ... )
{
BIFIE.summary(object)
cat("Univariate Statistics | Means\n")
obji <- object$stat_M
print_object_summary( obji, digits=digits )
cat("\nUnivariate Statistics | Standard Deviations\n")
obji <- object$stat_SD
print_object_summary( obji, digits=digits )
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE.univar.R
|
## File Name: BIFIE.univar.test.R
## File Version: 0.471
#######################################################################
# BIFIE univar.test
BIFIE.univar.test <- function( BIFIE.method, wald_test=TRUE )
{
s1 <- Sys.time()
cl <- match.call()
res5 <- BIFIE.method
if (res5$group=="one"){ stop("This function can only be applied with a grouping variable.\n")}
if (BIFIE.method$RR < 2){ wald_test <- FALSE }
mean1M <- res5$output$mean1M
sd1M <- res5$output$sd1M
sumweightM <- res5$output$sumweightM
GG <- res5$GG
group_values <- ( res5$stat$groupval )[1:GG]
if( res5$group=="pseudogroup" ){
is_pseudogroup <- TRUE
} else {
is_pseudogroup <- FALSE
}
if ( is.null( group_values) ){
group_values <- 1:GG
}
mean1repM <- res5$output$mean1repM
sd1repM <- res5$output$sd1repM
sumweightrepM <- res5$output$sumweightrepM
fayfac <- res5$fayfac
VV <- res5$VV
vars <- res5$vars
RR <- res5$RR
if (RR==1){ RR <- 0 }
group <- res5$group
N <- res5$N
Nimp <- res5$Nimp
#**** Rcpp call
res <- bifie_test_univar( mean1M, sd1M, sumweightM, GG, group_values,
mean1repM, sd1repM, sumweightrepM, fayfac )
#****
# output eta^2
dfr <- data.frame( "var"=vars, "group"=group )
dfr$eta2 <- res$eta2L$pars^2
dfr$eta <- res$eta2L$pars
dfr$eta_SE <- res$eta2L$pars_se
dfr$fmi <- res$eta2L$pars_fmi
dfr$df <- rubin_calc_df( res$eta2L, Nimp )
dfr$VarMI <- res$eta2L$pars_varBetween
dfr$VarRep <- res$eta2L$pars_varWithin
if (BIFIE.method$NMI ){
# eta2
res1 <- BIFIE_NMI_inference_parameters( parsM=res$eta2M, parsrepM=res$eta2repM,
fayfac=fayfac, RR=RR, Nimp=Nimp,
Nimp_NMI=BIFIE.method$Nimp_NMI, comp_cov=FALSE )
dfr$eta <- res1$pars
dfr$eta_SE <- res1$pars_se
dfr$df <- res1$df
dfr$eta_fmi <- res1$pars_fmi
dfr$eta_VarMI <- res1$pars_varBetween1 + res1$pars_varBetween2
dfr$eta_VarRep <- res1$pars_varWithin
}
if (RR==0){
dfr$df <- dfr$SE <- dfr$fmi <- dfr$VarMI <- dfr$VarRep <- NULL
}
# extract replicated statistics for d and eta squared
stat.eta2 <- dfr
#****
# output d values
group_values_matrix <- res$group_values_matrix
ZZ <- nrow(group_values_matrix)
dfr <- data.frame( "var"=rep(vars,each=ZZ) )
g2 <- group_values_matrix[ rep(1:ZZ, VV),, drop=FALSE]
g2 <- data.frame(g2)
colnames(g2) <- c("groupval1", "groupval2")
dfr$group <- group
dfr <- cbind( dfr, g2 )
r5 <- res5$stat
h1 <- NULL
h4 <- h3 <- h2 <- NULL
for (kk in 1:2){
group_values_matrix[,kk] <- match( group_values_matrix[,kk], group_values )
}
for (vv in 1:VV){
h1 <- c(h1, r5[ (vv-1)*GG + group_values_matrix[,1], "M" ] )
h2 <- c(h2, r5[ (vv-1)*GG + group_values_matrix[,2], "M" ] )
h3 <- c(h3, r5[ (vv-1)*GG + group_values_matrix[,1], "SD" ] )
h4 <- c(h4, r5[ (vv-1)*GG + group_values_matrix[,2], "SD" ] )
}
dfr$M1 <- h1
dfr$M2 <- h2
dfr$SD <- sqrt( ( h3^2 + h4^2 ) / 2 )
dfr$d <- res$dstatL$pars
dfr$d_SE <- res$dstatL$pars_se
dfr$d_t <- dfr$d / dfr$d_SE
dfr$d_df <- rubin_calc_df( res$dstatL, Nimp )
dfr$d_p <- stats::pt( - abs(dfr$d_t ), df=dfr$d_df)*2
dfr$d_fmi <- res$dstatL$pars_fmi
dfr$d_VarMI <- res$dstatL$pars_varBetween
dfr$d_VarRep <- res$dstatL$pars_varWithin
if ( BIFIE.method$NMI ){
res1 <- BIFIE_NMI_inference_parameters( parsM=res$dstatM, parsrepM=res$dstatrepM,
fayfac=fayfac, RR=RR, Nimp=BIFIE.method$Nimp,
Nimp_NMI=BIFIE.method$Nimp_NMI, comp_cov=FALSE )
dfr$d <- res1$pars
dfr$d_SE <- res1$pars_se
dfr$d_t <- round( dfr$d / dfr$d_SE, 2 )
dfr$d_df <- res1$df
dfr$d_p <- stats::pt( - abs( dfr$d_t ), df=dfr$d_df) * 2
dfr$d_fmi <- res1$pars_fmi
dfr$d_VarMI <- res1$pars_varBetween1 + res1$pars_varBetween2
dfr$d_VarRep <- res1$pars_varWithin
}
if ( ( ! res5$se ) & ( RR==0 ) ){
dfr$d_SE <- dfr$d_fmi <- dfr$d_VarMI <- dfr$d_VarRep <- NULL
}
if ( is_pseudogroup ){
stat <- res5$stat[ 1:GG, ]
stat$pseudogroup <- 1:GG
ind1 <- grep( "groupvar", colnames(stat) )
ind2 <- grep( "groupval", colnames(stat) )
groupvar_pseudo <- apply( stat[, ind1 ], 1, FUN=function(hh){ paste0( hh, collapse="#") } )
groupval_pseudo <- apply( stat[, ind2 ], 1, FUN=function(hh){ paste0( hh, collapse="#") } )
dfr$group <- groupvar_pseudo[1]
dfr$groupval1 <- groupval_pseudo[ dfr$groupval1 ]
dfr$groupval2 <- groupval_pseudo[ dfr$groupval2 ]
}
stat.dstat <- dfr
#*****
# F statistics
dfr <- NULL
for (vv in 1:VV){
Cdes <- matrix( 0, nrow=GG-1, ncol=GG*VV )
indvec <- 1:(GG-1)
for (zz in indvec ){
Cdes[ zz, c(zz + (vv-1)*GG,zz+1 + (vv-1)*GG ) ] <- c(1,-1)
}
rdes <- rep(0,GG-1)
if ( wald_test ){
wres5 <- BIFIE.waldtest( res5, Cdes=Cdes, rdes=rdes )
dfr <- rbind( dfr, wres5$stat.D )
}
}
if ( wald_test ){
dfr <- data.frame( "variable"=vars, "group"=group, dfr )
stat.F <- dfr
} else {
stat.F <- NA
}
parnames <- NULL
#*************************** OUTPUT ***************************************
s2 <- Sys.time()
timediff <- c( s1, s2 ) #, paste(s2-s1 ) )
res1 <- list( "stat.F"=stat.F, "stat.eta"=stat.eta2, "stat.dstat"=stat.dstat,
"timediff"=timediff,
"N"=N, "Nimp"=Nimp, "RR"=RR, "fayfac"=fayfac,
"NMI"=BIFIE.method$NMI, "Nimp_NMI"=BIFIE.method$Nimp_NMI,
"GG"=GG, "parnames"=parnames, "CALL"=cl, wald_test=wald_test )
class(res1) <- "BIFIE.univar.test"
return(res1)
}
###################################################################################
####################################################################################
# summary
summary.BIFIE.univar.test <- function( object, digits=4, ... )
{
BIFIE.summary(object)
if ( object$wald_test ){
cat("F Test (ANOVA) \n")
obji <- object$stat.F
print_object_summary( obji, digits=digits )
}
cat("\nEta Squared \n")
obji <- object$stat.eta
print_object_summary( obji, digits=digits )
cat("\nCohen's d Statistic \n")
obji <- object$stat.dstat
print_object_summary( obji, digits=digits )
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE.univar.test.R
|
## File Name: BIFIE.waldtest.R
## File Version: 1.311
#***** BIFIE Wald test
BIFIE.waldtest <- function( BIFIE.method, Cdes=NULL, rdes=NULL, type=NULL )
{
s1 <- Sys.time()
cl <- match.call()
res1 <- BIFIE.method
# extract replicated parameters
parsres <- extract.replicated.pars( BIFIE.method=res1, type=type)
parsM <- parsres$parsM
parsrepM <- parsres$parsrepM
parnames <- parsres$parnames
fayfac <- res1$fayfac
N <- BIFIE.method$N
Nimp <- BIFIE.method$Nimp
RR <- BIFIE.method$RR
#--- class derivedParameters
if (is.null(Cdes) & (inherits(BIFIE.method,"BIFIE.derivedParameters")) ){
res <- extract.replicated.pars(BIFIE.method=BIFIE.method)
parsM <- res$parsM
np <- nrow(parsM)
Cdes <- diag(np)
rdes <- rep(0,np)
}
#****** which columns in C do have non-zero entries
Ccols <- which( colSums( abs( Cdes) ) > 0 )
if ( ! BIFIE.method$NMI ){
# apply Rcpp Wald test function
res <- bifiesurvey_rcpp_wald_test( parsM=parsM, parsrepM=parsrepM, Cdes=Cdes,
rdes=rdes, Ccols=Ccols-1, fayfac=fayfac )
RR <- res$RR
Nimp <- res$Nimp
fayfac <- res$fayfac
# data frame with results
dfr <- data.frame( "D1"=res$D1, "D2"=res$D2, "df1"=res$df,
"D1_df2"=round(res$nu2,1), "D2_df2"=round(res$nu3,1),
"D1_p"=res$p_D1, "D2_p"=res$p_D2 )
}
if ( BIFIE.method$NMI ){
Cdes_cols <- Cdes[, Ccols, drop=FALSE]
df1 <- nrow(Cdes_cols)
parsM2 <- Cdes_cols %*% parsM[ Ccols, ]
parsrepM2 <- Cdes_cols %*% parsrepM[ Ccols, ]
# within covariance matrices
res0 <- bifie_comp_vcov_within( parsM2, parsrepM2, fayfac,
BIFIE.method$RR, Nimp )
u <- res0$u
Nimp_NMI <- BIFIE.method$Nimp_NMI
qhat <- array( parsM2, dim=c( df1, Nimp_NMI[2], Nimp_NMI[1] ) )
qhat <- aperm( qhat, c(3,2,1) )
v1 <- paste0("parm",1:df1)
dimnames(qhat) <- list(
paste0("imp_nmi_dim1_", seq(1,dim(qhat)[[1]] ) ),
paste0("imp_nmi_dim2_", seq(1,dim(qhat)[[2]] ) ), v1 )
if ( ! is.null( dimnames(qhat) ) ){
dimnames(qhat)[[3]] <- v1
}
u <- array( u, dim=c( df1, df1, Nimp_NMI[2], Nimp_NMI[1] ) )
u <- aperm( u, c(4,3,1,2) )
res <- miceadds::NMIwaldtest( qhat=qhat, u=u, testnull=v1)
dfr <- data.frame( "D1"=res$stat$F, "df1"=res$stat$df1,
"D1_df2"=round(res$stat$df2,1), "D1_p"=res$stat$pval )
}
#*************************** OUTPUT ***************************************
s2 <- Sys.time()
timediff <- c( s1, s2 ) #, paste(s2-s1 ) )
res1 <- list( "stat.D"=dfr, "timediff"=timediff,
"N"=N, "Nimp"=Nimp, "RR"=RR, "fayfac"=fayfac,
"NMI"=BIFIE.method$NMI, "Nimp_NMI"=BIFIE.method$Nimp_NMI,
"class.BIFIE.method"=class(BIFIE.method), "CALL"=cl )
class(res1) <- "BIFIE.waldtest"
return(res1)
}
#--- summary for BIFIE.waldtest function
summary.BIFIE.waldtest <- function( object, digits=4, ... )
{
BIFIE.summary(object, FALSE)
BIFIE_waldtest_summary_print_test_statistics(object=object, digits=digits,
value_name="stat.D")
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE.waldtest.R
|
## File Name: BIFIE_NMI_inference_parameters.R
## File Version: 0.18
###########################################################
# NMI inference, helper function
BIFIE_NMI_inference_parameters <- function( parsM, parsrepM, fayfac,
RR, Nimp, Nimp_NMI, comp_cov=FALSE )
{
res0 <- bifie_comp_vcov_within( parsM, parsrepM, fayfac, RR, Nimp )
u_diag <- res0$u_diag
NV <- length(u_diag) / Nimp
u_diag <- array( u_diag, dim=c( NV, Nimp_NMI[2], Nimp_NMI[1] ) )
u_diag <- aperm( u_diag, c(3,2,1) )
u <- array( 0, dim=c( Nimp_NMI[1], Nimp_NMI[2], NV, NV ) )
for (ii in seq( 1, Nimp_NMI[1] ) ){
for (jj in seq( 1, Nimp_NMI[2] ) ){
if (NV>1){
diag(u[ii,jj,,]) <- u_diag[ii,jj,]
}
if (NV==1){
u[ii,jj,1,1] <- u_diag[ii,jj,1]
}
}
}
qhat <- array( parsM, dim=c(NV, Nimp_NMI[2], Nimp_NMI[1] ) )
qhat <- aperm( qhat, c(3,2,1) )
# inference using miceadds package
res1 <- miceadds::NMIcombine( qhat=qhat, u=u, comp_cov=comp_cov, is_list=FALSE )
res1$df <- ifelse( res1$df > 1000, Inf, res1$df )
# output management
res1$pars <- res1$qbar
res1$pars_se <- sqrt( diag( res1$Tm ) )
res1$pars_fmi <- res1$lambda
res1$pars_fmiB <- res1$lambda_Between
res1$pars_fmiW <- res1$lambda_Within
res1$pars_varBetween1 <- diag(res1$Bm)
res1$pars_varBetween2 <- diag(res1$Wm)
res1$pars_varWithin <- diag(res1$ubar)
return(res1)
}
#################################################################
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE_NMI_inference_parameters.R
|
## File Name: BIFIE_NMIcombine_results.R
## File Version: 0.09
BIFIE_NMIcombine_results <- function(results, Nimp_NMI, package="stats")
{
if (package=="stats"){
fun_coef <- coef
fun_vcov <- vcov
}
if (package=="lavaan"){
fun_coef <- BIFIE_lavaan_coef
fun_vcov <- BIFIE_lavaan_vcov
}
#- estimates
qhat <- BIFIE_NMIcombine_results_extract_parameters(results=results,
fun=fun_coef, Nimp_NMI=Nimp_NMI)
#- variance matrices
u <- BIFIE_NMIcombine_results_extract_parameters(results=results,
fun=fun_vcov, Nimp_NMI=Nimp_NMI)
#- inference
stat <- miceadds::NMIcombine(qhat=qhat, u=u)
return(stat)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE_NMIcombine_results.R
|
## File Name: BIFIE_NMIcombine_results_extract_parameters.R
## File Version: 0.03
BIFIE_NMIcombine_results_extract_parameters <- function(results, fun, Nimp_NMI,
loop_within=TRUE)
{
u <- lapply(results, FUN=function(res){ fun(res) } )
res <- miceadds::List2nestedList(List=u, N_between=Nimp_NMI[1],
N_within=Nimp_NMI[2], loop_within=loop_within)
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE_NMIcombine_results_extract_parameters.R
|
## File Name: BIFIE_by_helper_pureR.R
## File Version: 0.17
############################################################
BIFIE_by_helper_pureR <- function(
group_values, userfct, datalistM,
N, vars_index, wgt_, wgtrep, Nimp, RR, fayfac,
group_index, userparnames)
{
G <- length(group_values)
h1 <- do.call( userfct, list( "X"=datalistM[1:N, vars_index], "w"=wgt_ ) )
NP <- length(h1)
parsM <- matrix( NA, nrow=NP*G, ncol=Nimp )
parsrepM <- matrix( NA, nrow=NP*G, ncol=Nimp*RR)
sumwgtM <- matrix( NA, nrow=G, ncol=Nimp )
ncasesM <- matrix( NA, nrow=G, ncol=Nimp )
cat("|")
s1 <- Sys.time()
for (ii in 1:Nimp){
# ii <- 1 # imputed dataset
cat("-"); utils::flush.console();
dat.ii <- datalistM[ 1:N + (ii-1)*N, ]
for (gg in 1:G){
ind.gg <- which( dat.ii[, group_index ]==group_values[gg] )
ind.gg <- stats::na.omit(ind.gg)
dat1 <- dat.ii[ ind.gg, vars_index ]
w1 <- wgt_[ ind.gg ]
sumwgtM[gg,ii] <- sum(w1)
ncasesM[gg,ii] <- length(w1)
wgtrep1 <- wgtrep[ ind.gg, ]
h1 <- do.call( userfct, list( "X"=dat1, "w"=w1 ) )
parsM[ 1:NP + (gg-1)*NP, ii ] <- h1
h1 <- sapply( 1:RR, FUN=function(rr){
do.call( userfct, list( "X"=dat1, "w"=wgtrep1[, rr] ) )
} )
parsrepM[ 1:NP + (gg-1)*NP, 1:RR + (ii-1)*RR ] <- h1
}
}
cat("|\n"); utils::flush.console()
# statistical inference
res0 <- bifie_comp_vcov_within( parsM, parsrepM, fayfac,
RR, Nimp )
u_diag <- res0$u_diag
eps <- 1E-15
qhat <- parsM
u_diag <- array( u_diag, dim=c(NP*G, Nimp) )
qbar <- rowMeans(qhat)
var_w <- rowMeans(u_diag)
var_b <- rowSums( ( parsM - qbar )^2 / ( Nimp - 1 + eps ) )
df <- rubin_calc_df2( B=var_b, W=var_w, Nimp, digits=2)
var_t <- ( 1 + 1 / Nimp) * var_b + var_w
fmi <- ( 1+1/Nimp) * var_b / ( var_t + eps )
parsL <- list( pars=qbar, pars_se=sqrt( var_t ),
pars_varWithin=var_w, pars_varBetween=var_b,
pars_fmi=fmi, df=df)
# arrange output
res <- list( parsM=parsM, parsrepM=parsrepM, userfct=userfct,
ncasesM=ncasesM, sumwgtM=sumwgtM, N=N, NP=NP,
WW=RR , parsL=parsL )
return(res)
}
############################################################
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE_by_helper_pureR.R
|
## File Name: BIFIE_create_pseudogroup.R
## File Version: 1.17
#**** multiple grouping helper functions
BIFIE_create_pseudogroup <- function( datalistM,
group, group_index, group_values )
{
GR <- length(group)
res0 <- list( "datalistM"=datalistM, "group_orig"=group,
"group"=group, "group_index"=group_index, "GR"=GR,
"group_values"=group_values)
#*** multiple groupings
if (GR>1){
group_values <- as.list( 1:GR )
for (gg in 1:GR){
t1 <- bifie_table( datalistM[, group_index[gg] ] )
group_values[[gg]] <- sort( as.numeric( paste( names(t1) ) ))
}
res0$group_values_orig <- group_values
datalistM2 <- datalistM[, group_index]
for (gg in 1:GR){
datalistM2[,gg] <- match( datalistM2[,gg], group_values[[gg]] )
}
# maxval_exp <- 3
maxval_exp <- max(ceiling(log10(unlist(lapply(group_values, length)))+1)) + 1
maxval <- 10^maxval_exp
res0$maxval <- maxval
pseudogroup <- datalistM2[,1]
for (gg in 2:GR){
pseudogroup <- pseudogroup + maxval^(gg-1) * datalistM2[,gg]
}
t1 <- bifie_table( pseudogroup )
group_values <- sort( as.numeric( paste( names(t1) ) ))
res0$group_values <- group_values
#**** group values recalculated in original values
group_values_recode <- matrix( NA, nrow=length(group_values), ncol=GR )
for (gg in 1:GR){
group_values_recode[,gg] <- group_values / maxval^(GR-gg)
}
for (gg in 1:GR){
group_values_recode[,gg] <- round( group_values_recode[,gg], 0 )
}
for (gg in 2:GR){
group_values_recode[,gg] <- group_values_recode[,gg] %% ( maxval )
}
group_values_recode <- group_values_recode[, seq(GR,1,-1) ]
for (gg in 1:GR){
h1 <- res0$group_values_orig[[gg]]
group_values_recode[,gg] <- h1[ group_values_recode[,gg] ]
}
res0$group_values_recode <- group_values_recode
res0$datalistM <- as.matrix( cbind( datalistM, pseudogroup ) )
res0$group_index <- ncol(datalistM)+1
res0$group <- "pseudogroup"
}
#--- output
return(res0)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE_create_pseudogroup.R
|
## File Name: BIFIE_data_nested_MI.R
## File Version: 0.07
###########################################################
# subfunction for handling nested multiple imputation
BIFIE_data_nested_MI <- function( data.list, NMI ){
Nimp_B <- length(data.list)
Nimp_W <- length(data.list[[1]])
Ntot <- Nimp_B * Nimp_W
data.list0 <- data.list
Nimp_NMI <- NULL
if (NMI){
data.list <- as.list( 1:Ntot)
hh <- 1
for (ii in 1:Nimp_B){
for (jj in 1:Nimp_W){
data.list[[hh]] <- data.list0[[ii]][[jj]]
hh <- hh + 1
}
}
Nimp_NMI <- c( Nimp_B, Nimp_W )
}
res <- list( data.list=data.list, Nimp_NMI=Nimp_NMI )
return(res)
}
###############################################################
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE_data_nested_MI.R
|
## File Name: BIFIE_data_pv_vars_create_datlist.R
## File Version: 0.131
BIFIE_data_pv_vars_create_datlist <- function(pvpre, pv_vars, jktype, data)
{
dfr <- NULL
VV <- length(pv_vars)
for (vv in 1:VV){
vv1 <- pv_vars[vv]
if (jktype !="RW_PISA"){
# ind.vv1 <- which( substring( colnames(data), 1, nchar(vv1) )==vv1 )
ind.vv1 <- grep(vv1, colnames(data))
} else {
varsel <- paste0( pvpre, vv1)
ind.vv1 <- which( colnames(data) %in% varsel )
}
Nimp <- length(ind.vv1)
dfr2 <- data.frame( "variable"=vv1, "var_index"=vv, "data_index"=ind.vv1,
"impdata_index"=1:Nimp )
dfr <- rbind( dfr, dfr2 )
}
sel_ind <- setdiff( 1:( ncol(data) ), dfr$data_index )
data0 <- data[, sel_ind ]
V0 <- ncol(data0)
newvars <- seq( V0+1, V0+VV )
datalist <- as.list( 1:Nimp )
for (ii in 1:Nimp ){
dat1 <- data.frame( data0, data[, dfr[ dfr$impdata_index==ii, "data_index" ] ] )
colnames(dat1)[ newvars ] <- pv_vars
datalist[[ii]] <- dat1
} # end imputations
#----- output
return(datalist)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE_data_pv_vars_create_datlist.R
|
## File Name: BIFIE_data_transform_process_formula.R
## File Version: 0.01
BIFIE_data_transform_process_formula <- function(transform.formula)
{
t1 <- stats::terms(transform.formula)
t2 <- attr(t1, "term.labels")
transform.formula <- stats::as.formula( paste0( "~ 0 + ", paste0( t2, collapse=" + ") ) )
return(transform.formula)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE_data_transform_process_formula.R
|
## File Name: BIFIE_lavaan_coef.R
## File Version: 0.12
BIFIE_lavaan_coef <- function(object, ...)
{
requireNamespace("lavaan")
lavaan_coef <- methods::getMethod("coef", "lavaan")
est <- lavaan_coef(object, ...)
return(est)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE_lavaan_coef.R
|
## File Name: BIFIE_lavaan_fitMeasures.R
## File Version: 0.03
BIFIE_lavaan_fitMeasures <- function(object, fit.measures)
{
requireNamespace("lavaan")
res <- lavaan::fitMeasures(object=object, fit.measures=fit.measures)
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE_lavaan_fitMeasures.R
|
## File Name: BIFIE_lavaan_lavInspect.R
## File Version: 0.02
BIFIE_lavaan_lavInspect <- function(object, what, ...)
{
requireNamespace("lavaan")
res <- lavaan::lavInspect(object=object, what=what, ...)
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE_lavaan_lavInspect.R
|
## File Name: BIFIE_lavaan_summary.R
## File Version: 0.02
BIFIE_lavaan_summary <- function(object)
{
requireNamespace("lavaan")
lavaan_summary <- methods::getMethod("summary","lavaan")
lavaan_summary(object)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE_lavaan_summary.R
|
## File Name: BIFIE_lavaan_survey_NMIcombine.R
## File Version: 0.03
BIFIE_lavaan_survey_NMIcombine <- function(results, variances, Nimp_NMI)
{
qhat <- miceadds::List2nestedList(List=results, N_between=Nimp_NMI[1],
N_within=Nimp_NMI[2], loop_within=TRUE)
u <- miceadds::List2nestedList(List=variances, N_between=Nimp_NMI[1],
N_within=Nimp_NMI[2], loop_within=TRUE)
#- inference
inf_res <- miceadds::NMIcombine(qhat=qhat, u=u)
inf_res$coefficients <- inf_res$qbar
inf_res$variance <- inf_res$Tm
return(inf_res)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE_lavaan_survey_NMIcombine.R
|
## File Name: BIFIE_lavaan_survey_combine_fit_measures.R
## File Version: 0.12
BIFIE_lavaan_survey_combine_fit_measures <- function(fitstat, Nimp)
{
fitstat1 <- 0
for (ii in 1:Nimp){
fitstat1 <- fitstat1 + fitstat[[ii]]
}
fitstat <- fitstat1 / Nimp
return(fitstat)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE_lavaan_survey_combine_fit_measures.R
|
## File Name: BIFIE_lavaan_survey_combine_partable.R
## File Version: 0.07
BIFIE_lavaan_survey_combine_partable <- function(partable, Nimp, inf_res)
{
partable0 <- partable[[1]]
if (Nimp>1){
for (ii in 2L:Nimp){
partable_ii <- partable[[ii]]
partable0$est <- partable0$est + partable_ii$est
}
}
partable0$est <- partable0$est / Nimp
partable <- partable0
# include results of statistical inference
ind_free <- which(partable$free>0)
partable$est[ ind_free ] <- as.vector(inf_res$coefficients)
partable$se[ ind_free ] <- sqrt(diag(as.matrix(inf_res$variance)))
return(partable)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE_lavaan_survey_combine_partable.R
|
## File Name: BIFIE_lavaan_survey_define_fit_measures.R
## File Version: 0.05
BIFIE_lavaan_survey_define_fit_measures <- function(fit.measures)
{
if ( is.null(fit.measures) ){
fit.measures <- c("npar","chisq", "df",
"pvalue", "baseline.chisq", "baseline.df", "baseline.pvalue",
"cfi","tli", "nnfi","rfi","nfi","pnfi","ifi","rni",
"rmsea","rmr","rmr_nomean","srmr","srmr_bentler",
"srmr_bentler_nomean","crmr","crmr_nomean","srmr_mplus",
"srmr_mplus_nomean","gfi","agfi","pgfi","mfi","ecvi")
}
return(fit.measures)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE_lavaan_survey_define_fit_measures.R
|
## File Name: BIFIE_lavaan_survey_define_lavaan_function.R
## File Version: 0.04
BIFIE_lavaan_survey_define_lavaan_function <- function(lavaan_fun)
{
requireNamespace("lavaan")
if (lavaan_fun=="sem"){ lav_fun <- lavaan::sem }
if (lavaan_fun=="cfa"){ lav_fun <- lavaan::cfa }
if (lavaan_fun=="lavaan"){ lav_fun <- lavaan::lavaan }
if (lavaan_fun=="growth"){ lav_fun <- lavaan::growth }
return(lav_fun)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE_lavaan_survey_define_lavaan_function.R
|
## File Name: BIFIE_lavaan_survey_define_variables.R
## File Version: 0.04
BIFIE_lavaan_survey_define_variables <- function(lavmodel, svyrepdes)
{
requireNamespace("lavaan")
res <- lavaan::lavaanify(model=lavmodel)
variables0 <- paste(svyrepdes$variables$variable)
variables <- intersect( variables0, unique( c( res$lhs, res$rhs) ) )
return(variables)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE_lavaan_survey_define_variables.R
|
## File Name: BIFIE_lavaan_survey_extract_dataset.R
## File Version: 0.091
BIFIE_lavaan_survey_extract_dataset <- function(svyrepdes, ii, variables,
svyrepdes0=NULL, datalist=NULL)
{
if ( inherits(svyrepdes,"svyimputationList") ){
svyrepdes0 <- svyrepdes$designs[[ii]]
}
if ( inherits(svyrepdes,"BIFIEdata") ){
use_datalist <- (ii>1) & ( ! is.null(datalist) )
if (! use_datalist){
svyrepdes0 <- BIFIEdata2svrepdesign(bifieobj=svyrepdes, varnames=variables,
impdata.index=ii)
} else {
svyrepdes0$variables <- datalist[[ii]]
}
}
return(svyrepdes0)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE_lavaan_survey_extract_dataset.R
|
## File Name: BIFIE_lavaan_survey_lavaan_survey.R
## File Version: 0.078
BIFIE_lavaan_survey_lavaan_survey <- function(lavaan.fit, survey.design, ...)
{
args <- c(as.list(environment()), list(...))
do.call(what=requireNamespace, args=list(package="lavaan.survey"))
res <- do.call(what="lavaan.survey", args=args)
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE_lavaan_survey_lavaan_survey.R
|
## File Name: BIFIE_lavaan_vcov.R
## File Version: 0.05
BIFIE_lavaan_vcov <- function(object, ...)
{
requireNamespace("lavaan")
# res <- BIFIE_lavaan_lavInspect(object=object, what="vcov")
# res <- as.matrix(res)
lavaan_vcov <- methods::getMethod("vcov", "lavaan")
vcov1 <- lavaan_vcov(object, ...)
return(vcov1)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE_lavaan_vcov.R
|
## File Name: BIFIE_mitools_MIcombine.R
## File Version: 0.02
BIFIE_mitools_MIcombine <- function(...)
{
requireNamespace("mitools")
res <- mitools::MIcombine(...)
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE_mitools_MIcombine.R
|
## File Name: BIFIE_multiple_groupings_helper.R
## File Version: 0.14
# multiple grouping helper functions
BIFIE_create_pseudogroup <- function( datalistM, group, group_index, group_values )
{
GR <- length(group)
res0 <- list( "datalistM"=datalistM, "group_orig"=group,
"group"=group, "group_index"=group_index,
"GR"=GR, "group_values"=group_values)
#****************
#*** multiple groupings
if (GR>1){
group_values <- as.list( 1:GR )
for (gg in 1:GR){
t1 <- bifie_table( datalistM[, group_index[gg] ] )
group_values[[gg]] <- sort( as.numeric( paste( names(t1) ) ))
}
res0$group_values_orig <- group_values
datalistM2 <- datalistM[, group_index]
for (gg in 1:GR){
datalistM2[,gg] <- match( datalistM2[,gg], group_values[[gg]] )
}
maxval_exp <- 3
maxval <- 10^maxval_exp
res0$maxval <- maxval
pseudogroup <- datalistM2[,1]
for (gg in 2:GR){
pseudogroup <- pseudogroup + maxval^(gg-1) * datalistM2[,gg]
}
t1 <- bifie_table( pseudogroup )
group_values <- sort( as.numeric( paste( names(t1) ) ))
res0$group_values <- group_values
#**** group values recalculated in original values
group_values_recode <- matrix( NA, nrow=length(group_values), ncol=GR )
for (gg in 1:GR){
group_values_recode[,gg] <- group_values / maxval^(GR-gg)
}
for (gg in 1:GR){
group_values_recode[,gg] <- round( group_values_recode[,gg], 0 )
}
for (gg in 2:GR){
group_values_recode[,gg] <- group_values_recode[,gg] %% ( maxval )
}
group_values_recode <- group_values_recode[, seq(GR,1,-1) ]
for (gg in 1:GR){
h1 <- res0$group_values_orig[[gg]]
group_values_recode[,gg] <- h1[ group_values_recode[,gg] ]
}
res0$group_values_recode <- group_values_recode
res0$datalistM <- as.matrix( cbind( datalistM, pseudogroup ) )
res0$group_index <- ncol(datalistM)+1
res0$group <- "pseudogroup"
}
return(res0)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE_multiple_groupings_helper.R
|
## File Name: BIFIE_nmi_error_message.R
## File Version: 0.05
BIFIE_nmi_error_message <- function(fun, NMI)
{
if (NMI){
n1 <- paste0("'", fun, "' cannot currently handle nested multiply imputed datasets.\n")
stop(n1)
}
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE_nmi_error_message.R
|
## File Name: BIFIE_object_size.R
## File Version: 0.08
##################################################
# output object sizes in MB and GB
BIFIE_object_size <- function( x1 )
{
x1 <- utils::object.size(x1)
vals <- c( x1, as.numeric(x1 / 1024^2),
as.numeric(x1 / 1024^3) )
names(vals) <- c("B", "MB", "GB" )
res <- list( "value"=vals )
res$value_string <- paste0( round( vals[2], 3 ),
" MB | ", round( vals[3], 5 ), " GB" )
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE_object_size.R
|
## File Name: BIFIE_pathmodel_summary_print_model_specification.R
## File Version: 0.09
BIFIE_pathmodel_summary_print_model_specification <- function(object, digits)
{
# print specified model
cat("Syntax for path model \n")
cat(object$lavaan.model, "\n")
# print fixed reliabilities
obji <- object$reliability
if (!is.null(obji)){
cat("Fixed reliabilities\n\n")
print( round(obji, digits))
cat("\n")
}
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE_pathmodel_summary_print_model_specification.R
|
## File Name: BIFIE_print_package_description.R
## File Version: 0.01
BIFIE_print_package_description <- function(pack="BIFIEsurvey")
{
d1 <- packageDescription(pack)
cat( paste( d1$Package, " ", d1$Version, " (", d1$Date, ")", sep=""), "\n" )
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE_print_package_description.R
|
## File Name: BIFIE_table_multiple_groupings.R
## File Version: 0.14
#- reidentify multiple grouping
BIFIE_table_multiple_groupings <- function( dfr, res00 )
{
GR <- res00$GR
if (GR>1){
ind1 <- which( colnames(dfr)=="groupvar" )
ind2 <- which( colnames(dfr)=="groupval" )
N2 <- ncol(dfr)
dfr1 <- dfr[, seq( 1, ind1 - 1 ), drop=FALSE ]
for (gg in 1:GR){
dfr1[, paste0("groupvar", gg ) ] <- paste(res00$group_orig[gg])
ind <- match( dfr$groupval, res00$group_values)
dfr1[, paste0("groupval", gg ) ] <- res00$group_values_recode[ ind,gg]
}
dfr <- cbind( dfr1, dfr[, seq( ind2 + 1, N2 ), drop=FALSE] )
}
return(dfr)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE_table_multiple_groupings.R
|
## File Name: BIFIE_waldtest_summary_print_test_statistics.R
## File Version: 0.051
BIFIE_waldtest_summary_print_test_statistics <- function(object, digits,
value_name="stat.D")
{
if ( ! object$NMI ){ cat("D1 and D2 Statistic for Wald Test \n\n") }
if ( object$NMI ){ cat("D1 Statistic for Wald Test \n\n") }
obji <- object[[ value_name ]]
print_object_summary( obji, digits=digits )
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIE_waldtest_summary_print_test_statistics.R
|
## File Name: BIFIEdata.select.R
## File Version: 1.09
# wrapper function for subfunctions BIFIE.data.select and
# BIFIE.cdata.select
BIFIEdata.select <- function( bifieobj, varnames=NULL, impdata.index=NULL )
{
cdata <- bifieobj$cdata
if ( cdata ){
bifieobj <- BIFIE.cdata.select( bifieobj=bifieobj,
varnames=varnames, impdata.index=impdata.index )
}
if ( ! cdata ){
bifieobj <- BIFIE.data.select( bifieobj=bifieobj,
varnames=varnames, impdata.index=impdata.index )
}
return(bifieobj)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIEdata.select.R
|
## File Name: BIFIEdata2svrepdesign.R
## File Version: 0.30
BIFIEdata2svrepdesign <- function(bifieobj, varnames=NULL,
impdata.index=NULL )
{
requireNamespace("mitools")
requireNamespace("survey")
CALL <- match.call()
Nimp <- bifieobj$Nimp
weights <- bifieobj$wgt
repweights <- bifieobj$wgtrep
RR <- bifieobj$RR
scale <- bifieobj$fayfac
rscales <- rep(1,RR)
if (bifieobj$NMI){
mess <- paste0( "Nested multiply imputed datasets cannot be converted \n",
" into objects for the survey package.\n")
stop(mess)
}
#**** create datasets
if (Nimp==1){
data <- as.data.frame(bifieobj$dat1)
if (! is.null(varnames)){
data <- data[,varnames, drop=FALSE]
}
}
if (Nimp>1){
data <- BIFIE.BIFIEdata2datalist(bifieobj=bifieobj, varnames=varnames,
impdata.index=impdata.index, as_data_frame=FALSE)
Nimp <- length(data)
if (Nimp==1){
data <- data[[1]]
} else {
data <- mitools::imputationList(datasets=data)
}
}
#*** adjust scale factor in case of finite sampling correction
if ( length(scale) > 1){
rscales <- scale
scale <- 1
}
#*** create svrepdesign object
svydes <- survey::svrepdesign(data=data, weights=weights, repweights=repweights,
type="other", scale=scale, rscales=rscales, mse=TRUE )
svydes$call <- CALL
return(svydes)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIEdata2svrepdesign.R
|
## File Name: BIFIEsurvey_print_term_formula.R
## File Version: 0.02
BIFIEsurvey_print_term_formula <- function(formula)
{
res <- paste0( attr( stats::terms(formula), "term.labels" ), collapse=" " )
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/BIFIEsurvey_print_term_formula.R
|
## File Name: RcppExports.R
## File Version: 3.005019
# Generated by using Rcpp::compileAttributes() -> do not edit by hand
# Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393
bifiesurvey_rcpp_jackknife_timss <- function(wgt, jkzone, jkrep, RR, jkfac, prbar) {
.Call('_BIFIEsurvey_bifiesurvey_rcpp_jackknife_timss', PACKAGE='BIFIEsurvey', wgt, jkzone, jkrep, RR, jkfac, prbar)
}
bifiesurvey_rcpp_bootstrap <- function(cumwgt, rand_wgt) {
.Call('_BIFIEsurvey_bifiesurvey_rcpp_bootstrap', PACKAGE='BIFIEsurvey', cumwgt, rand_wgt)
}
bifiesurvey_rcpp_bifiedata2bifiecdata <- function(datalistM, Nimp) {
.Call('_BIFIEsurvey_bifiesurvey_rcpp_bifiedata2bifiecdata', PACKAGE='BIFIEsurvey', datalistM, Nimp)
}
bifiesurvey_rcpp_bifiecdata2bifiedata <- function(datalistM_ind, datalistM_imputed, Nimp, dat1, datalistM_impindex) {
.Call('_BIFIEsurvey_bifiesurvey_rcpp_bifiecdata2bifiedata', PACKAGE='BIFIEsurvey', datalistM_ind, datalistM_imputed, Nimp, dat1, datalistM_impindex)
}
bifiesurvey_rcpp_bifiedata_stepwise <- function(dat1, dat_ind, Nmiss) {
.Call('_BIFIEsurvey_bifiesurvey_rcpp_bifiedata_stepwise', PACKAGE='BIFIEsurvey', dat1, dat_ind, Nmiss)
}
bifiesurvey_rcpp_linreg <- function(datalist, wgt1, wgtrep, dep_index, pre_index, fayfac, NI, group_index1, group_values) {
.Call('_BIFIEsurvey_bifiesurvey_rcpp_linreg', PACKAGE='BIFIEsurvey', datalist, wgt1, wgtrep, dep_index, pre_index, fayfac, NI, group_index1, group_values)
}
bifiesurvey_rcpp_logistreg <- function(datalist, wgt1, wgtrep, dep_index, pre_index, fayfac, NI, group_index1, group_values, eps, maxiter) {
.Call('_BIFIEsurvey_bifiesurvey_rcpp_logistreg', PACKAGE='BIFIEsurvey', datalist, wgt1, wgtrep, dep_index, pre_index, fayfac, NI, group_index1, group_values, eps, maxiter)
}
univar_multiple_V2group <- function(datalist, wgt1, wgtrep, vars_index, fayfac, NI, group_index1, group_values) {
.Call('_BIFIEsurvey_univar_multiple_V2group', PACKAGE='BIFIEsurvey', datalist, wgt1, wgtrep, vars_index, fayfac, NI, group_index1, group_values)
}
bifie_freq <- function(datalist, wgt1, wgtrep, vars_index, fayfac, NI, group_index1, group_values, vars_values, vars_values_numb) {
.Call('_BIFIEsurvey_bifie_freq', PACKAGE='BIFIEsurvey', datalist, wgt1, wgtrep, vars_index, fayfac, NI, group_index1, group_values, vars_values, vars_values_numb)
}
bifie_correl <- function(datalist, wgt1, wgtrep, vars_index, fayfac, NI, group_index1, group_values) {
.Call('_BIFIEsurvey_bifie_correl', PACKAGE='BIFIEsurvey', datalist, wgt1, wgtrep, vars_index, fayfac, NI, group_index1, group_values)
}
bifie_comp_vcov_within <- function(parsM, parsrepM, fayfac, RR, Nimp) {
.Call('_BIFIEsurvey_bifie_comp_vcov_within', PACKAGE='BIFIEsurvey', parsM, parsrepM, fayfac, RR, Nimp)
}
bifie_comp_vcov <- function(parsM, parsrepM, Cdes, rdes, Ccols, fayfac) {
.Call('_BIFIEsurvey_bifie_comp_vcov', PACKAGE='BIFIEsurvey', parsM, parsrepM, Cdes, rdes, Ccols, fayfac)
}
bifie_test_univar <- function(mean1M, sd1M, sumweightM, GG, group_values, mean1repM, sd1repM, sumweightrepM, fayfac) {
.Call('_BIFIEsurvey_bifie_test_univar', PACKAGE='BIFIEsurvey', mean1M, sd1M, sumweightM, GG, group_values, mean1repM, sd1repM, sumweightrepM, fayfac)
}
bifie_crosstab <- function(datalist, wgt1, wgtrep, vars_values1, vars_index1, vars_values2, vars_index2, fayfac, NI, group_index1, group_values) {
.Call('_BIFIEsurvey_bifie_crosstab', PACKAGE='BIFIEsurvey', datalist, wgt1, wgtrep, vars_values1, vars_index1, vars_values2, vars_index2, fayfac, NI, group_index1, group_values)
}
bifie_by <- function(datalist, wgt1, wgtrep, vars_index, fayfac, NI, group_index1, group_values, userfct) {
.Call('_BIFIEsurvey_bifie_by', PACKAGE='BIFIEsurvey', datalist, wgt1, wgtrep, vars_index, fayfac, NI, group_index1, group_values, userfct)
}
bifie_hist <- function(datalist, wgt1, wgtrep, vars_index, fayfac, NI, group_index1, group_values, breaks) {
.Call('_BIFIEsurvey_bifie_hist', PACKAGE='BIFIEsurvey', datalist, wgt1, wgtrep, vars_index, fayfac, NI, group_index1, group_values, breaks)
}
bifie_ecdf <- function(datalist, wgt1, wgtrep, vars_index, fayfac, NI, group_index1, group_values, breaks, quanttype, maxval) {
.Call('_BIFIEsurvey_bifie_ecdf', PACKAGE='BIFIEsurvey', datalist, wgt1, wgtrep, vars_index, fayfac, NI, group_index1, group_values, breaks, quanttype, maxval)
}
bifie_fasttable <- function(datavec) {
.Call('_BIFIEsurvey_bifie_fasttable', PACKAGE='BIFIEsurvey', datavec)
}
bifie_table1_character <- function(datavec) {
.Call('_BIFIEsurvey_bifie_table1_character', PACKAGE='BIFIEsurvey', datavec)
}
bifie_mla2 <- function(X_list, Z_list, y_list, wgttot, wgtlev2, wgtlev1, globconv, maxiter, group, group_values, cluster, wgtrep, Nimp, fayfac, recov_constraint, is_rcov_constraint) {
.Call('_BIFIEsurvey_bifie_mla2', PACKAGE='BIFIEsurvey', X_list, Z_list, y_list, wgttot, wgtlev2, wgtlev1, globconv, maxiter, group, group_values, cluster, wgtrep, Nimp, fayfac, recov_constraint, is_rcov_constraint)
}
bifiesurvey_rcpp_replication_variance <- function(pars, pars_repl, fay_factor) {
.Call('_BIFIEsurvey_bifiesurvey_rcpp_replication_variance', PACKAGE='BIFIEsurvey', pars, pars_repl, fay_factor)
}
bifiesurvey_rcpp_rubin_rules <- function(estimates, variances) {
.Call('_BIFIEsurvey_bifiesurvey_rcpp_rubin_rules', PACKAGE='BIFIEsurvey', estimates, variances)
}
bifiesurvey_rcpp_pathmodel <- function(datalist, wgt1, wgtrep, vars_index, fayfac, NI, group_index1, group_values, L, L_row_index, NL, E, R, R_row_index, coeff_index, NP0, unreliability) {
.Call('_BIFIEsurvey_bifiesurvey_rcpp_pathmodel', PACKAGE='BIFIEsurvey', datalist, wgt1, wgtrep, vars_index, fayfac, NI, group_index1, group_values, L, L_row_index, NL, E, R, R_row_index, coeff_index, NP0, unreliability)
}
bifiesurvey_rcpp_wald_test <- function(parsM, parsrepM, Cdes, rdes, Ccols, fayfac) {
.Call('_BIFIEsurvey_bifiesurvey_rcpp_wald_test', PACKAGE='BIFIEsurvey', parsM, parsrepM, Cdes, rdes, Ccols, fayfac)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/RcppExports.R
|
## File Name: BIFIE_data_select_pv_vars.R
## File Version: 0.07
BIFIE_data_select_pv_vars <- function(pvpre, cn_data)
{
# select variables with plausible values
nc1 <- nchar( pvpre[1] )
pv_vars <- which( substring( cn_data, 1, nc1 )==pvpre[1] )
#-- deselect all duplicated variables
pv_elim <- NULL
LP <- length(pvpre)
for (pp in 2:LP){
pvpre_pp <- pvpre[pp]
pv1 <- which( substring( cn_data, 1, nchar(pvpre_pp) )==pvpre_pp )
pv_elim <- c( pv_elim, pv1 )
}
pv_vars <- setdiff(pv_vars, pv_elim)
pv_vars <- gsub( pvpre[1], "", cn_data[ pv_vars ] )
#--- output
return(pv_vars)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/bifie_data_select_pv_vars.R
|
## File Name: bifie_ecdf_postproc_output.R
## File Version: 0.11
bifie_ecdf_postproc_output <- function(res, group_values, breaks, VV, res00,
vars, group)
{
GG <- length(group_values)
BB <- length(breaks)
#--- output data frame containing distribution functions as columns
dfr <- as.data.frame( matrix( NA, nrow=BB, ncol=VV*GG+1 ) )
colnames(dfr)[1] <- "yval"
dfr[,1] <- breaks
dfr[,-1] <- matrix( res$ecdf, nrow=BB, ncol=VV*GG )
colnames(dfr)[-1] <- paste0( rep( vars, each=GG ),
"_", group, rep( group_values, VV ) )
GR <- res00$GR
if (GR>1){
group_orig <- res00$group_orig
group_values_recode <- res00$group_values_recode
rr <- 1
p1 <- paste0( group_orig[rr], group_values_recode[,rr] )
for (rr in 2:GR){
p1 <- paste0( p1, "_", group_orig[rr], group_values_recode[,rr] )
}
cn <- paste0( rep( vars, each=GG ), "_", rep( p1, VV ) )
colnames(dfr)[-1] <- cn
}
ecdf_ <- dfr
#--- data frame with statistics
stat <- NULL
ii <- 1
for (vv in 1:VV){
for (gg in 1:GG){
dfr1 <- data.frame( "var"=vars[vv], "groupvar"=group,
"groupval"=group_values[gg], "yval"=breaks, "quant"=dfr[,ii+1] )
ii <- ii + 1
stat <- rbind( stat, dfr1 )
}
}
#--- output
res <- list( ecdf_=ecdf_, stat=stat)
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/bifie_ecdf_postproc_output.R
|
## File Name: bifie_extend_list_length2.R
## File Version: 0.03
bifie_extend_list_length2 <- function(x)
{
N <- length(x)
if (N==1){
x <- list( x[[1]], x[[1]] )
}
return(x)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/bifie_extend_list_length2.R
|
## File Name: bifie_table.R
## File Version: 1.13
###########################################
# Rcpp version of R's table function
bifie_table <- function( vec, sort.names=FALSE )
{
datavec <- matrix( vec, ncol=1 )
if ( storage.mode(vec)=="character" ){
characters <- TRUE
} else {
characters <- FALSE
}
if ( ! characters ){
res <- bifie_fasttable( datavec )
res1 <- res$tableM[ 1:res$N_unique,, drop=FALSE]
tvec <- res1[,2]
names(tvec) <- res1[,1]
}
if ( characters ){
t1 <- bifie_table1_character( vec )
res <- t1$tableM
names(res) <- t1$table_names
if ( sort.names ){
tvec <- res[ sort( names(res) ) ]
} else { tvec <- res }
}
return(tvec)
}
###########################################
bifietable <- bifie_table
fasttable <- bifie_table
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/bifie_table.R
|
## File Name: cdata.wgtrep.R
## File Version: 0.05
############################################
# BIFIEcdata format for replicate weights
cdata.wgtrep <- function( wgtrep ){
N <- nrow(wgtrep)
RR <- ncol(wgtrep)
longwgtrep <- matrix( wgtrep, nrow=N*RR, ncol=1 )
unique_wgt <- sort( unique( longwgtrep ) )
indexwgtrep <- match( longwgtrep, unique_wgt )
indexwgtrep <- matrix( indexwgtrep, nrow=N, ncol=RR )
# list with compactly saved replicate weights
wgtrep_list <- list( "unique_wgt"=unique_wgt, "indexwgtrep"=indexwgtrep )
return(wgtrep_list)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/cdata.wgtrep.R
|
## File Name: clean_summary_table.R
## File Version: 0.10
clean_summary_table <- function( dfr, RR, se, Nimp )
{
#*** RR==0
if ( ( ! se ) & ( RR==0 ) ){
vars <- c("df", "cor_SE", "cor_fmi", "cor_VarMI",
"cor_VarRep", "cor_VarMI_St2", "cor_VarMI_St1",
"cor_fmi_St1", "cor_fmi_St2", "t", "p",
"cov_SE", "cov_fmi", "cov_VarMI", "cov_VarRep",
"cov_VarMI_St2", "cov_VarMI_St1",
"cov_fmi_St1", "cov_fmi_St2", "SE",
"Var_MI", "VarRep"
)
for (vv in vars){ dfr[,vv] <- NULL }
}
#**** Nimp==1
if ( Nimp==1 ){
vars <- c("cov_fmi", "cov_VarMI", "fmi", "VarMI")
for (vv in vars){
dfr[,vv] <- NULL
}
}
return(dfr)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/clean_summary_table.R
|
## File Name: coef.BIFIE.lavaan.survey.R
## File Version: 0.05
coef.BIFIE.lavaan.survey <- function(object, ...)
{
coef(object$lavfit, ...)
}
vcov.BIFIE.lavaan.survey <- function(object, ...)
{
BIFIE_lavaan_vcov(object$lavfit, ...)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/coef.BIFIE.lavaan.survey.R
|
## File Name: coef.BIFIE.survey.R
## File Version: 0.01
coef.BIFIE.survey <- function(object, ...)
{
coef(object$stat, ...)
}
vcov.BIFIE.survey <- function(object, ...)
{
vcov(object$stat, ...)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/coef.BIFIE.survey.R
|
## File Name: coef.BIFIEsurvey.R
## File Version: 0.11
###########################################
# general BIFIE method coef
coef.BIFIEsurvey <- function( object, type=NULL, ... ){
parsres <- extract.replicated.pars( BIFIE.method=object, type=type )
pars <- parsres$parsM
pars <- rowMeans(pars)
names(pars) <- parsres$parnames
return(pars)
}
###############################################
# BIFIE.correl
coef.BIFIE.correl <- function( object, type=NULL, ... ){
pars <- coef.BIFIEsurvey( object=object, type=type )
return(pars)
}
# further BIFIE functions
coef.BIFIE.by <- function( object, ... ){
pars <- coef.BIFIEsurvey( object=object, type=NULL )
return(pars)
}
coef.BIFIE.crosstab <- function( object, ... ){
pars <- coef.BIFIEsurvey( object=object, type=NULL )
return(pars)
}
coef.BIFIE.derivedParameters <- function( object, ... ){
pars <- coef.BIFIEsurvey( object=object, type=NULL )
return(pars)
}
coef.BIFIE.freq <- function( object, ... ){
pars <- coef.BIFIEsurvey( object=object, type=NULL )
return(pars)
}
coef.BIFIE.linreg <- function( object, ... ){
pars <- coef.BIFIEsurvey( object=object, type=NULL )
return(pars)
}
coef.BIFIE.logistreg <- function( object, ... ){
pars <- coef.BIFIEsurvey( object=object, type=NULL )
return(pars)
}
coef.BIFIE.univar <- function( object, ... ){
pars <- coef.BIFIEsurvey( object=object, type=NULL )
return(pars)
}
coef.BIFIE.twolevelreg <- function( object, ... )
{
if (object$se){
pars <- coef.BIFIEsurvey( object=object, type=NULL )
} else {
pars <- coef(object$micombs)
}
return(pars)
}
coef.BIFIE.pathmodel <- function( object, ... )
{
pars <- coef.BIFIEsurvey( object=object, type=NULL )
return(pars)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/coef.BIFIEsurvey.R
|
## File Name: create_function_name.R
## File Version: 0.06
create_function_name <- function(pack, fun)
{
requireNamespace(pack)
lav_fun_00 <- NULL
fn <- paste0(pack, paste0(rep(":",2), collapse=""), fun)
r_op <- paste0("lav_fun_00 <- ", fn)
eval(parse(text=r_op), envir=parent.frame())
return(lav_fun_00)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/create_function_name.R
|
## File Name: create_summary_table.R
## File Version: 0.12
##################################################################
create_summary_table <- function( res_pars, parsM, parsrepM, dfr, BIFIEobj)
{
dfr$est <- res_pars$pars
dfr$SE <- res_pars$pars_se
dfr$t <- round( dfr$est / dfr$SE, 2 )
dfr$df <- rubin_calc_df( res_pars, BIFIEobj$Nimp )
dfr$p <- stats::pt( - abs( dfr$t ), df=dfr$df) * 2
# dfr$p <- pnorm( - abs( dfr$t ) ) * 2
dfr$fmi <- res_pars$pars_fmi
dfr$VarMI <- res_pars$pars_varBetween
dfr$VarRep <- res_pars$pars_varWithin
#*****
# inference nested multiple imputation
if ( BIFIEobj$NMI ){
res1 <- BIFIE_NMI_inference_parameters( parsM=parsM, parsrepM=parsrepM,
fayfac=BIFIEobj$fayfac, RR=BIFIEobj$RR, Nimp=BIFIEobj$Nimp,
Nimp_NMI=BIFIEobj$Nimp_NMI, comp_cov=FALSE )
dfr$fmi <- dfr$cov_VarMI <- NULL
dfr$est <- res1$pars
dfr$SE <- res1$pars_se
dfr$t <- round( dfr$est / dfr$SE, 2 )
dfr$df <- res1$df
dfr$p <- stats::pt( - abs( dfr$t ), df=dfr$df) * 2
dfr$fmi <- res1$pars_fmi
dfr$fmi_St1 <- res1$pars_fmiB
dfr$fmi_St2 <- res1$pars_fmiW
dfr$VarMI_St1 <- res1$pars_varBetween1
dfr$VarMI_St2 <- res1$pars_varBetween2
dfr$VarRep <- res1$pars_varWithin
dfr$VarMI <- res1$pars_varBetween1 + res1$pars_varBetween2
}
return(dfr)
}
##################################################################
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/create_summary_table.R
|
## File Name: extract.replicated.pars.R
## File Version: 0.163
#--- extract replicated parameters for BIFIE method
extract.replicated.pars <- function( BIFIE.method, type=NULL )
{
parsM <- parsrepM <- NULL
res1 <- BIFIE.method
#**** linear regression
if ( inherits( BIFIE.method,"BIFIE.linreg") ){
# parameters in every imputed dataset
parsM <- res1$output$regrcoefM
# replicated parameters
parsrepM <- res1$output$regrcoefrepM
}
#**** path model
if ( inherits( BIFIE.method,"BIFIE.pathmodel")){
# parameters in every imputed dataset
parsM <- res1$output$parsM
# replicated parameters
parsrepM <- res1$output$parsrepM
}
#**** correlation
if ( inherits( BIFIE.method,"BIFIE.correl") ){
parsM <- res1$output$cor1M
parsrepM <- res1$output$cor1repM
if ( ! is.null(type) ){
if ( type=="cov"){
parsM <- res1$output$cov1M
parsrepM <- res1$output$cov1repM
}
}
}
#**** frequencies
if ( inherits( BIFIE.method,"BIFIE.freq")){
parsM <- res1$output$perc2M
parsrepM <- res1$output$perc2repM
}
#**** univar
if ( inherits( BIFIE.method,"BIFIE.univar")){
parsM <- res1$output$mean1M
parsrepM <- res1$output$mean1repM
}
#**** crosstab
if ( inherits( BIFIE.method,"BIFIE.crosstab")){
parsM <- res1$output$ctparsM
parsrepM <- res1$output$ctparsrepM
}
#**** logistreg
if ( inherits( BIFIE.method,"BIFIE.logistreg")){
parsM <- res1$output$regrcoefM
parsrepM <- res1$output$regrcoefrepM
}
#**** BIFIE.by
if ( inherits( BIFIE.method,"BIFIE.by")){
parsM <- res1$output$parsM
parsrepM <- res1$output$parsrepM
}
#**** BIFIE.derivedParameters
if ( inherits( BIFIE.method,"BIFIE.derivedParameters")){
parsM <- res1$parsM
parsrepM <- res1$parsrepM
}
#**** BIFIE.twolevelreg
if ( inherits( BIFIE.method,"BIFIE.twolevelreg") ){
parsM <- res1$output$parsM
parsrepM <- res1$output$parsrepM
}
#-- output
res <- list( parsM=parsM, parsrepM=parsrepM, parnames=res1$parnames)
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/extract.replicated.pars.R
|
## File Name: load.BIFIE.data.R
## File Version: 1.24
#*** load BIFIEdata objects when objects are saved as full BIFIEdata
#*** objects in one file
load.BIFIEdata <- function(filename, dir=getwd() )
{
d1 <- load( file=file.path(dir,filename) )
objname <- "bdat_temp"
cdata <- NULL
miceadds::Reval( paste0("cdata <- ", d1,"$cdata" ) , print.string=FALSE )
if (cdata){ # if cdata=TRUE
l1 <- paste0( d1, "$wgtrep <- matrix(",
d1,"$wgtreplist$unique_wgt[ ", d1, "$wgtreplist$indexwgtrep ],
nrow=", d1, "$N, ncol=", d1, "$RR ) ")
miceadds::Reval( l1, print.string=FALSE )
miceadds::Reval( paste0( d1, "$wgtreplist <- NULL" ), print.string=FALSE)
}
# save object in global environment
eval(parse(text=paste(objname, "<- ", d1)))
eval( parse(text=paste0( "return( ", objname, ")" ) ) )
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/load.BIFIE.data.R
|
## File Name: load.BIFIEdata.files.R
## File Version: 3.17
#****** loading files for conversion into BIFIE data objects
load.BIFIEdata.files <- function( files.imp, wgt, file.wgtrep, file.ind=NULL, type="Rdata",
varnames=NULL, cdata=TRUE, dir=getwd(), ... )
{
Nimp <- length(files.imp)
# handle cases in which no weights are defined?
#**** no indicator dataset
if ( is.null(file.ind) ){
#**********
# read imputed datasets
datalist <- list(1:Nimp)
for (ii in 1:Nimp){
# cat(paste0( "- Read ", files.imp[[ii]], "\n") )
# utils::flush.console()
load_BIFIEdata_files_cat_print_file_name( file=files.imp[[ii]] )
dat1 <- miceadds::load.data( file=files.imp[[ii]], path=dir, type=type, ... )
if (ii==1){ wgt <- dat1[, wgt ] }
dat1 <- as.data.frame(dat1)
dat1 <- load_BIFIEdata_files_select_variables( dat=dat1, varnames=varnames )
dat1$one <- NULL
datalist[[ii]] <- dat1
}
#**************
# read replicate weights
load_BIFIEdata_files_cat_print_file_name( file=file.wgtrep )
wgtrep <- miceadds::load.data( file=file.wgtrep, type=type, path=dir, ...)
#****************************
# create BIFIEdata object
bifieobj <- BIFIE.data( data.list=datalist, wgt=wgt, wgtrep=wgtrep, cdata=cdata )
}
#**** with indicator dataset
if ( ! is.null( file.ind ) ){
#--- read indicator dataset
load_BIFIEdata_files_cat_print_file_name( file=file.ind )
dat_ind <- miceadds::load.data( file=file.ind, type=type, path=dir, ...)
if ( is.null(varnames) ){
varnames <- setdiff( colnames(dat_ind ), "one" )
}
dat_ind <- load_BIFIEdata_files_select_variables( dat=dat_ind, varnames=varnames )
dat_ind <- as.matrix( dat_ind )
# add column 1 for "one"
dat_ind <- cbind( dat_ind, 1 )
colnames(dat_ind) <- c( varnames, "one")
#************************
# Read first imputed dataset
ii <- 1
load_BIFIEdata_files_cat_print_file_name( file=files.imp[[ii]] )
dat1 <- miceadds::load.data( file=files.imp[[ii]], path=dir, type=type, ... )
dat1 <- load_BIFIEdata_files_select_variables( dat=dat1, varnames=varnames )
datalist <- list( dat1 )
#**************
# read replicate weights
load_BIFIEdata_files_cat_print_file_name( file=file.wgtrep )
wgtrep <- miceadds::load.data( file=file.wgtrep, type=type, path=dir, ...)
#***************
# create initial BIFIEdata object
bifieobj <- BIFIE.data( data.list=datalist, wgt=wgt, wgtrep=wgtrep, cdata=cdata )
bifieobj$datalistM_ind <- dat_ind
bifieobj$Nimp <- Nimp
Nmiss <- sum( 1 - dat_ind )
datalistM_imputed <- matrix( NA, nrow=Nmiss, Nimp)
res1 <- bifiesurvey_rcpp_bifiedata_stepwise( as.matrix(dat1), dat_ind, Nmiss )$datalistM_imputed
datalistM_imputed[,1] <- res1[,4]
datalistM_impindex <- res1[,2:3]
#----- read other imputed datasets
if (Nimp>1){
for (ii in 2:Nimp){
load_BIFIEdata_files_cat_print_file_name( file=files.imp[[ii]] )
dat1 <- miceadds::load.data( file=files.imp[[ii]], path=dir, type=type, ... )
dat1 <- load_BIFIEdata_files_select_variables( dat=dat1, varnames=varnames )
res1 <- bifiesurvey_rcpp_bifiedata_stepwise( as.matrix(dat1), dat_ind, Nmiss )$datalistM_imputed
datalistM_imputed[,ii] <- res1[,4]
datalistM_impindex <- rbind( datalistM_impindex, res1[,2:3] )
}
}
bifieobj$dat1 <- cbind( as.data.frame(dat1), "one"=1 )
bifieobj$datalistM_imputed <- datalistM_imputed
datalistM_imputed <- NULL
bifieobj$datalistM_impindex <- datalistM_impindex
} # end indicator data
#--- return BIFIE object
return(bifieobj)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/load.BIFIEdata.files.R
|
## File Name: load_BIFIEdata_files_cat_print_file_name.R
## File Version: 0.02
load_BIFIEdata_files_cat_print_file_name <- function( file )
{
cat(paste0( "- Read ", file, "\n") )
utils::flush.console()
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/load_BIFIEdata_files_cat_print_file_name.R
|
## File Name: load_BIFIEdata_files_select_variables.R
## File Version: 0.03
load_BIFIEdata_files_select_variables <- function( dat, varnames )
{
if ( ! is.null(varnames) ){
dat <- dat[, varnames ]
}
return(dat)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/load_BIFIEdata_files_select_variables.R
|
## File Name: print_object_summary.R
## File Version: 0.161
print_object_summary <- function( obji, digits)
{
V <- ncol(obji)
for (vv in 1L:V){
if ( is.numeric( obji[,vv] ) ){
obji[,vv] <- round( obji[,vv], digits=digits )
}
}
print( format(obji, scientific=FALSE), digits=digits )
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/print_object_summary.R
|
## File Name: rubin_calc_df.R
## File Version: 0.10
######################################################
# calculate degrees of freedom according to Rubin
rubin_calc_df <- function( res_pars, Nimp, indices=NULL, digits=2)
{
W <- res_pars$pars_varWithin
B <- res_pars$pars_varBetween
df <- rubin_calc_df2( B=B, W=W, Nimp=Nimp, indices=indices, digits=digits)
return(df)
}
######################################################
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/rubin_calc_df.R
|
## File Name: rubin_calc_df2.R
## File Version: 0.05
######################################################
rubin_calc_df2 <- function( B, W, Nimp, indices=NULL, digits=2)
{
if ( ! is.null(indices) ){
W <- W[indices]
B <- B[indices]
}
B <- B + W * 1E-15
df <- ( 1 + Nimp / ( Nimp + 1 ) * W / B )^2 * (Nimp - 1 )
df <- round( df, digits )
df <- ifelse( ( df > 1000 ) | ( Nimp==1 ), Inf, df )
return(df)
}
######################################################
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/rubin_calc_df2.R
|
## File Name: save.BIFIE.data.R
## File Version: 1.09
######################################################################
# save BIFIEdata objects
save.BIFIEdata <- function( BIFIEdata, name.BIFIEdata, cdata=TRUE, varnames=NULL )
{
make.cdata <- cdata
if ( BIFIEdata$cdata ){
make.cdata <- FALSE
}
#********** convert BIFIE data object into compact BIFIEcdata object
if ( make.cdata ){
BIFIEdata <- BIFIE.BIFIEdata2BIFIEcdata( BIFIEdata, varnames=varnames )
varnames <- NULL
}
#********** compact saving of replicate weights
if (cdata){
BIFIEdata$wgtreplist <- cdata.wgtrep( BIFIEdata$wgtrep )
BIFIEdata$wgtrep <- NULL
BIFIEdata$cdata <- TRUE
}
#******** variable selection in case of non-compact data
if ( ! cdata ){
BIFIEdata <- BIFIE.data.select( BIFIEdata, varnames=varnames,
impdata.index=NULL )
}
#******** variable selection in case of compact BIFIEdata
if ( cdata ){
BIFIEdata <- BIFIE.cdata.select( BIFIEdata,
varnames=varnames, impdata.index=NULL )
}
#***********************************************************
#****** save objects
save( BIFIEdata, file=paste0( name.BIFIEdata, ".Rdata") )
sink( paste0( name.BIFIEdata, "__SUMMARY.Rout") )
cat( getwd(), "\n", paste0( name.BIFIEdata, ".Rdata\n"),
"Saved at ", paste(Sys.time()), "\n\n")
summary( BIFIEdata )
cat("\n\nSaved variables:\n")
VV <- length(BIFIEdata$varnames)
for (vv in 1:VV){
cat( vv, " ", BIFIEdata$varnames[vv], "\n")
}
sink()
cat( " - Saved", paste0( name.BIFIEdata, ".Rdata"), "in directory \n ")
cat( getwd(), "\n")
}
######################################################################
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/save.BIFIE.data.R
|
## File Name: se.R
## File Version: 0.02
se <- function(object)
{
res <- sqrt(diag(vcov(object)))
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/se.R
|
## File Name: summary.BIFIE.data.R
## File Version: 0.18
##############################################################
summary.BIFIEdata <- function(object, ... )
{
cat("------------------------------------------------------------\n")
d1 <- utils::packageDescription("BIFIEsurvey")
cat( paste( d1$Package, " ", d1$Version, " (", d1$Date, ")", sep=""), "\n" )
cat("\nCall:\n ", paste(deparse(object$CALL), sep="\n", collapse="\n"),
"", sep="")
if( object$cdata ){ cat("\nCompact BIFIEdata") }
cat("\n\n" )
cat( "Date of Analysis:", paste( object$time[1] ), "\n\n" )
if ( ! object$NMI ){
cat("Multiply imputed dataset\n\n")
}
if ( object$NMI ){
cat("Nested multiply imputed dataset\n\n")
}
cat( "Number of persons","=", object$N, "\n" )
cat( "Number of variables","=", object$Nvars, "\n" )
if ( ! object$NMI){
cat( "Number of imputed datasets","=", object$Nimp, "\n" )
}
if ( object$NMI){
cat( "Number of imputed between-nest datasets","=", object$Nimp_NMI[1], "\n" )
cat( "Number of imputed within-nest datasets","=", object$Nimp_NMI[2], "\n" )
}
cat( "Number of Jackknife zones per dataset","=", object$RR, "\n" )
fayfac <- object$fayfac
if ( length(fayfac)==1){
cat( "Fay factor","=", round( object$fayfac, 5 ), "\n\n" )
} else {
mf <- mean(fayfac)
sdf <- stats::sd(fayfac)
cat( "Fay factor: M","=", round( mf, 5 ), "| SD","=",
round( sdf, 5 ), "\n\n" )
}
x2 <- BIFIE_object_size(object)
cat( "Object size: \n " )
cat( "Total: ", x2$value_string, "\n")
obj1 <- "datalistM"
x2 <- BIFIE_object_size(object[[ obj1 ]] )
cat( paste0( " $", obj1, " :" ), x2$value_string, "\n")
obj1 <- "datalistM_ind"
x2 <- BIFIE_object_size(object[[ obj1 ]] )
cat( paste0( " $", obj1, " :" ), x2$value_string, "\n")
obj1 <- "datalistM_imputed"
x2 <- BIFIE_object_size(object[[ obj1 ]] )
cat( paste0( " $", obj1, " :" ), x2$value_string, "\n")
obj1 <- "datalistM_impindex"
x2 <- BIFIE_object_size(object[[ obj1 ]] )
cat( paste0( " $", obj1, " :" ), x2$value_string, "\n")
obj1 <- "dat1"
x2 <- BIFIE_object_size(object[[ obj1 ]] )
cat( paste0( " $", obj1, " :" ), x2$value_string, "\n")
obj1 <- "wgtrep"
x2 <- BIFIE_object_size(object[[ obj1 ]] )
cat( paste0( " $", obj1, " :" ), x2$value_string, "\n")
}
######################################################################
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/summary.BIFIE.data.R
|
## File Name: summary.BIFIE.lavaan.survey.R
## File Version: 0.13
summary.BIFIE.lavaan.survey <- function(object, ... )
{
BIFIE.summary(object)
#- lavaan summary output
print(BIFIE_lavaan_summary(object$lavfit, ...))
#- fit statistics
cat("\n\nModel Fit Statistics\n")
print(object$fit)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/summary.BIFIE.lavaan.survey.R
|
## File Name: svrepdesign2BIFIEdata.R
## File Version: 0.261
svrepdesign2BIFIEdata <- function(svrepdesign, varnames=NULL, cdata=FALSE)
{
## class svyrep.design
if (inherits(svrepdesign,"svyrep.design")){
res <- svrepdesign_extract_data(svrepdesign=svrepdesign, varnames=varnames)
wgt <- res$wgt
wgtrep <- res$wgtrep
fayfac <- res$fayfac
varnames <- res$varnames
data <- svrepdesign$variables
data$one <- NULL
datalist <- data[, varnames, drop=FALSE]
}
## class svyimputationList
if (inherits(svrepdesign,"svyimputationList")){
designs <- svrepdesign$designs
Nimp <- length(designs)
svrepdesign0 <- designs[[1]]
res <- svrepdesign_extract_data(svrepdesign=svrepdesign0, varnames=varnames)
wgt <- res$wgt
wgtrep <- res$wgtrep
fayfac <- res$fayfac
varnames <- res$varnames
datalist <- svrepdesign2datalist(svrepdesign=svrepdesign, varnames=varnames)
}
#- convert to BIFIEdata object
res <- BIFIE.data(data.list=datalist, wgt=wgt, wgtrep=wgtrep, fayfac=fayfac,
cdata=cdata, NMI=FALSE)
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/svrepdesign2BIFIEdata.R
|
## File Name: svrepdesign2datalist.R
## File Version: 0.081
svrepdesign2datalist <- function(svrepdesign, varnames=NULL)
{
if (inherits(svrepdesign,"svyimputationList")){
datalist <- list()
designs <- svrepdesign$designs
Nimp <- length(designs)
if (is.null(varnames)){
varnames <- setdiff( colnames(designs[[1]]$variables), "one")
}
for (ii in 1:Nimp){
data_ii <- designs[[ii]]$variables
datalist[[ii]] <- data_ii[,varnames, drop=FALSE]
}
}
if (inherits(svrepdesign,"svyrep.design")){
if (is.null(varnames)){
varnames <- setdiff( colnames(svrepdesign$variables), "one")
}
datalist <- list()
data1 <- svrepdesign$variables
datalist[[1]] <- data1[,varnames, drop=FALSE]
}
return(datalist)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/svrepdesign2datalist.R
|
## File Name: svrepdesign_extract_data.R
## File Version: 0.10
svrepdesign_extract_data <- function(svrepdesign, varnames=NULL)
{
wgtrep <- svrepdesign$repweights
fayfac <- svrepdesign$scale
wgt <- svrepdesign$pweights
data <- svrepdesign$variables
N <- nrow(data)
sv_varnames <- setdiff( colnames(data), "one")
if (is.null(varnames)){
varnames <- sv_varnames
}
RR <- ncol(wgtrep)
#--- output
res <- list(wgt=wgt, wgtrep=wgtrep, fayfac=fayfac, varnames=varnames,
data=data, N=N, RR=RR)
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/svrepdesign_extract_data.R
|
## File Name: vcov_BIFIE.survey.R
## File Version: 0.297
#--- vcov_BIFIEsurvey
vcov_BIFIEsurvey <- function( object, type=NULL, eps=1E-10, avoid.singul=FALSE )
{
# extract replicated parameters
parsres <- extract.replicated.pars( BIFIE.method=object, type=type )
res1 <- object
#*****
parsM <- parsres$parsM
parsrepM <- parsres$parsrepM
parnames <- parsres$parnames
RR <- object$RR
if ( inherits(object,"BIFIE.correl") & is.null(type) ){
avoid.singul <- TRUE
}
if ( inherits(object, c("BIFIE.freq", "BIFIE.crosstab") ) ){
avoid.singul <- TRUE
}
if ( avoid.singul ){
parsrepM <- parsrepM * ( 1 + stats::runif(prod(dim(parsrepM)), 0, eps ) )
}
fayfac <- res1$fayfac
NP <- nrow(parsM)
Cdes <- matrix( 1, ncol=NP, nrow=1 )
Ccols <- which( colSums( abs( Cdes) ) > 0 )
rdes <- c(0)
# compute covariance matrices
res0 <- bifie_comp_vcov( parsM=parsM, parsrepM=parsrepM,
Cdes, rdes, Ccols - 1, fayfac=fayfac )
var_w <- res0$var_w
var_b <- res0$var_b
Nimp <- res1$Nimp
# total variance
var_tot <- var_w + ( 1 + 1/Nimp ) * var_b
rownames(var_tot) <- colnames(var_tot) <- parnames
if (object$NMI){
var_tot <- BIFIE_NMI_inference_parameters( parsM, parsrepM, fayfac,
RR, Nimp, object$Nimp_NMI, comp_cov=TRUE )$Tm
}
return(var_tot)
}
vcov.BIFIE.correl <- function( object, type=NULL, ... )
{
pars <- vcov_BIFIEsurvey( object=object, type=type, ... )
return(pars)
}
# further BIFIE functions
vcov.BIFIE.by <- function( object, ... )
{
pars <- vcov_BIFIEsurvey( object=object, type=NULL, ...)
return(pars)
}
vcov.BIFIE.derivedParameters <- function( object, ... )
{
pars <- vcov_BIFIEsurvey( object=object, type=NULL, ... )
return(pars)
}
vcov.BIFIE.crosstab <- function( object, ... )
{
pars <- vcov_BIFIEsurvey( object=object, type=NULL, ... )
return(pars)
}
vcov.BIFIE.freq <- function( object, ... )
{
pars <- vcov_BIFIEsurvey( object=object, type=NULL, ...)
return(pars)
}
vcov.BIFIE.linreg <- function( object, ... )
{
pars <- vcov_BIFIEsurvey( object=object, type=NULL, ... )
return(pars)
}
vcov.BIFIE.logistreg <- function( object, ... )
{
pars <- vcov_BIFIEsurvey( object=object, type=NULL, ...)
return(pars)
}
vcov.BIFIE.univar <- function( object, ... )
{
pars <- vcov_BIFIEsurvey( object=object, type=NULL, ...)
return(pars)
}
vcov.BIFIE.twolevelreg <- function( object, ... )
{
if (object$se){
pars <- vcov_BIFIEsurvey( object=object, type=NULL, ... )
} else {
pars <- vcov( object$micombs )
}
return(pars)
}
vcov.BIFIE.pathmodel <- function( object, ... )
{
pars <- vcov_BIFIEsurvey( object=object, type=NULL, ...)
return(pars)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/vcov_BIFIE.survey.R
|
## File Name: write.BIFIE.data.R
## File Version: 1.19
#############################################################
# write BIFIEdata object
write.BIFIEdata <- function( BIFIEdata, name.BIFIEdata,
dir=getwd(), varnames=NULL,
impdata.index=NULL, type="Rdata", ... )
{
dir1 <- getwd()
setwd(dir)
cdata <- BIFIEdata$cdata
# make BIFIE object smaller
BIFIEdata <- BIFIEdata.select( BIFIEdata, varnames, impdata.index)
cat("** Working directory:", dir, "\n")
#*************************
# define file suffixes
filesuf <- paste0(".", type )
if ( type=="csv2" ){ filesuf <- ".csv" }
if ( type=="table" ){ filesuf <- ".dat" }
if ( type=="sav" ){ filesuf <- "" }
#***************************************
# save dataset with replicate weights
cat(" - Saved replicate weights\n") ; utils::flush.console()
filename.temp <- paste0( name.BIFIEdata, "__WGTREP", filesuf )
w1 <- as.data.frame( BIFIEdata$wgtrep )
miceadds::save.data( w1, filename=filename.temp, type=type, path=dir, ... )
w1 <- NULL
#*******************************************
# save imputed datasets
Nimp <- BIFIEdata$Nimp
for (ii in 1:Nimp){
cat(" - Saved imputed dataset", ii, "\n") ; utils::flush.console()
if (! cdata ){
bii <- BIFIEdata.select( BIFIEdata, varnames=varnames, impdata.index=ii )
}
if ( cdata ){
bii <- BIFIE.BIFIEcdata2BIFIEdata( BIFIEdata, varnames=varnames, impdata.index=ii )
}
dat1 <- bii$datalistM
colnames(dat1) <- bii$varnames
filename.temp <- paste0( name.BIFIEdata, "__IMP", ii, filesuf )
dat1 <- as.data.frame(dat1)
miceadds::save.data( dat1, filename=filename.temp, type=type, path=dir, ... )
}
#*** save BIFIEdata object
save.BIFIEdata( BIFIEdata, paste0( name.BIFIEdata, "__BIFIEdataObject" ), cdata=TRUE )
#**** finished
setwd(dir1)
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/write.BIFIE.data.R
|
## File Name: zzz.R
## File Version: 0.14
# zzz.R
#
# This function is simply copied from mice package.
# on attach
.onAttach <- function(libname,pkgname)
{
d <- utils::packageDescription("BIFIEsurvey")
packageStartupMessage("|---------------------------------------------------------",
"--------\n",
paste("| ",d$Package," ", d$Version," (",d$Date,")",sep=""),
"\n| http://www.bifie.at ",
"\n|---------------------------------------------------",
"--------------\n" )
}
version <- function(pkg="BIFIEsurvey")
{
lib <- dirname( system.file(package=pkg) )
d <- utils::packageDescription(pkg)
return( paste(d$Package,d$Version,d$Date,lib) )
}
|
/scratch/gouwar.j/cran-all/cranData/BIFIEsurvey/R/zzz.R
|
#' Amino Acid Analysis Function
#'
#' This is the workhorse function for the amino acid analysis.
#' @param Locus Locus being analyzed.
#' @param loci.ColNames The column names of the loci being analyzed.
#' @param genos Genotype table.
#' @param grp Case/Control or Phenotype groupings.
#' @param Strict.Bin Logical specify if strict rare cell binning should be used in ChiSq test.
#' @param ExonAlign Exon protein alignment filtered for locus.
#' @param Cores Number of cores to use for analysis.
#' @note This function is for internal BIGDAWG use only.
A <- function(Locus,loci.ColNames,genos,grp,Strict.Bin,ExonAlign,Cores) {
# pull out locus specific columns
getCol <- seq(1,length(loci.ColNames),1)[loci.ColNames %in% Locus]
HLA_grp <- cbind(grp,genos[,getCol])
rownames(HLA_grp) <- NULL
nAllele <- length(na.omit(HLA_grp[,2])) + length(na.omit(HLA_grp[,3]))
## extract alleles
Alleles <- unique(c(HLA_grp[,2],HLA_grp[,3]))
Alleles2F <- sort(unique(as.character(sapply(Alleles, GetField, Res=2))))
if( length(Alleles2F)>1 ) {
# Filter exon alignment matrix for specific alleles
TabAA <- AlignmentFilter(ExonAlign,Alleles2F,Locus)
TabAA.list <- lapply(seq_len(ncol(TabAA)), function(x) TabAA[,c(2,x)])
TabAA.list <- TabAA.list[5:ncol(TabAA)]
TabAA.names <- colnames(TabAA)[5:ncol(TabAA)]
# Generate Contingency Tables
ConTabAA.list <- parallel::mclapply(TabAA.list,AAtable.builder,y=HLA_grp,mc.cores=Cores)
names(ConTabAA.list) <- TabAA.names
# Check Contingency Tables
# FlagAA.list <- parallel::mclapply(ConTabAA.list,AA.df.check,Strict.Bin=Strict.Bin,mc.cores=Cores)
# Run ChiSq
ChiSqTabAA.list <- parallel::mclapply(ConTabAA.list,AA.df.cs,Strict.Bin=Strict.Bin,mc.cores=Cores)
FlagAA.list <- lapply(ChiSqTabAA.list,"[[",4)
# build data frame for 2x2 tables
Final_binned.list <- lapply(ChiSqTabAA.list,"[[",1)
ccdat.list <- lapply(Final_binned.list,TableMaker)
OR.list <- lapply(ccdat.list, cci.pval.list) #OR
} else {
# Filter exon alignment matrix for single allele
TabAA <- AlignmentFilter(ExonAlign,Alleles2F,Locus)
FlagAA.list <- as.list(rep(TRUE,length(TabAA[6:length(TabAA)])))
names(FlagAA.list) <- names(TabAA[6:length(TabAA)])
ChiSqTabAA.list <- NA
OR.list <- NA
Final_binned.list <- NA
}
####################################################### Build Output List
A.tmp <- list()
## AAlog_out - Positions with insufficient variation or invalid ChiSq
csRange <- which(FlagAA.list==FALSE) # all failed ChiSeq
FlagAA.fail <- rownames(do.call(rbind,FlagAA.list[csRange]))
if( length(csRange)>0 ) {
# identify insufficient vs invalid flags
invRange <- intersect(names(csRange),
names(which(lapply(Final_binned.list,nrow)>=2)) )# invalid cont table
isfRange <- setdiff(names(csRange),invRange) # insufficient variation
if( length(isfRange)>=1 ){
AAlog.out.isf <- cbind(rep(Locus,length(isfRange)),
isfRange,
rep("Insufficient variation at position.",length(isfRange)))
} else { AAlog.out.isf <- NULL }
if( length(invRange)>=1 ){
AAlog.out.inv <- cbind(rep(Locus,length(invRange)),
invRange,
rep("Position invalid for Chisq test.",length(invRange)))
} else { AAlog.out.inv <- NULL }
# Final AAlog.out
AAlog.out <- rbind(AAlog.out.inv, AAlog.out.isf)
colnames(AAlog.out) <- c("Locus","Position","Comment")
rownames(AAlog.out) <- NULL
AAlog.out <- AAlog.out[match(FlagAA.fail,AAlog.out[,'Position']),]
} else { AAlog.out <- NULL }
A.tmp[['log']] <- AAlog.out
## AminoAcid.binned_out
if(length(ChiSqTabAA.list)>1) {
binned.list <- lapply(ChiSqTabAA.list,"[[",2)
binned.list <- binned.list[which(lapply(binned.list,is.logical)==F)]
binned.out <- do.call(rbind,binned.list)
if(!is.null(nrow(binned.out))) {
binned.out <- cbind(rep(Locus,nrow(binned.out)),
rep(names(binned.list),as.numeric(lapply(binned.list,nrow))),
rownames(binned.out),
binned.out)
colnames(binned.out) <- c("Locus","Position","Residue","Group.0","Group.1")
rownames(binned.out) <- NULL
A.tmp[['binned']] <- binned.out
} else {
binned.out <- cbind(Locus,'Nothing.binned',NA,NA,NA)
colnames(binned.out) <- c("Locus","Position","Residue","Group.0","Group.1")
rownames(binned.out) <- NULL
A.tmp[['binned']] <- binned.out
}
} else{
binned.out <- cbind(Locus,'Nothing.binned',NA,NA,NA)
colnames(binned.out) <- c("Locus","Position","Residue","Group.0","Group.1")
rownames(binned.out) <- NULL
A.tmp[['binned']] <- binned.out
}
## overall.chisq_out
rmPos <- match(FlagAA.fail,names(ChiSqTabAA.list))
ChiSqTabAA.list <- ChiSqTabAA.list[-rmPos]
if(length(ChiSqTabAA.list)>1) {
ChiSq.list <- lapply(ChiSqTabAA.list,"[[",3)
ChiSq.out <- do.call(rbind,ChiSq.list)
if(!is.null(ChiSq.out)){
ChiSq.out <- cbind(rep(Locus,nrow(ChiSq.out)),
rownames(ChiSq.out),
ChiSq.out)
colnames(ChiSq.out) <- c("Locus","Position","X.square","df","p.value","sig")
rownames(ChiSq.out) <- NULL
A.tmp[['chisq']] <- ChiSq.out
} else {
Names <- c("Locus","Position","X.square","df","p.value","sig")
A.tmp[['chisq']] <- Create.Null.Table(Locus,Names,nr=1)
}
} else {
Names <- c("Locus","Position","X.square","df","p.value","sig")
A.tmp[['chisq']] <- Create.Null.Table(Locus,Names,nr=1)
}
## ORtable_out
rmPos <- match(FlagAA.fail,names(OR.list))
OR.list <- OR.list[-rmPos]
if(length(OR.list)>1) {
OR.out <- do.call(rbind,OR.list)
if(!is.null(OR.out)) {
OR.out <- cbind(rep(Locus,nrow(OR.out)),
rep(names(OR.list),as.numeric(lapply(OR.list,nrow))),
rownames(OR.out),
OR.out)
colnames(OR.out) <- c("Locus","Position","Residue","OR","CI.lower","CI.upper","p.value","sig")
rownames(OR.out) <- NULL
rmRows <- unique(which(OR.out[,'sig']=="NA"))
if( length(rmRows) > 0 ) { OR.out <- OR.out[-rmRows,,drop=F] }
A.tmp[['OR']] <- OR.out
} else {
Names <- c("Locus","Position","Residue","OR","CI.lower","CI.upper","p.value","sig")
A.tmp[['OR']] <- Create.Null.Table(Locus,Names,nr=1)
}
} else {
Names <- c("Locus","Position","Residue","OR","CI.lower","CI.upper","p.value","sig")
A.tmp[['OR']] <- Create.Null.Table(Locus,Names,nr=1)
}
## Final_binned_out (Final Table)
rmPos <- match(FlagAA.fail,names(Final_binned.list))
Final_binned.list <- Final_binned.list[-rmPos]
if( length(Final_binned.list)>1 ) {
Final_binned.out <- do.call(rbind,Final_binned.list)
if(!is.null(Final_binned.out)) {
Final_binned.out <- cbind(rep(Locus,nrow(Final_binned.out)),
rep(names(Final_binned.list),as.numeric(lapply(Final_binned.list,nrow))),
rownames(Final_binned.out),
Final_binned.out)
colnames(Final_binned.out) <- c("Locus","Position","Residue","Group.0","Group.1")
rownames(Final_binned.out) <- NULL
A.tmp[['table']] <- Final_binned.out
} else {
Final_binned.out <- NULL
Names <- c("Locus","Position","Residue","Group.0","Group.1")
A.tmp[['table']] <- Create.Null.Table(Locus,Names,nr=1)
}
} else {
Final_binned.out <- NULL
Names <- c("Locus","Position","Residue","Group.0","Group.1")
A.tmp[['table']] <- Create.Null.Table(Locus,Names,nr=1)
}
## AminoAcid.freq_out
if( !is.null(Final_binned.out) ) {
Positions <- unique(Final_binned.out[,'Position'])
for(p in Positions) {
getRows <- which(Final_binned.out[,'Position']==p)
FBO_tmp <- Final_binned.out[getRows,,drop=F]
Final_binned.out[getRows,'Group.0'] <- round(as.numeric(FBO_tmp[,'Group.0']) / sum(as.numeric(FBO_tmp[,'Group.0'])), digits=5)
Final_binned.out[getRows,'Group.1'] <- round(as.numeric(FBO_tmp[,'Group.1']) / sum(as.numeric(FBO_tmp[,'Group.1'])), digits=5)
}
A.tmp[['freq']] <- Final_binned.out
} else {
Names <- c("Locus","Position","Residue","Group.0","Group.1")
A.tmp[['freq']] <- Create.Null.Table(Locus,Names, nr=1)
}
return(A.tmp)
}
|
/scratch/gouwar.j/cran-all/cranData/BIGDAWG/R/A.R
|
#' File Fetcher
#'
#' Download Protein Alignment and Accessory Files
#' @param Loci HLA Loci to be fetched. Limited Loci available.
#' @note This function is for internal BIGDAWG use only.
GetFiles <- function(Loci) {
#downloads *_prot.txt alignment files
#downloads hla_nom_p.txt file
# Get P-Groups Files
download.file("ftp://ftp.ebi.ac.uk/pub/databases/ipd/imgt/hla/wmda/hla_nom_p.txt",destfile="hla_nom_p.txt",method="libcurl")
# Get Release Version
#download.file("ftp://ftp.ebi.ac.uk/pub/databases/ipd/imgt/hla/release_version.txt",destfile="release_version.txt",method="libcurl")
#Release <- read.table("release_version.txt",comment.char="",sep="\t")
#Release <- apply(Release,MARGIN=1,FUN= function(x) gsub(": ",":",x))
#RD <- unlist(strsplit(Release[2],split=":"))[2]
#RV <- unlist(strsplit(Release[3],split=":"))[2]
#write.table(c(RD,RV),file="Release.txt",quote=F,col.names=F,row.names=F)
#file.remove("release_version.txt")
df <- readLines(con="hla_nom_p.txt", n=3)
RD <- unlist(strsplit(df[2],split=" "))[3]
RV <- paste(unlist(strsplit(df[3],split=" "))[3:4],collapse=" ")
write.table(c(RD,RV),file="Release.txt",quote=F,col.names=F,row.names=F)
# Get Locus Based Alignments
for(i in 1:length(Loci)) {
Locus <- Loci[i]
FileName <- paste(Locus,"_prot.txt",sep="")
URL <- paste("ftp://ftp.ebi.ac.uk/pub/databases/ipd/imgt/hla/alignments/",FileName,sep="")
download.file(URL,destfile = FileName,method="libcurl")
}
}
#' HLA P group File Formatter
#'
#' Format the hla_nom_p.txt read table object for a specific locus.
#' @param x P group object from read.table command.
#' @param Locus Locus to be filtered on.
#' @note This function is for internal BIGDAWG use only.
PgrpFormat <- function(x,Locus) {
# Identify for Locus ... change necessary if DRB
x.sub <- x[which(x[,1]==Locus),]
rownames(x.sub) <- NULL
x.sub[,2] <- sapply(x.sub[,2],function(i) paste(paste(Locus,"*",unlist(strsplit(i,"/")),sep=""),collapse="/"))
colnames(x.sub) <- c("Locus","Allele","P.Group")
#Expand
x.list <- list()
for(i in 1:nrow(x.sub)) {
if(grepl("/",x.sub[i,'Allele'],fixed=T)) {
tmp <- unlist(strsplit(x.sub[i,'Allele'],"/"))
tmp <- cbind(rep(Locus,length(tmp)),tmp,rep(x.sub[i,'P.Group'],length(tmp)))
colnames(tmp) <- colnames(x.sub)
x.list[[i]] <- tmp
} else {
x.list[[i]] <- x.sub[i,]
}
}
x.list <- do.call(rbind,x.list)
x.list <- x.list[order(x.list[,'Allele']),]
rownames(x.list) <- NULL
colnames(x.list) <- c("Locus","Allele","P.Group")
return(x.list)
}
#' HLA P group Finder
#'
#' Identify P group for a given allele if exists.
#' @param x Allele of interest.
#' @param y Formatted P groups.
#' @note This function is for internal BIGDAWG use only.
PgrpExtract <- function(x,y) {
getRow <- grep(x,y[,'Allele'],fixed=T)
if(length(getRow)>=1) {
if(length(getRow)>1) { getRow <- getRow[which(sapply(as.character(y[getRow,'Allele']),nchar)==nchar(x))] }
return(as.character(y[getRow,'P.Group']))
} else { return("") }
}
#' Protein Exon Alignment Formatter
#'
#' Dynamically creates an alignmnet of Allele exons for Analysis.
#' @param Locus Locus alignment to be formatted.
#' @param RefTab Reference exon protein information for alignment formatting.
#' @note This function is for internal BIGDAWG use only.
ExonPtnAlign.Create <- function(Locus,RefTab) {
#########################################################################
# Need to remove if DRB split into single locus files
if(grepl("DRB",Locus)) { Locus.get <- "DRB" } else { Locus.get <- Locus }
#########################################################################
AlignMatrix <- NULL; rm(AlignMatrix)
#Read in P-Groups
Pgrps <- read.table("hla_nom_p.txt",fill=T,header=F,sep=";",stringsAsFactors=F,strip.white=T,colClasses="character")
Pgrps[,1] <- gsub("\\*","",Pgrps[,1])
Pgrps <- PgrpFormat(Pgrps,Locus)
#Read in Alignment
Name <- paste0(Locus.get,"_prot.txt")
Align <- read.table(Name,fill=T,header=F,sep="\t",stringsAsFactors=F,strip.white=T,colClasses="character")
#Trim
Align <- as.matrix(Align[-nrow(Align),]) #Remove Footer
#Begin Formatting
Align <- as.matrix(Align[-grep("\\|",Align[,1]),1]) #Remove Pipes
Align[,1] <- sapply(Align[,1],FUN=sub,pattern=" ",replacement="~")
Align[,1] <- sapply(Align[,1],FUN=gsub,pattern=" ",replacement="")
Align <- strsplit(Align[,1],"~")
Align <- as.matrix(do.call(rbind,Align))
#Adjust rows to blank where Sequence column == Allele Name
Align[which(Align[,1]==Align[,2]),2] <- ""
# Remove Prot Numbering Headers
Align <- Align[-which(Align[,1]=="Prot"),]
# Get Unique Alleles
Alleles <- unique(Align[,1])
# Loop Through and Build Alignment Block
Block <- list()
for(i in Alleles) {
getRows <- which(Align[,1]==i)
Block[[i]] <- paste(Align[getRows,2],collapse="")
}
Block <- cbind(Alleles,do.call(rbind,Block))
#Fill end gaps with * to make char lengths even
Block.len <- max(as.numeric(sapply(Block[,2],FUN=nchar)))
for( i in 1:nrow(Block) ) {
Block.miss <- Block.len - nchar(Block[i,2])
if( Block.miss > 0 ) {
Block[i,2] <- paste0(as.character(Block[i,2]), paste(rep(".",Block.miss),collapse=""))
}
}; rm(i)
#Split Allele name into separate Locus and Allele, Send Back to Align object
AlignAlleles <- do.call(rbind,strsplit(Block[,1],"[*]"))
AlignAlleles <- cbind(AlignAlleles,apply(AlignAlleles,MARGIN=c(1,2),FUN=GetField,Res=2)[,2])
rownames(AlignAlleles) <- NULL
Align <- cbind(AlignAlleles,Block)
colnames(Align) <- c("Locus","Allele","Trimmed","FullName","Sequence")
#Split Sub Alignment into composite elements and Extract relevant positions
Align.split <- strsplit(Align[,'Sequence'],"")
Align.split <- do.call(rbind,Align.split)
AlignMatrix <- cbind(Align[,1:4],Align.split)
rownames(AlignMatrix) <- NULL
#Ensure Reference in Row 1
RefAllele <- paste(RefTab[which(RefTab[,'Locus']==Locus),'Reference.Locus'],
RefTab[which(RefTab[,'Locus']==Locus),'Reference.Allele'],
sep="*")
if( !AlignMatrix[1,'FullName']==RefAllele ) {
Align.tmp <- rbind(AlignMatrix[which(AlignMatrix[1,'Allele']==RefAllele),],
AlignMatrix[-which(AlignMatrix[1,'Allele']==RefAllele),])
AlignMatrix <- Align.tmp
rm(Align.tmp)
}
#Save Reference Row
RefSeq <- AlignMatrix[1,]
#Ensure Locus Specific Rows
AlignMatrix <- AlignMatrix[which(AlignMatrix[,'Locus']==Locus),]
#Rebind Reference if removed (only for DRB3, DRB4, and DRB5)
if( !AlignMatrix[1,'FullName']==RefAllele ) { AlignMatrix <- rbind(RefSeq,AlignMatrix) }
#Remove columns with no amino acids positions (only for DRB3, DRB4, and DRB5)
#Count occurence of "." and compare to nrow of AlignMatrix
rmCol <- which( apply(AlignMatrix,MARGIN=2, FUN=function(x) length(which(x=="."))) == nrow(AlignMatrix) )
if( length(rmCol)>0 ) { AlignMatrix <- AlignMatrix[,-rmCol] }
#Propagate Consensus Positions
for( i in 5:ncol(AlignMatrix) ) {
x <- AlignMatrix[,i]
x[which(x=="-")] <- x[1]
AlignMatrix[,i] <- x
}
#Rename amino acid positions based on reference numbering
#Deletions are named according to the preceding position with a .1,.2,etc.
RefStart <- as.numeric(RefTab[which(RefTab[,'Locus']==Locus),'Reference.Start'])
RefArray <- AlignMatrix[1,5:ncol(AlignMatrix)]
Names <- NULL ; RefPos <- RefStart
for(i in 1:length(RefArray) ) {
if(RefArray[i]==".") {
Names <- c(Names, paste0("Pos.",RefPos-1,".",Iteration) )
Iteration = Iteration + 1
} else {
Iteration=1
Names <- c(Names, paste0("Pos.",RefPos))
RefPos <- RefPos + 1
if (RefPos==0) { RefPos <- 1 }
}
}
colnames(AlignMatrix)[5:ncol(AlignMatrix)] <- Names
rownames(AlignMatrix) <- NULL
#Add Absent Allele (Absence due to lack of allele and not lack of typing information)
AlignMatrix <- rbind(c(Locus,"00:00:00:00","00:00",paste(Locus,"*00:00:00:00",sep=""),rep("^",ncol(AlignMatrix)-4)),
AlignMatrix)
#Assign P groups
AlignMatrix <- cbind(AlignMatrix, sapply(AlignMatrix[,'FullName'],PgrpExtract,y=Pgrps) )
colnames(AlignMatrix)[ncol(AlignMatrix)] <- "P.group"
#Tally Unknowns as separate column
AlignMatrix <- cbind(AlignMatrix,
apply(AlignMatrix[,5:(ncol(AlignMatrix)-1)],MARGIN=1,FUN=function(x) length(which(unlist(grep("*",x,fixed=T))>0))) )
colnames(AlignMatrix)[ncol(AlignMatrix)] <- "Unknowns"
#Tally Null Positions as separate column
AlignMatrix <- cbind(AlignMatrix,
apply(AlignMatrix[,5:(ncol(AlignMatrix)-2)],MARGIN=1,FUN=function(x) length(which(unlist(grep("-",x,fixed=T))>0))) )
colnames(AlignMatrix)[ncol(AlignMatrix)] <- "NullPositions"
#Tally InDels
AlignMatrix <- cbind(AlignMatrix,
apply(AlignMatrix[,5:(ncol(AlignMatrix)-3)],MARGIN=1,FUN=function(x) length(which(unlist(grep(".",x,fixed=T))>0))) )
colnames(AlignMatrix)[ncol(AlignMatrix)] <- "InDels"
rownames(AlignMatrix) <- NULL
FileName <- paste("ExonPtnAlign_",Locus,".obj",sep="")
save(AlignMatrix,file=FileName)
}
#' Alignment Object Creator
#'
#' Create Object for Exon Protein Alignments.
#' @param Loci Loci to be bundled.
#' @param Release IMGT/HLA database release version.
#' @param RefTab Data of reference exons used for protein alignment creation.
#' @note This function is for internal BIGDAWG use only.
AlignObj.Create <- function(Loci,Release,RefTab) {
AlignMatrix <- NULL; rm(AlignMatrix)
ExonPtnList <- list()
for(i in 1:length(Loci)) {
Locus <- Loci[i]
FileName <- paste("ExonPtnAlign_",Locus,".obj",sep="")
load(FileName) #Loads AlignMatrix
ExonPtnList[[Locus]] <- AlignMatrix
}
ExonPtnList[['Release.Version']] <- as.character(Release[2,])
ExonPtnList[['Release.Date']] <- as.character(Release[1,])
ExonPtnList[['RefExons']] <- RefTab
save(ExonPtnList,file="ExonPtnAlign.obj")
}
#' Updated Alignment Object Creator
#'
#' Synthesize Object for Exon Protein Alignments.
#' @param Loci Loci to be bundled.
#' @param Release IMGT/HLA database release version.
#' @param RefTab Data of reference exons used for protein alignment creation.
#' @note This function is for internal BIGDAWG use only.
AlignObj.Update <- function(Loci,Release,RefTab) {
AlignMatrix <- NULL; rm(AlignMatrix)
UpdatePtnList <- list()
for(i in 1:length(Loci)) {
Locus <- Loci[i]
FileName <- paste("ExonPtnAlign_",Locus,".obj",sep="")
load(FileName) #Loads AlignMatrix
UpdatePtnList[[Locus]] <- AlignMatrix
}
UpdatePtnList[['Release.Version']] <- as.character(Release[2,])
UpdatePtnList[['Release.Date']] <- as.character(Release[1,])
UpdatePtnList[['RefExons']] <- RefTab
save(UpdatePtnList,file="UpdatePtnAlign.RData")
}
|
/scratch/gouwar.j/cran-all/cranData/BIGDAWG/R/A_ExonPtnAlign_functions.R
|
#' Alignment Filter
#'
#' Filter Protein Exon Alignment File for Specific Alleles.
#' @param Align Protein Alignment Object.
#' @param Alleles to be pulled.
#' @param Locus Locus to be filtered against.
#' @note This function is for internal BIGDAWG use only.
AlignmentFilter <- function(Align, Alleles, Locus) {
getCols <- c(match(c("Trimmed","Unknowns","NullPositions"),
colnames(Align)),
grep("Pos\\.",colnames(Align)))
getRows <- Align[,"Trimmed"] %in% Alleles
Align.sub <- Align[getRows,getCols]
Align.sub <- unique(Align.sub)
if(!is.null(nrow(Align.sub))) {
Alleles.S <- names(which(table(Align.sub[,'Trimmed'])==1))
Alleles.M <- names(which(table(Align.sub[,'Trimmed'])>1))
# Removing Duplicates at 2-Field Level
if( length(Alleles.M > 0 ) ) {
Align.tmp <- list()
for( m in 1:length(Alleles.M) ) {
Allele <- Alleles.M[m]
Alignsub.Grp <- Align.sub[which(Align.sub[,"Trimmed"]==Allele),]
Unknowns.Grp <- which(Alignsub.Grp[,'Unknowns']==min(Alignsub.Grp[,'Unknowns']))
if(length(Unknowns.Grp)>1) { Unknowns.Grp <- Unknowns.Grp[1] }
Align.tmp[[Allele]] <- Alignsub.Grp[Unknowns.Grp,]
}
Align.tmp <- do.call(rbind,Align.tmp)
if( length(Alleles.S) > 0 ) {
AlignMatrix <- rbind(Align.tmp, Align.sub[which(Align.sub[,'Trimmed'] %in% Alleles.S==T),,drop=F])
} else {
AlignMatrix <- Align.tmp
}
} else {
AlignMatrix <- Align.sub
}
AlignMatrix <- cbind(rep(Locus,nrow(AlignMatrix)),AlignMatrix)
rownames(AlignMatrix) <- NULL
colnames(AlignMatrix)[1] <- "Locus"
colnames(AlignMatrix)[which(colnames(AlignMatrix)=="Trimmed")] <- "Allele.2D"
AlignMatrix <- AlignMatrix[ order(AlignMatrix[,'Allele.2D']), ]
} else {
AlignMatrix <- cbind(rep(Locus,nrow(Align.sub)),Align.sub)
rownames(AlignMatrix) <- NULL
colnames(AlignMatrix)[1] <- "Locus"
colnames(AlignMatrix)[which(colnames(AlignMatrix)=="Trimmed")] <- "Allele.2D"
AlignMatrix <- AlignMatrix[ order(AlignMatrix[,'Allele.2D']), ]
}
return(AlignMatrix)
}
#' Amino Acid Contingency Table Build
#'
#' Build Contingency Tables for Amino Acid Analysis.
#' @param x Filtered alignmnet list element.
#' @param y Phenotype groupings.
#' @note This function is for internal BIGDAWG use only.
AAtable.builder <- function(x,y) {
#x = list element for filtered alignment (TabAA.list)
#y = HLA_grp (case vs control)
# Create count Grp 0 v Grp 1 (Control v Case)
x[,2] <- gsub(" ","Null",x[,2])
x[,2] <- gsub("\\*","Unknown",x[,2])
x[,2] <- gsub("\\.","InDel",x[,2])
Residues <- unique(x[,2])
AminoAcid.df <- mat.or.vec(nr=length(Residues),2)
colnames(AminoAcid.df) <- c("Group.0", "Group.1")
rownames(AminoAcid.df) <- Residues
y[,2:3] <- apply(y[,2:3],MARGIN=c(1,2),GetField,Res=2)
# Grp 0 (Control)
Grp0 <- y[which(y[,'grp']==0),]
Grp0cnt <- table(c(x[match(Grp0[,2],x[,1]),2],
x[match(Grp0[,3],x[,1]),2]))
PutRange <- match(rownames(AminoAcid.df),names(Grp0cnt))
AminoAcid.df[,'Group.0'] <- Grp0cnt[PutRange]
# Grp 1 (Case)
Grp1 <- y[which(y[,'grp']==1),]
Grp1cnt <- table(c(x[match(Grp1[,2],x[,1]),2],
x[match(Grp1[,3],x[,1]),2]))
PutRange <- match(rownames(AminoAcid.df),names(Grp1cnt))
AminoAcid.df[,'Group.1'] <- Grp1cnt[PutRange]
AminoAcid.df[is.na(AminoAcid.df)] <- 0
# drop unknowns
rmRow <- which(row.names(AminoAcid.df)=="Unknown")
if( length(rmRow) > 0 ) { AminoAcid.df <- AminoAcid.df[-rmRow,,drop=F] }
return(AminoAcid.df)
}
#' Contingency Table Check
#'
#' Checks amino acid contingency table data frame to ensure required variation exists.
#' @param x contingency table.
#' @param Strict.Bin Logical specify if strict rare cell binning should be used in ChiSq test.
#' @note This function is for internal BIGDAWG use only.
AA.df.check <- function(x,Strict.Bin) {
# Returns true if insufficient variations exists
# RunChiSq Flag is true is sufficient variant exists
if( nrow(x)<2 ) {
return(FALSE)
} else if (Strict.Bin) {
return(!(RunChiSq(x)$Flag))
} else {
return(!(RunChiSq_c(x)$Flag))
}
}
#' Contingency Table Amino Acid ChiSq Testing
#'
#' Runs ChiSq test on amino acid contingency table data frames.
#' @param x contingency table.
#' @param Strict.Bin Logical specify if strict rare cell binning should be used in ChiSq test.
#' @note This function is for internal BIGDAWG use only.
AA.df.cs <- function(x,Strict.Bin) {
# RunChiSq on data frame
if( nrow(x) < 2 ) {
tmp.chisq <- data.frame(rbind(rep("NCalc",4)))
colnames(tmp.chisq) <- c("X.square", "df", "p.value", "sig")
row.names(tmp.chisq) <- "X-squared"
chisq.out <- list(Matrix = x,
Binned = NA,
Test = tmp.chisq,
Flag = FALSE)
return( chisq.out )
} else if (Strict.Bin) {
return( RunChiSq(x) )
} else {
return( RunChiSq_c(x) )
}
}
#' Create Empty Table
#'
#' Creates matrix of NA for no result tables.
#' @param Locus Locus being analyzed.
#' @param Names Column names for final matrix.
#' @param nr Number of rows.
#' @note This function is for internal BIGDAWG use only.
Create.Null.Table <- function(Locus,Names,nr) {
nc <- length(Names)
Data <- c( Locus,rep(NA,nc-1) )
tmp <- matrix(Data,nrow=nr,ncol=nc)
colnames(tmp) <- Names
rownames(tmp) <- NULL
return(tmp)
}
#' Filter Exon Specific Alignment Sections
#'
#' Filters the ExonPtnAlign object by locus and exon.
#' @param Locus Locus being analyzed.
#' @param Exon Exon being analyzed.
#' @param EPL.Locus ExonPtnAlign object filtered by Locus
#' @param RefExons Reference Exon Table
#' @param E.Ptn.Starts Exon Protein Overlay Map
#' @note This function is for internal BIGDAWG use only.
Exon.Filter <- function(Locus,Exon,EPL.Locus,RefExons,E.Ptn.Starts) {
# Get Reference Protoen Start
Ref.Start <- as.numeric(RefExons[RefExons[,'Locus']==Locus,'Reference.Start'])
# Define 5'/3' Boundary Positions
E.Start <- as.numeric(E.Ptn.Starts[which(E.Ptn.Starts[,'Exon']==Exon),'Start'])
E.Stop <- as.numeric(E.Ptn.Starts[which(E.Ptn.Starts[,'Exon']==Exon),'Stop'])
E.Length <- E.Stop - E.Start + 1
# Ensure Number Shift Due to lack of Position 0
if( E.Start >= abs(Ref.Start) ) {
E.Start.Pos <- E.Start + Ref.Start
} else {
E.Start.Pos <- E.Start + Ref.Start - 1
}
E.Stop.Pos <- E.Start.Pos + E.Length - 1
if( E.Start.Pos < 0 && E.Stop.Pos > 0 ) { E.Stop.Pos <- E.Start.Pos + E.Length }
# Find Exon 5' Boundary Position in ExonPtnAlign Object
E.Start.Pos <- paste0("Pos.",E.Start.Pos)
getStart <- match(E.Start.Pos,colnames(EPL.Locus))
# Find Exon 3' Boundary Position
E.Stop.Pos <- paste0("Pos.",E.Stop.Pos)
getStop <- match(E.Stop.Pos,colnames(EPL.Locus))
testStop <- grep(paste0(E.Stop.Pos,"."),colnames(EPL.Locus),fixed=TRUE)
if( length(testStop)>0 ) { getStop <- max(testStop) }
# Define Amino Acid Range to Carve Out
getOverlap <- seq(getStart,getStop)
# Restructure Final ExnPtnAlign Object
getEndCol <- seq(ncol(EPL.Locus)-3,ncol(EPL.Locus))
EPL.Locus.Exon <- EPL.Locus[,c(1:4,getOverlap,getEndCol),drop=F]
return(EPL.Locus.Exon)
}
#' Condensing Exon Specific Alignments to Single Dataframe
#'
#' Combines multiple Exon Specific Alignments into a single Alignment object
#' @param EPL.Exon Exon-Locus Specific Amino Acid Alignment.
#' @note This function is for internal BIGDAWG use only.
Condense.EPL <- function(EPL.Exon) {
df.1 <- EPL.Exon[[1]][,1:4]
getCol <- ncol(EPL.Exon[[1]])
df.2 <- EPL.Exon[[1]][,seq(getCol-3,getCol)]
df <- list()
for( i in 1:length(EPL.Exon) ) {
totalCol <- ncol(EPL.Exon[[i]]) - 4
df[[i]] <- EPL.Exon[[i]][,5:totalCol,drop=F]
}
df <- do.call(cbind,df)
df.out <- cbind(df.1,df,df.2)
return(df.out)
}
|
/scratch/gouwar.j/cran-all/cranData/BIGDAWG/R/A_support_functions.R
|
#' Amino Acid Wrapper
#'
#' Wrapper function for amino acid analysis.
#' @param loci Loci being analyzed.
#' @param loci.ColNames The column names of the loci being analyzed.
#' @param genos Genotype table.
#' @param grp Case/Control or Phenotype groupings.
#' @param Exon Exon(s)for targeted analysis.
#' @param EPL Protein Alignment List.
#' @param Cores Number of cores to use for analysis.
#' @param Strict.Bin Logical specify if strict rare cell binning should be used in ChiSq test
#' @param Output Data return carryover from main BIGDAWG function
#' @param Verbose Summary display carryover from main BIGDAWG function
#' @note This function is for internal BIGDAWG use only.
A.wrapper <- function(loci,loci.ColNames,genos,grp,Exon,EPL,Cores,Strict.Bin,Output,Verbose) {
cat("\n>>>> STARTING AMINO ACID LEVEL ANALYSIS...\n")
# Define Lists for Per Loci Running Tallies
AAlog <- list()
AminoAcid.binned <- list()
AminoAcid.freq <- list()
overall.chisq <- list()
ORtable <- list()
Final_binned <- list()
cat("Processing Locus: ")
cat(colnames(EPL))
# Loop Through Loci
for(x in 1:length(loci)) {
# Get Locus
Locus <- as.character(loci[x])
cat(Locus,".. ")
# Read in Locus Alignment file for Locus specific alignments
if( !missing(Exon) ) {
Exon <- as.numeric(unique(unlist(Exon)))
# Get ExonPtnAlign for Locus
EPL.Locus <- EPL[[Locus]]
RefExons <- EPL[["RefExons"]]
E.Ptn.Starts <- EPL[["ExonPtnMap"]][[Locus]]
EPL.Exon <- list() ; p <- NULL
for (e in 1:length(Exon)) {
getExon <- Exon[e]
if( getExon %in% E.Ptn.Starts[,'Exon'] ) {
if ( is.null(p) ) { p=1 } else { p = p + 1 }
EPL.Exon[[p]] <- Exon.Filter(Locus,getExon,EPL.Locus,RefExons,E.Ptn.Starts)
} else {
Err.Log(Output,"Exon",Locus)
stop("Analysis Stopped.",call. = F)
}
}
ExonAlign <- Condense.EPL(EPL.Exon)
#cbind(colnames(ExonAlign))
} else {
ExonAlign <- EPL[[Locus]]
}
# Run Amino Acid Analysis
A.list <- A(Locus,loci.ColNames,genos,grp,Strict.Bin,ExonAlign,Cores)
# Build Output Lists
AAlog[[Locus]] <- A.list[['log']]
AminoAcid.binned[[Locus]] <- A.list[['binned']]
overall.chisq[[Locus]] <- A.list[['chisq']]
ORtable[[Locus]] <- A.list[['OR']]
Final_binned[[Locus]] <- A.list[['table']]
AminoAcid.freq[[Locus]] <- A.list[['freq']]
}; rm(x) #locus loop
cat("\n\n")
Out <- list()
Out[['AL']] <- do.call(rbind,AAlog)
Out[['AB']] <- do.call(rbind,AminoAcid.binned)
Out[['AF']] <- do.call(rbind,AminoAcid.freq)
Out[['CS']] <- do.call(rbind,overall.chisq)
Out[['OR']] <- do.call(rbind,ORtable)
Out[['FB']] <- do.call(rbind,Final_binned)
if(Output) {
## write to file
write.table(Out[['AL']], file = "AA_log.txt", sep="\t", row.names = F, col.names=T, quote = F)
write.table(Out[['AF']], file = "AA_freqs.txt", sep="\t", row.names = F, col.names=T, quote = F)
write.table(Out[['AB']], file = "AA_binned.txt", sep="\t", row.names = F, col.names=T, quote = F)
write.table(Out[['OR']], file = "AA_OR.txt", sep="\t", row.names = F, col.names=T, quote = F)
write.table(Out[['CS']], file = "AA_chisq.txt", sep="\t", row.names = F, col.names=T, quote = F)
write.table(Out[['FB']], file = "AA_table.txt", sep="\t", row.names = F, col.names=T, quote = F)
}
cat("> AMINO ACID ANALYSIS COMPLETED\n")
if(Verbose){
cat("Significant Amino Acid Position(s):","\n")
tmp <- do.call(rbind,overall.chisq); rownames(tmp) <- NULL
tmp.sig <- tmp[which(tmp[,'sig']=="*"),]; rownames(tmp.sig) <- NULL
if(nrow(tmp.sig)>0) { print(as.data.frame(tmp.sig),row.names=F) }
}
return(Out)
}
|
/scratch/gouwar.j/cran-all/cranData/BIGDAWG/R/A_wrapper.R
|
#' BIGDAWG Main Wrapper Function
#'
#' This is the main wrapper function for each analysis.
#' @param Data Name of the genotype data file.
#' @param HLA Logical Indicating whether data is HLA class I/II genotyping data only.
#' @param Run.Tests Specifics which tests to run.
#' @param Loci.Set Input list defining which loci to use for analyses (combinations permitted).
#' @param Exon Numeric Exon(s) for targeted amino acid analysis.
#' @param All.Pairwise Logical indicating whether all pairwise loci should be analyzed in haplotype analysis.
#' @param Trim Logical indicating if HLA alleles should be trimmed to a set resolution.
#' @param Res Numeric setting what desired resolution to trim HLA alleles.
#' @param EVS.rm Logical indicating if expression variant suffixes should be removed.
#' @param Missing Numeric setting allowable missing data for running analysis (may use "ignore").
#' @param Strict.Bin Logical specify if strict rare cell binning should be used in ChiSq test.
#' @param Cores.Lim Integer setting the number of cores accessible to BIGDAWG (Windows limit is 1 core).
#' @param Results.Dir Optional, string of full path directory name for BIGDAWG output.
#' @param Return Logical Should analysis results be returned as list.
#' @param Output Logical Should analysis results be written to output directory.
#' @param Merge.Output Logical Should analysis results be merged into a single file for easy access.
#' @param Verbose Logical Should a summary of each analysis be displayed in console.
#' @examples
#' \dontrun{
#' ### The following examples use the synthetic data set bundled with BIGDAWG
#'
#' # Haplotype analysis with no missing genotypes for two loci sets
#' # Significant haplotype association with phenotype
#' # BIGDAWG(Data="HLA_data", Run.Tests="H", Missing=0, Loci.Set=list(c("DRB1","DQB1")))
#'
#' # Hardy-Weinberg and Locus analysis ignoring missing data
#' # Significant locus associations with phenotype at all but DQB1
#' # BIGDAWG(Data="HLA_data", Run.Tests="L", Missing="ignore")
#'
#' # Hardy-Weinberg analysis trimming data to 2-Field resolution with no output to files (console only)
#' # Significant locus deviation at DQB1
#' BIGDAWG(Data="HLA_data", Run.Tests="HWE", Trim=TRUE, Res=2, Output=FALSE)
#' }
BIGDAWG <- function(Data, HLA=TRUE, Run.Tests, Loci.Set, Exon, All.Pairwise=FALSE, Trim=FALSE, Res=2, EVS.rm=FALSE, Missing=2, Strict.Bin=FALSE, Cores.Lim=1L, Results.Dir, Return=FALSE, Output=TRUE, Merge.Output=FALSE, Verbose=TRUE) {
options(warn=-1)
MainDir <- getwd()
on.exit(setwd(MainDir), add = TRUE)
# CHECK PARAMETERS
if( missing(Data) ) { Err.Log("P.Missing","Data") ; stop("Analysis Stopped.",call.=FALSE) }
HLA <- as.logical(HLA)
Check.Params(HLA, Loci.Set, Exon, All.Pairwise, Trim, Res, EVS.rm, Missing, Cores.Lim, Return, Output, Merge.Output, Verbose)
# MULTICORE LIMITATIONS
Cores <- Check.Cores(Cores.Lim,Output)
cat(rep("=",40))
cat("\n BIGDAWG: Bridging ImmunoGenomic Data Analysis Workflow Gaps\n")
cat(rep("=",40),"\n")
cat("\n>>>>>>>>>>>>>>>>>>>>>>>>> BEGIN Analysis <<<<<<<<<<<<<<<<<<<<<<<<<\n\n")
# Define Output object
BD.out <- list()
# ===================================================================================================================================== ####
# Read in Data ________________________________________________________________________________________________________________________ ####
NAstrings=c("NA","","****","-","na","Na")
if(is.character(Data)) {
if (Data=="HLA_data") {
# Using internal synthetic set
Tab <- BIGDAWG::HLA_data
Data.Flag <- "Internal Synthetic Data Set"
} else {
# Read in data file entered as string
if(!file.exists(Data)) { Err.Log(Output,"Bad.Filename", Data) ; stop("Analysis stopped.",call.=F) }
Tab <- read.table(Data, header = T, sep="\t", stringsAsFactors = F, na.strings=NAstrings, fill=T, comment.char = "#", strip.white=T, blank.lines.skip=T, colClasses="character")
Data.Flag <- Data
}
} else {
# Using R object
Tab <- Data
Data.Flag <- deparse(substitute(Data))
# Convert Empty Cells to NA
for ( i in 3:ncol(Tab) ) {
putCell <- which( sapply( Tab[,i], nchar )==0 )
if( length(putCell) > 0 ) { Tab[putCell,i] <- NA }
}
}
# Declare Data Input Parameter
cat("Data Input:",Data.Flag,"\n\n\n")
# Convert GLS data
if( ncol(Tab)==3 && !HLA ) { Err.Log(Output,"notHLA.GLS") }
if( ncol(Tab)==3 && HLA ) {
cat("Converting Gene List Strings to Tabular Format...\n\n")
Tab <- GLSconvert(Tab,Convert="GL2Tab",System="HLA",File.Output="R",Strip.Prefix=T,Abs.Fill=T,Cores.Lim=Cores)
}
# Prep Data for processing and checks
Tab <- prepData(Tab)
# Define and Change to the required output directory
if (Output) {
if(missing(Results.Dir)) {
OutDir <- paste(MainDir,"/output ",format(Sys.time(), "%d%m%y %H%M%S"),sep="")
dir.create(OutDir)
} else {
OutDir <- Results.Dir
}
}
if(Output) { setwd(OutDir) }
# ===================================================================================================================================== ####
# Data Processing and Sanity Checks ___________________________________________________________________________________________________ ####
cat(">>>> DATA PROCESSING AND CHECKS.\n")
#### General processing and checks for all data
# Define Data Columns
Data.Col <- seq(3,ncol(Tab))
# RUN TESTS DEFINITIONS
if ( missing(Run.Tests) ) { Run <- c("HWE","H","L","A") } else { Run <- Run.Tests }
if(!HLA) {
if("A" %in% Run) {
cat("Not HLA data. Skipping Amino Acid Analysis.\n")
Run <- Run[-which(Run=="A")]
}
}
# BAD DATA DEFINITIONS - No 1's or 0's
if( length(which(Tab[,Data.Col]==0))>0 || length(which(Tab[,Data.Col]==0))>1 ) {
Err.Log(Output,"Bad.Data")
stop("Analysis Stopped.",call. = F)
}
# MISSING DATA
if(Missing == "ignore") {
cat("Ignoring any missing data.\n")
Err.Log(Output,"Ignore.Missing")
rows.rm <- NULL
} else {
if (Missing > 2) {
if ("H" %in% Run) { Err.Log(Output,"Big.Missing") }
}
cat("Removing any missing data. This will affect Hardy-Weinberg Equilibrium test.\n")
geno.desc <- summaryGeno.2(Tab[,Data.Col], miss.val=NAstrings)
test <- geno.desc[,2] + 2*geno.desc[,3]
rows.rm <- which(test > Missing)
if( length(rows.rm) > 0 ) {
rows.rm <- which(test > Missing)
ID.rm <- Tab[rows.rm,1]
Tab <- Tab[-rows.rm,]
if(Output) { write.table(ID.rm, file="Removed_SampleIDs.txt", sep="\t", row.names=F, col.names=F, quote=F) }
rm(ID.rm)
}
rm(geno.desc,test)
if(nrow(Tab)==0) { Err.Log(Output,"TooMany.Missing") ; stop("Analysis Stopped.",call. = F) }
}
# MULTIPLE SETS AND ANALYSIS DUPLICATION
if(!missing(Loci.Set)) {
if( length(Loci.Set)>1 && (All.Pairwise | "L" %in% Run | "A" %in% Run ) ) { Err.Log(Output,"MultipleSets") }
}
# DATA MERGE AND NUMBER OF LOCI
if(Output && Merge.Output && All.Pairwise) {
if(ncol(Tab)>52) { Err.Log(Output,"AllPairwise.Merge") }
}
##### HLA specific checks
#Check for the updated ExonPtnList 'UpdatePtnList' and use if found.
UpdatePtnList <- NULL
UPL <- paste(path.package('BIGDAWG'),"/data/UpdatePtnAlign.RData",sep="")
if( file.exists(UPL) ) {
load(UPL)
EPL <- UpdatePtnList
rm(UpdatePtnList)
UPL.flag=T
} else {
rm(UpdatePtnList,UPL)
EPL <- BIGDAWG::ExonPtnList
UPL.flag=F }
if(Trim & !HLA) { Err.Log(Output,"NotHLA.Trim") }
if(EVS.rm & !HLA) { Err.Log(Output,"NotHLA.EVS.rm") }
if(!HLA) { DRBFLAG <- NULL } else { DRB345.test <- length(grep("DRB345",colnames(Tab)))>0 }
if(HLA) {
if(Trim | EVS.rm | "A" %in% Run | DRB345.test ) { cat("Running HLA specific check functions...\n") }
# Check Locus*Allele Formatting across all loci
CheckCol <- sum( unlist( apply(Tab[,Data.Col], MARGIN=c(1,2), FUN = function(x) grepl("\\*",na.omit(x))) ) )
TotalCol <- ( dim(Tab[,Data.Col])[1] * dim(Tab[,Data.Col])[2] ) - ( length(which(Tab[,Data.Col]=="^")) + sum(is.na(Tab[,Data.Col])) )
if( CheckCol>0 && CheckCol!=TotalCol ) {
Err.Log(Output,"Bad.Format.HLA")
stop("Analysis Stopped.",call. = F)
}
# Separate DRB345 if exists as single column pair and check zygosity
if(DRB345.test) {
cat("Processing DRB345 column data.\n")
DRBFLAG <- T
# Expand DRB3/4/5 to separate column pairs
Tab <- DRB345.parser(Tab)
colnames(Tab) <- sapply(colnames(Tab),FUN=gsub,pattern="\\.1",replacement="")
# Redefine Data Columns
Data.Col <- seq(3,ncol(Tab))
# Define DR Loci to Process
getCol <- grep("DRB",colnames(Tab))
Loci.DR <- unique(colnames(Tab)[getCol])
# Process Loci
Tab.list <- lapply(seq_len(nrow(Tab)), FUN=function(z) Tab[z,getCol])
Tab.tmp <- mclapply(Tab.list,FUN=DRB345.Check.Wrapper,Loci.DR=Loci.DR,mc.cores=Cores)
Tab.tmp <- do.call(rbind,Tab.tmp)
Tab[,getCol] <- Tab.tmp[,grep("DRB",colnames(Tab.tmp))]
Tab <- cbind(Tab,Tab.tmp[,'DR.HapFlag']) ; colnames(Tab)[ncol(Tab)] <- "DR.HapFlag"
#Identify DR345 flagged haplotypes and Write to File
DR.Flags <- Tab[which(Tab[,'DR.HapFlag']!=""),c(1,2,getCol,ncol(Tab))] ; row.names(DR.Flags) <- NULL
if(Output) {
if(!is.null(DR.Flags)) {
Err.Log(Output,"Bad.DRB345.hap") ; cat("\n")
write.table(DR.Flags,file="Flagged_DRB345_Haplotypes.txt",sep="\t",quote=F,row.names=F,col.names=T)
}
}
cat("\n")
} else { DRBFLAG <- F }
# Separate locus and allele names if data is formatted as Loci*Allele
Tab[,Data.Col] <- apply(Tab[,Data.Col],MARGIN=c(1,2),FUN=Stripper)
# Sanity Check for Resolution if Trim="T" and Trim Data
if(Trim & CheckHLA(Tab[,Data.Col])) {
cat("--Trimming Data.\n")
#Tab.untrim <- Tab
Tab[,Data.Col] <- apply(Tab[,Data.Col],MARGIN=c(1,2),GetField,Res=Res)
rownames(Tab) <- NULL
} else if (Trim) {
Err.Log(Output,"Bad.Format.Trim")
stop("Analysis Stopped.",call. = F)
}
# Sanity Check for Expression Variant Suffix Stripping
if(EVS.rm & CheckHLA(Tab[,Data.Col])) {
cat("--Stripping Expression Variants Suffixes.\n")
Tab[,Data.Col] <- apply(Tab[,Data.Col],MARGIN=c(1,2),gsub,pattern="[[:alpha:]]",replacement="")
EVS.loci <- as.list(names(EPL))
EPL <- lapply(EVS.loci,EVSremoval,EPList=EPL)
names(EPL) <- EVS.loci ; rm(EVS.loci)
} else if (EVS.rm) {
Err.Log(Output,"Bad.Format.EVS")
stop("Analysis Stopped.",call. = F)
}
# Sanity Check for Amino Acid Test Feasibility
if ("A" %in% Run) {
cat("Running Amino Acid Analysis specific checks functions...\n")
Release <- EPL$Release.Version
# Sanity Check for Known HLA loci in Bundled Database Release
cat(paste("--Checking loci against database version",Release,".\n",sep=""))
test <- CheckLoci(names(EPL),unique(colnames(Tab)[Data.Col]))
if( test$Flag ) { Err.Log(Output,"Bad.Locus.HLA",test$Loci) ; stop("Analysis stopped.",call. = F) }
# Sanity Check for Known HLA alleles in Bundled Database Release
cat(paste("--Checking alleles against database version",Release,".\n",sep=""))
test <- CheckAlleles(EPL, Tab[,Data.Col])
if( test$Flag ) { Err.Log(Output,"Bad.Allele.HLA",test$Alleles) ; stop("Analysis stopped.",call. = F) }
# Sanity Check for Analysis and HLA Allele Resolution (MUST perform THIS STEP AFTER TRIM!!!!)
if(Res<2 | !CheckHLA(Tab[,Data.Col])) {
Err.Log(Output,"Low.Res")
cat("You have opted to run the amino acid analysis.\n")
stop("Analysis stopped.",call. = F)
}
} # End A if statement
} # End HLA if statement and HLA specific functionalities
# LOCI SET COLUMN DEFINITIONS
# This section MUST follow DRB345 processing (above) on the chance that DRB345 is formatted as single column
# and DRB3, DRB4, or DRB5 is defined in Loci.Set.
if(missing(Loci.Set)) {
Set <- list(Data.Col)
} else {
Loci.Set <- lapply(Loci.Set,FUN=function(x) sapply(x,toupper))
Set <- lapply(Loci.Set,FUN=function(x) seq(1,ncol(Tab))[colnames(Tab) %in% x])
}
# LOCUS SET DEFINED DOES NOT EXIST IN DATA
if(!missing(Loci.Set)) {
Loci.Set <- unique(unlist(Loci.Set))
Loci.Data <- colnames(Tab)[Data.Col]
if ( sum(Loci.Set %in% Loci.Data) != length(Loci.Set) ) { Err.Log(Output,"PhantomSets") ; stop("Analysis Stopped.",call. = F) }
}
# ===================================================================================================================================== ####
# Case-Control Summary ________________________________________________________________________________________________________________ ####
cat("\n>>>> CASE - CONTROL SUMMARY STATISTICS\n")
#cat(paste(rep("_",50),collapse=""),"\n")
if (Trim) { rescall <- paste(Res,"-Field",sep="") } else { rescall <- "Not Defined" }
Check <- PreCheck(Tab,colnames(Tab),rescall,HLA,Verbose,Output)
if(Output) { write.table(Check,file="Data_Summary.txt",sep=": ",col.names=F,row.names=T,quote=F); rm(Check,rescall) }
# ===================================================================================================================================== ####
# Write to Parameter File _____________________________________________________________________________________________________________ ####
if(Output) {
if(HLA && !is.null(DRBFLAG)) { DRB345.tmp <- DRBFLAG } else { DRB345.tmp <- NULL }
if(HLA) { Trim.tmp <- Trim } else { Trim.tmp <- NULL }
if(HLA && Trim) { Res.tmp <- Res } else { Res.tmp <- NULL }
if(HLA) { EVS.rm.tmp <- EVS.rm } else { EVS.rm.tmp <- NULL }
if( !missing(Exon) ) { Exon.tmp <- paste(unique(unlist(Exon)),collapse=",") } else { Exon.tmp <- NULL }
Params.Run <- list(Time = format(Sys.time(), "%a %b %d %X %Y"),
BD.Version = as.character(packageVersion("BIGDAWG")),
Cores.Used = Cores,
File = Data.Flag,
Output.Results = Output,
Merge = Merge.Output,
Return.Object = Return,
Display.Results = Verbose,
HLA.Data = HLA,
Exon = Exon.tmp,
DRB345.Parsed = DRB345.tmp,
Tests = paste(Run,collapse=","),
All.Pairwise = All.Pairwise,
Trim = Trim.tmp,
Resolution = Res.tmp,
Suffix.Stripping = EVS.rm.tmp,
Missing.Allowed = Missing,
Strict.Binning = Strict.Bin,
Samples.Removed = length(rows.rm))
Params.Run <- do.call(rbind,Params.Run)
write.table(Params.Run,file="Run_Parameters.txt",sep=": ", row.names=T, col.names=F, quote=F)
}
# ===================================================================================================================================== ####
# Hardy Weignberg Equilibrium 'HWE' ___________________________________________________________________________________________________ ####
if ("HWE" %in% Run) {
cat("\n>>>> STARTING HARDY-WEINBERG ANALYSIS...\n")
#cat(paste(rep("_",50),collapse=""),"\n")
if(HLA && Trim) {
cat("HWE performed at user defined resolution.\n")
} else if (HLA) {
cat("HWE performed at maximum available resolution.\n")
}
HWE <- HWE.wrapper(Tab,Output,Verbose)
BD.out[['HWE']] <- HWE
rm(HWE)
} #END HARDY-WEINBERG
# ===================================================================================================================================== ####
# Set Loop Begin (loop through each defined locus/loci set) ___________________________________________________________________________ ####
if ( sum( c("H","L","A") %in% Run ) > 0 ) {
cat("\n>>>>>>>>>>>>>>>>>>>>>>>>> Begin Locus Sets <<<<<<<<<<<<<<<<<<<<<<<<<\n\n")
if(length(Set)==1) {
cat("Your analysis has 1 set to analyze.\n")
} else {
cat(paste("Your analysis has ", length(Set), " sets to analyze.", sep=""),"\n")
}
for(k in 1:length(Set)) {
cat("\n")
cat(paste(rep(">",35),collapse=""),"Running Set",k,"\n")
cols <- Set[[k]]
Tabsub <- Tab[,c(1,2,cols)]
#Set Specific Global Variables
SID <- Tabsub[,1] # sample IDs
genos <- Tabsub[,3:ncol(Tabsub)] # genotypes
genos[genos==""] <- NA
grp <- Tabsub[, 2] # phenotype
#nGrp0 <- length(which(grp==0))*2 #nalleles
#nGrp1 <- length(which(grp==1))*2 #nalleles
loci <- unique(gsub(".1","",colnames(genos),fixed=T)) # name of loci
loci.ColNames <- gsub(".1","",colnames(genos),fixed=T) # column names
nloci <- as.numeric(length(loci)) # number of loci
SetName <- paste('Set',k,sep="")
if(HLA==T) { genos[genos=='^'] <- "00:00" }
if(Output) {
OutSetDir <- paste(OutDir,"/Set",k,sep="")
dir.create(OutSetDir)
setwd(OutSetDir)
Params.set <- list(Set = paste("Set",k),
Loci.Run = paste(loci,collapse=",")
)
Params.set <- do.call(rbind,Params.set)
write.table(Params.set,file="Set_Parameters.txt",sep=": ", row.names=T, col.names=F, quote=F)
}
SAFE <- c(ls(),"SAFE")
# ===================================================================================================================================== ####
# Haplotype Analysis 'H' ______________________________________________________________________________________________________________ ####
if ("H" %in% Run) {
#cat(paste(rep("_",50),collapse="","\n"))
# Sanity check for set length and All.Pairwise=T
if (nloci<2) {
Err.Log(Output,"Loci.No")
stop("Analysis Stopped.", call. = F)
} else if (All.Pairwise & nloci<=2) {
Err.Log(Output,"Loci.No.AP")
stop("Analysis Stopped.", call. = F) }
Haps.list <- H.MC.wrapper(SID,Tabsub,loci,loci.ColNames,genos,grp,All.Pairwise,Strict.Bin,Output,Verbose,Cores)
if(All.Pairwise) {
if(length(BD.out[['H']])>0) { BD.out[['H']] <- c(BD.out[['H']],Haps.list) } else { BD.out[['H']] <- Haps.list }
} else {
BD.out[['H']][[SetName]] <- Haps.list
}
rm(list=ls()[!(ls() %in% SAFE)])
} #END HAPLOTYPE
# ===================================================================================================================================== ####
# Locus Level 'L' _____________________________________________________________________________________________________________________ ####
if ("L" %in% Run) {
#cat(paste(rep("_",50),collapse=""))
L.list <- L.wrapper(nloci,loci,loci.ColNames,genos,grp,Strict.Bin,Output,Verbose)
BD.out[['L']][[SetName]] <- list(binned=L.list[['AB']],
freq=L.list[['AF']],
OR=L.list[['OR']],
chisq=L.list[['CS']],
table=L.list[['FB']])
rm(list=ls()[!(ls() %in% SAFE)])
} #END LOCUS
# ===================================================================================================================================== ####
# Amino Acid Level 'A' ________________________________________________________________________________________________________________ ####
if(HLA) {
if ("A" %in% Run) {
#cat(paste(rep("_",50),collapse=""))
if(UPL.flag) { cat("Using updated protein exon alignments for amino acid analysis.\n") }
A.list <- A.wrapper(loci,loci.ColNames,genos,grp,Exon,EPL,Cores,Strict.Bin,Output,Verbose)
if(Output) {
## write to file
write.table(Release, file = "Set_Parameters.txt", sep="\t", row.names = F, col.names=F, quote = F, append=T)
}
BD.out[['A']][[SetName]] <- list(log=A.list[['AL']],
binned=A.list[['AB']],
freq=A.list[['AF']],
OR=A.list[['OR']],
chisq=A.list[['CS']],
table=A.list[['FB']])
rm(list=ls()[!(ls() %in% SAFE)])
} #END AMINO ACID
}#END if(HLA)
# ===================================================================================================================================== ####
# End Analyses ________________________________________________________________________________________________________________________ ####
}; rm(k)
}# END SET LOOP
if(Output) {
if(Merge.Output) {
cat("\nMerging data files ...\n")
if("HWE" %in% Run) { Run <- Run[-which(Run=="HWE")] }
if( length(Run)>=1 ) { MergeData_Output(BD.out,Run,OutDir) }
}
}
# ===================================================================================================================================== ####
cat("\n>>>>>>>>>>>>>>>>>>>>>>>>>> End Analysis <<<<<<<<<<<<<<<<<<<<<<<<<<\n")
if(Output) { setwd(OutDir); save(BD.out, file="Analysis.RData") }
options(warn=0)
if(Return) { return(BD.out) }
}# END FUNCTION
|
/scratch/gouwar.j/cran-all/cranData/BIGDAWG/R/BIGDAWG.R
|
#' DRB345 Column Processing
#'
#' Separates DRB345 column pair into separate columns for each locus
#' @param Tab Data frame of sampleIDs, phenotypes, and genotypes
#' @note This function is for internal BIGDAWG use only.
DRB345.parser <- function(Tab) {
#Tab Dataset Data-frame
getCol <- grep("DRB345",colnames(Tab))
df <- matrix(data="^",nrow=nrow(Tab),ncol=6)
colnames(df) <- c("DRB3","DRB3.1","DRB4","DRB4.1","DRB5","DRB5.1")
tmp.1 <- sapply(Tab[,getCol[1]],FUN=GetField,Res=1) ; tmp.2 <- sapply(Tab[,getCol[2]],FUN=GetField,Res=1)
tmp <- list()
# DRB3
tmp[[1]] <- unlist(grep("DRB3",Tab[,getCol[1]])) ; tmp[[2]] <- unlist(grep("DRB3",Tab[,getCol[2]]))
df[tmp[[1]],1] <- Tab[tmp[[1]],getCol[1]] ; df[tmp[[2]],2] <- Tab[tmp[[2]],getCol[2]]
df[setdiff(1:nrow(df),tmp[[1]]),1] <- "DRB3*^" ; df[setdiff(1:nrow(df),tmp[[2]]),2] <- "DRB3*^"
df[which(tmp.1=="00"),1] <- paste("DRB3*",Tab[which(tmp.1=="00"),getCol[1]],sep="")
df[which(tmp.2=="00"),2] <- paste("DRB3*",Tab[which(tmp.2=="00"),getCol[2]],sep="")
tmp <- list()
# DRB4
tmp[[1]] <- unlist(grep("DRB4",Tab[,getCol[1]])) ; tmp[[2]] <- unlist(grep("DRB4",Tab[,getCol[2]]))
df[tmp[[1]],3] <- Tab[tmp[[1]],getCol[1]] ; df[tmp[[2]],4] <- Tab[tmp[[2]],getCol[2]]
df[setdiff(1:nrow(df),tmp[[1]]),3] <- "DRB4*^" ; df[setdiff(1:nrow(df),tmp[[2]]),4] <- "DRB4*^"
df[which(tmp.1=="00"),3] <- paste("DRB4*",Tab[which(tmp.1=="00"),getCol[1]],sep="")
df[which(tmp.2=="00"),4] <- paste("DRB4*",Tab[which(tmp.2=="00"),getCol[2]],sep="")
tmp <- list()
# DRB5
tmp[[1]] <- unlist(grep("DRB5",Tab[,getCol[1]])) ; tmp[[2]] <- unlist(grep("DRB5",Tab[,getCol[2]]))
df[tmp[[1]],5] <- Tab[tmp[[1]],getCol[1]] ; df[tmp[[2]],6] <- Tab[tmp[[2]],getCol[2]]
df[setdiff(1:nrow(df),tmp[[1]]),5] <- "DRB5*^" ; df[setdiff(1:nrow(df),tmp[[2]]),6] <- "DRB5*^"
df[which(tmp.1=="00"),5] <- paste("DRB5*",Tab[which(tmp.1=="00"),getCol[1]],sep="")
df[which(tmp.2=="00"),6] <- paste("DRB5*",Tab[which(tmp.2=="00"),getCol[2]],sep="")
# NA's
df[is.na(Tab[,getCol[1]]),] <- NA ; df[is.na(Tab[,getCol[2]]),] <- NA
Tab.sub <- Tab[,-getCol]
Tab <- cbind(Tab.sub,df)
return(Tab)
}
#' DRB345 haplotype zygosity wrapper
#'
#' Checks DR haplotypes for correct zygosity and flags unanticipated haplotypes
#' @param Genotype Row of data set data frame following DRB345 parsing
#' @param Loci.DR DRBx Loci of interest to test for consistency
#' @note This function is for internal use only.
DRB345.Check.Wrapper <- function(Genotype,Loci.DR) {
# Set non-DRB1 Loci
Loci.DR <- Loci.DR[-grep("DRB1",Loci.DR)]
# Substitute ^ for 00:00
Genotype[] <- sapply(Genotype,as.character)
if( sum(grepl("\\^",Genotype)) > 0 ) { Genotype[] <- gsub("\\^","00:00",Genotype) ; Fill.Flag <- T } else { Fill.Flag <- F }
# Apply Function to each DRBx Locus
tmp <- lapply(Loci.DR,FUN=DRB345.Check.Zygosity,Genotype=Genotype)
tmp.calls <- lapply( seq(length(tmp)), FUN = function(i) cbind(tmp[[i]]['Locus_1'], tmp[[i]]['Locus_2']) )
Genotype[,!grepl("DRB1",colnames(Genotype))] <- do.call(cbind, tmp.calls)
if( Fill.Flag ) { Genotype[] <- gsub("00:00","^",Genotype) }
DR.HapFlag <- unlist(lapply(tmp,'[','Flag'))
DR.HapFlag <-paste(DR.HapFlag[which(DR.HapFlag!="")],collapse=",")
Genotype <- cbind(Genotype,DR.HapFlag)
return(Genotype)
}
#' DRB345 haplotype zygosity checker single locus
#'
#' Checks DR haplotypes for correct zygosity and flags unanticipated haplotypes for a single DRBx
#' @param Locus Locus of interest to test for consistency
#' @param Genotype Row of data set data frame following DRB345 parsing
#' @note This function is for internal use only.
DRB345.Check.Zygosity <- function(Locus,Genotype) {
# Remove Abs Strings
Genotype <- Filler(Genotype,Type="Remove") ; Genotype <- Genotype[which(Genotype!="")] ; Genotype <- Genotype[which(Genotype!="")]
DR.out <- data.frame(Locus_1=character(), Locus_2=character(), DR.HapFlag=character(), stringsAsFactors=F)
Abs <- paste(Locus,"*00:00",sep="")
DR.Locus <- gsub("HLA-","",Locus) ; DR.Calls <- gsub("HLA-","",Genotype)
DR.Calls <- sapply(DR.Calls,FUN=GetField,Res=1) # get 1 Field Resolution for Genotype Calls
names(DR.Calls) <- NULL ; Flag <- NULL
#DRB1 - get expected DRB3/4/5 genotypes
DR345.Exp.Calls <- DRB345.Exp(DR.Calls[grep("DRB1",DR.Calls)])
#DRB345 Check
getDRB345 <- grep(DR.Locus,DR.Calls) ; DR.obs <- length(getDRB345) ; DR.exp <- sum(grepl(DR.Locus,DR345.Exp.Calls))
# Assign Genotypes
if( DR.obs != DR.exp ) {
# Inconsistent Genotype Possibilities
if ( DR.obs==0 && DR.exp>=1 ) {
# Missing Allele
DR.out[1, 'Locus_1'] <- Abs ; DR.out[1, 'Locus_2'] <- Abs ; DR.out[1, 'Flag'] <- paste(Locus,"_M",sep="")
} else if ( DR.obs >=1 && DR.exp==0 ) {
# Extra Allele
DR.out[1, 'Locus_1'] <- Genotype[getDRB345[1]] ; DR.out[1, 'Locus_2'] <- Abs ; DR.out[1, 'Flag'] <- paste(Locus,"_P",sep="")
} else if( DR.obs==1 && DR.exp==2 ) {
# Presumed Homozygote Missing Allele
DR.out[1, 'Locus_1'] <- Genotype[getDRB345[1]] ; DR.out[1, 'Locus_2'] <- Genotype[getDRB345[1]] ; DR.out[1, 'Flag'] <- ""
} else if( DR.obs==2 && DR.exp==1 ) {
if( Genotype[getDRB345[1]] == Genotype[getDRB345[2]] ) {
# Extra Allele ... False Homozygote Assumption
DR.out[1, 'Locus_1'] <- Genotype[getDRB345[1]] ; DR.out[1, 'Locus_2'] <- Abs ; DR.out[1, 'Flag'] <- ""
} else {
# Extra Allele Present
DR.out[1, 'Locus_1'] <- Genotype[getDRB345[1]] ; DR.out[1, 'Locus_2'] <-Genotype[getDRB345[2]] ; DR.out[1, 'Flag'] <- paste(Locus,"_P",sep="")
}
}
} else {
DR.out[1, 'Flag'] <- ""
# Consistent Genotype
if( DR.obs==0 ) {
DR.out[1, 'Locus_1'] <-Abs ; DR.out[1, 'Locus_2'] <- Abs
} else if( DR.obs==1 ) {
DR.out[1, 'Locus_1'] <- Genotype[getDRB345[1]] ; DR.out[1, 'Locus_2'] <- Abs
} else if ( DR.obs==2 ) {
DR.out[1, 'Locus_1'] <- Genotype[getDRB345[1]] ; DR.out[1, 'Locus_2'] <- Genotype[getDRB345[2]]
}
}
# Return Result
return(DR.out)
}
#' DRB345 Expected
#'
#' Checks DRB1 Genotype and Returns Expected DR345 Loci
#' @param DRB1.Genotype DRB1 Subject Genotypes
#' @note This function is for internal use only.
DRB345.Exp <- function(DRB1.Genotype) {
#Checks for and fixes certain DRB345 errors that are consistent with known DR haplotypes
Rules <- list("DRB1*01"="","DRB1*10"="","DRB1*08"="",
"DRB1*03"="DRB3","DRB1*11"="DRB3","DRB1*12"="DRB3","DRB1*13"="DRB3","DRB1*14"="DRB3",
"DRB1*04"="DRB4","DRB1*07"="DRB4","DRB1*09"="DRB4",
"DRB1*15"="DRB5","DRB1*16"="DRB5")
DRB1.Genotype <- gsub("HLA-","",DRB1.Genotype)
DRB1.Genotype <- sapply(DRB1.Genotype,FUN=GetField,Res=1)
# Allele 1
DRB1.1 <- DRB1.Genotype[1]
DR.Gtype <- as.character(Rules[DRB1.1])
# Allele 2
if(length(DRB1.Genotype)==1) {
#Consider Homozygote
DRB1.2 <- DRB1.Genotype[1]
} else {
DRB1.2 <- DRB1.Genotype[2]
}
DR.Gtype <- c(DR.Gtype,as.character(Rules[DRB1.2]))
DR.Gtype <- DR.Gtype[which(DR.Gtype!="")]
if(length(DR.Gtype)>0) { DR.Gtype <- paste("HLA-",DR.Gtype,sep="") }
return(DR.Gtype)
}
|
/scratch/gouwar.j/cran-all/cranData/BIGDAWG/R/DRB_Parser.R
|
#' Error Code Display and Logging
#'
#' Displays error codes attributable to data formatting and Locus/Allele naming. Writes to log file.
#' @param Output Logical indicating if Error logging should be written to a file.
#' @param x Log Code.
#' @param y Misc information relevant to error.
#' @param z Misc information relevant to error.
#' @note This function is for internal BIGDAWG use only.
Err.Log <- function (Output, x, y=NULL, z=NULL) {
cat("*****ERROR!******\n")
switch(x,
#Parameters
P.Missing = { Error <- paste("\nNo ",y," specified. This parameter is not optional. Please see vignette.",sep="") },
P.Error = { Error <- paste("\nInvalid ",y," parameter. Please see vignette.",sep="") },
Windows.Cores = { Error <- "\nYou have exceed the maximum allowable cores for Windows. Please see vignette." },
#Formatting
Bad.Data = { Error <- "\nYou seem to have subject data that are 0's or 1's, replace these with another value. Please see vignette." },
Bad.DRB345.hap = { Error <- "\nWe have encountered unanticipated DR haplotypes. Please see the 'Flagged_DRB345_Haplotypes.txt' output file." },
Uneven.Prefix = { Error <- "\nIt seems some (not all) of your loci are formatted as Locus*Allele. Please ensure all loci share a similar format." },
Bad.Format.HLA = { Error <- "\nYour HLA data includes Locus*Allele genotype formatting. Please ensure all genotypes follow this format." },
Bad.Format.Trim = { Error <- "\nYour HLA data does not appear to be formatted properly for trimming. Please see vignette." },
Bad.Format.EVS = { Error <- "\nYour HLA data does not appear to be formatted properly for EVS stripping. Please see vignette." },
Case.Con = { Error <- "\nYour data does not appear to contain both cases and controls. Please see vignette." },
Loci.No = { Error <- "\nYou have opted to run the haplotype analysis with too few loci. Please check Set definitions." },
Loci.No.AP = { Error <- "\nYou have set All.Pairwise to 'True' but one or more your defined locus sets contain too few loci. Please check Set definitions." },
Low.Res = { Error <- "\nThe resolution of your HLA data is less than 2 or does not appear to be formatted properly. Please see vignette." },
High.Res = { Error <- "\nYour HLA does not appear to be formatted properly, >4 fields detected. Please see vignette" },
#Names
Bad.Filename = { Error <- paste("\nBIGDAWG could not locate a file labeled: ",y," in the specificied working directory.",sep="") },
Bad.Locus.NA = { Error <- "\nYou seem to have specified a locus in the Loci.Set that is not present in your data file." },
Bad.Locus.HLA = { Error <- paste("\nThere may be a discrepancy with HLA loci names. Unrecognized locus name(s) encountered: ",y,".",sep="") },
Bad.Allele.HLA = { Error <- paste("\nThere may be a discrepancy with allele names. Unrecognized allele name(s) encountered: ",y,".",sep="") },
#Other
PhantomSets = { Error <- "\nYou have defined a locus set (Loci.Set) that does not exist in the sample data. Please check the defined locus set." },
MultipleSets = { Error <- "\nWARNING!!! You have opted to run multiple sets with overlapping loci. To avoid duplication of effort and results from the all pairwise haplotype tests, the locus test, and/or the amino acid test(!!!), it is suggested you run these tests separately on either the largest loci set possible or all loci in a given data set." },
No.Internet = { Error <- "\nYou do not seem to be connected to the internet. CheckRelease() or UpdateRelease() cannot proceed." },
TooMany.Missing = { Error <- "\nYour data is missing too many values at each locus. Try using Missing='ignore' when running BIGDAWG and avoid haplotype test." }, #Notifications
Ignore.Missing = { Error <- "\nConsider setting a missing threshold or running without the haplotype ('H') analysis. A large number of missing data in the haplotype analysis will affect performance, require large amounts of RAM, cause long wait times, and in the worst case crash your computer." },
Big.Missing = { Error <- "\nThe number of allowable missing will affect performance.\nConsider running with a smaller 'Missing' value or without the haplotype ('H') analysis.\ncontinuing......" },
AllPairwise.Merge = { Error <- "\nYou have opted to run all pairwise combinations and merge the final data tables. For a large number of loci, this could take a long time. You have been warned!" },
NotHLA.Trim = { Error <- "\nTrimming only relevant to HLA data, no trimming performed." },
NotHLA.EVS.rm = { Error <- "\nExpression variant suffix stripping only relevant to HLA data, no stripping performed." },
Exon = { Error <- paste("\n You have defined an exon that does not exist in locus ",y,". Please adjust exons or loci.set.",sep="") },
#GLS Notifications
Tab.Format = { Error <- "\nThe conversion tool encountered GL string delimiters. This isn't valid data for Tab2GL converion. Please see vignette." },
GL.Format = { Error <- "\nYour GL strings may not be properly formatted. Please see vignette." },
File.Error = { Error <- paste("\nThe conversion tool could not locate a file labeled ",y," in the specified working directory.",sep="") },
GTYPE.Amb = { Error <- paste("\nThis appears to contain genotype list piping ('|') for genotype ambiguity strings (data rows: ",y,"). This is not supported in GLSconversion.",sep="") },
Table.Col = { Error <- "\nThe table for Tab2GL conversion is not properly formatted, too few columns. Please see vignette." },
Table.Pairs = { Error <- "\nThe table for Tab2GL conversion is not properly formatted, no locus column pairs encountered. Please see vignette." },
Table.Amb = { Error <- "\nYour data has duplicate identifying information rows, perhaps due to data genotype ambiguity." },
Locus.MultiField = { Error <- paste("\nYour GL string may be invalid. A locus cannot appear in multiple gene fields! ",z,ifelse(grepl(",",z)," appear"," appears")," in multiple fields of the GL string: ", y, ". Please see vignette.",sep="") },
Allele.Amb.Format = { Error <- paste("\nYour GL string may be invalid. The ambiguous allele ",y," is not properly formatted. Please see vignette.", sep="") },
notHLA.GLS = { Error <- paste("\nYou may want GLS conversion for non-HLA data. Currently, BIGDAWG only supports HLA for automatic GLS conversion. Please see vignette.", sep="") }
)
cat(Error,"\n",file=stderr())
if(Output) { write.table(Error,file="Error_Log.txt",sep="\t",quote=F,col.names=F,row.names=F,append=T) }
}
|
/scratch/gouwar.j/cran-all/cranData/BIGDAWG/R/ErrLog.R
|
#' Genotype List String to Tabular Data Conversion
#'
#' Expands GL strings to columns of adjacent locus pairs.
#' @param df Data frame containing GL strings
#' @param System Character Genetic system HLA or KIR
#' @param Strip.Prefix Logical Should System/Locus prefixes be stripped from table data.
#' @param Abs.Fill Logical Should absent loci special designations be used.
#' @param Cores Integer How many cores can be used
#' @note This function is for internal use only
GL2Tab.wrapper <- function(df,System,Strip.Prefix,Abs.Fill,Cores) {
# Data column
LastCol <- ncol(df)
MiscCol <- seq(1,ncol(df)-1)
# Remove empty data rows
df <- na.omit(df)
rmRows <- which(nchar(df[,LastCol])==0)
if( length(rmRows)!=0 ) { df <- df[-rmRows,] }
# Run Conversion
df.list <- strsplit(df[,LastCol],"\\^")
Tab <- parallel::mclapply(df.list,FUN=GL2Tab.Sub,System=System,mc.cores=Cores)
Loci <- sort(unique(gsub("_1|_2","",unlist(lapply(Tab,colnames)))))
if( sum(grepl('DR.HapFlag',Loci)) > 0 ) { Loci <- Loci[-grep('DR.HapFlag',Loci)] }
Order <- Build.Matrix(System,Loci)
Tab <- parallel::mclapply(Tab,FUN=Format.Tab,Order=Order,mc.cores=Cores)
Tab <- do.call(rbind,Tab)
Tab[Tab==0] <- ""
Tab[grepl("\\^",Tab)] <- ""
# Pad Absent Calls for DRBx?
if( System=="HLA-") {
getCol <- grep("DRB3|DRB4|DRB5",colnames(Tab))
if(length(getCol)>0) {
if(Abs.Fill) {
Tab[,getCol] <- sapply(getCol,FUN=function(i) Filler(Tab[,i], colnames(Tab)[i], Type="Fill"))
} else {
Tab[,getCol] <- sapply(getCol,FUN=function(i) Filler(Tab[,i], Type="Remove"))
}
}
}
# Strip Prefixes?
if(Strip.Prefix) { Tab[,seq(1,ncol(Tab)-1)] <- apply(Tab[,seq(1,ncol(Tab)-1)],MARGIN=c(1,2),FUN=Stripper) }
# Final Table with Misc Information Appended
Tab <- cbind(df[,MiscCol],Tab)
return(Tab)
}
#' Genotype List String Expander
#'
#' Expands GL string into a table of adjacent loci
#' @param x Character GL string to expand
#' @param System Character Genetic system HLA or KIR
#' @note This function is for internal use only.
GL2Tab.Sub <- function(x,System) {
# Break GL String and Remove Any Absent Call Type Strings (00:00)
Calls <- unlist(sapply(x,FUN=function(x) strsplit(x,"\\+"))) ; names(Calls) <- NULL
# Check GL String For Locus*Allele/Locus*Allele Ambiguity Formatting
invisible(sapply(Calls,CheckString.Allele))
# Collapse Ambiguous allele names to remove locus prefix
if( sum(grepl("/",Calls)>0 ) ) {
Calls <- unlist(lapply(Calls,Format.Allele,Type="off"))
}
# Get loci and initialize table
Loci <- unique(unlist(lapply(strsplit(Calls,"\\*"),"[",1)))
if(System=="HLA-") {
if( sum(grepl("DRB1",Loci))>0 ) { Loci <- c(Loci,DRB345.Exp(Calls[grep("DRB1",Calls)])) }
Loci <- unique(Loci)
}
Tab <- Build.Matrix(System,Loci)
# Check GL String For Locus^Gene Field Consistency
invisible(CheckString.Locus(x,Loci))
# Populate table
tmp <- lapply(Loci,GL2Tab.Loci,Genotype=Calls,System=System)
tmp.calls <- lapply( seq(length(tmp)), FUN = function(i) cbind(tmp[[i]]['Locus_1'], tmp[[i]]['Locus_2']) )
tmp.calls <- do.call(cbind, tmp.calls)
DR.HapFlag <- unlist(lapply(tmp,'[','DR.HapFlag'))
DR.HapFlag <-paste(DR.HapFlag[which(DR.HapFlag!="")],collapse=",")
Tab[1,] <- cbind(tmp.calls,DR.HapFlag)
return(Tab)
}
#' Locus Ordering for GL2Tab
#'
#' Orders Locus Calls
#' @param Locus Locus to condense
#' @param Genotype Row of loci to condense
#' @param System Character Genetic system HLA or KIR
#' @note This function is for internal use only.
GL2Tab.Loci <- function(Locus,Genotype,System) {
Alleles <- Genotype[grep(Locus,Genotype)]
if( length(Alleles) == 1 && System=="HLA-" ) {
if( Locus!="HLA-DRB3" || Locus!="HLA-DRB4" || Locus!="HLA-DRB5" ) {
# Homozygous Assumption for HLA non-DRB345
Alleles <- c(Alleles,Alleles)
}
} else if ( length(Alleles) == 1 ) {
Alleles <- c(Alleles,"")
} else if ( length(Alleles) == 0 ) {
Alleles <- c("","")
}
names(Alleles) <- c('Locus_1','Locus_2')
if(System=="HLA-") {
if(Locus=="HLA-DRB3" || Locus=="HLA-DRB4" || Locus=="HLA-DRB5") {
if( sum(grepl("DRB1",Genotype))>0 ) {
# Assumptions for DRB345
DRB.GTYPE <- DRB345.Check.Zygosity(Locus,Genotype[grep("DRB",Genotype)])
DRB.GTYPE[1,grepl("\\^",DRB.GTYPE)] <- ""
Alleles[] <- c(DRB.GTYPE[,'Locus_1'],DRB.GTYPE[,'Locus_2'])
# for inconsistent DR haplotypes
DRB345.Flag <- DRB.GTYPE[,'Flag']
} else {
# No DRB1 but DBR345 (ZYgosity Check Not Determined)
DRB345.Flag <- "DRB345_ND"
} # fi DRB1
} else { DRB345.Flag <- NULL } # fi DRB345
} # fi HLA
if(System=="HLA-") {
DR.HapFlag <- ifelse(!is.null(DRB345.Flag), paste(unlist(DRB345.Flag),collapse=",") , "")
Out <- c(Alleles,DR.HapFlag)
names(Out)[length(Out)] <- "DR.HapFlag"
} else {
Out <- Alleles
}
return(Out)
}
|
/scratch/gouwar.j/cran-all/cranData/BIGDAWG/R/GL2TAB.R
|
#' Genotype List String Conversion
#'
#' Main Workhorse wrapper for cross converting columnar table to GL string representaion.
#' @param Data String File name or R Data Frame.
#' @param Convert String Direction for conversion.
#' @param File.Output String Type of File.Output.
#' @param System String Genetic system (HLA or KIR) of the data being converted
#' @param HZY.Red Logical Reduction of homozygote genotypes to single allele.
#' @param DRB345.Check Logical Check DR haplotypes for consistency and flag unusual haplotypes.
#' @param Strip.Prefix Logical Should System/Locus prefixes be stripped from table data.
#' @param Abs.Fill Logical Should absent loci special designations be used.
#' @param Cores.Lim Integer How many cores can be used.
GLSconvert <- function(Data,Convert,File.Output="txt",System="HLA",HZY.Red=FALSE,DRB345.Check=FALSE,Strip.Prefix=TRUE,Abs.Fill=FALSE,Cores.Lim=1L) {
# Check Parameters
if( missing(Data) ) { Err.Log(FALSE,"P.Missing","Data") ; stop("Conversion Stopped.",call.=FALSE) }
if( missing(Convert) ) { Err.Log(FALSE,"P.Missing","Convert") ; stop("Conversion Stopped.",call.=FALSE) }
Check.Params.GLS(Convert,File.Output,System,HZY.Red,DRB345.Check,Cores.Lim)
# MultiCore Limitations
Cores <- Check.Cores(Cores.Lim,FALSE)
# Set nomenclature system and Prefix stripping for pypop output
if( System == "HLA" ) { System <- "HLA-" }
if( File.Output == "pypop" ) { Strip.Prefix <- TRUE }
# Read in Data and Set File.Output File Name
if( is.character(Data) ) {
if( file.exists(Data) ) {
df <- read.table(file=Data,header=T,sep="\t", stringsAsFactors=FALSE, fill=T, comment.char = "#", strip.white=T, blank.lines.skip=T, colClasses="character")
colnames(df) <- gsub("HLA.","HLA-",colnames(df))
fileName <- getFileName(Data)
} else { Err.Log(FALSE,"File.Error",Data) ; stop("Conversion Stopped.",call.=FALSE) }
} else { df <- Data ; fileName <- "Converted" }
df[] <- lapply(df, as.character)
df[is.na(df)] <- ""
# Check Data Structure/Formatting
Check.Data(df,System,Convert)
# Run Data Conversion
switch(Convert,
GL2Tab = { data.out <- GL2Tab.wrapper(df,System,Strip.Prefix,Abs.Fill,Cores) } ,
Tab2GL = { data.out <- Tab2GL.wrapper(df,System,HZY.Red,Abs.Fill,Cores) } )
# Output DR.HapFlag for HLA data
if( System=="HLA-" && !DRB345.Check ) { data.out <- data.out[,-grep('DR.HapFlag',colnames(data.out))] }
# File Name Ouput Options
switch(File.Output,
txt = { fileName <- paste(fileName,".txt",sep="") },
csv = { fileName <- paste(fileName,".csv",sep="") },
pypop = { fileName <- paste(fileName,".pop",sep="") } )
# File.Output Final Converted File
switch(File.Output,
R = return(data.out),
txt = write.table(data.out,file=fileName,sep="\t",quote=F,col.names=T,row.names=F),
csv = write.csv(data.out,file=fileName,quote=F,col.names=T,row.names=F),
pypop = write.table(data.out,file=fileName,sep="\t",quote=F,col.names=T,row.names=F) )
}
|
/scratch/gouwar.j/cran-all/cranData/BIGDAWG/R/GLSconvert.R
|
#' Hardy Weinbergy Equilibrium Function
#'
#' This is the main function for the HWE analysis.
#' @param Tab data frame of genotype files post processing.
#' @note This function is for internal BIGDAWG use only.
HWE <- function(Tab) {
HWE.out <- list()
All.ColNames <- colnames(Tab)
loci <- as.list(unique(All.ColNames[3:length(All.ColNames)]))
nloci <- length(loci)
#HWE Controls / Group 0
genos.sub <- Tab[which(Tab[,2]==0),3:ncol(Tab)]
HWE.out[["controls"]] <- HWE.ChiSq(genos.sub,loci,nloci)
#HWE Cases / Group 1
genos.sub <- Tab[which(Tab[,2]==1),3:ncol(Tab)]
HWE.out[["cases"]] <- HWE.ChiSq(genos.sub,loci,nloci)
return(HWE.out)
}
|
/scratch/gouwar.j/cran-all/cranData/BIGDAWG/R/HWE.R
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.