content
stringlengths
0
14.9M
filename
stringlengths
44
136
#' Summary method for class MultipleCICA #' @description Summarize a CICA analysis #' @param object Object of the type produced by \code{\link{CICA}} #' @param ... Additional arguments #' #' @return \code{summary.MultipleCICA} returns an overview of the estimated clustering of a \code{\link{CICA}} analysis #' \item{PM}{Partitioning matrix} #' \item{tab}{tabulation of the clustering} #' \item{Loss}{Loss function value of the solution} #' #' #' @examples #' \dontrun{ #' CICA_data <- Sim_CICA(Nr = 15, Q = 5, R = 4, voxels = 100, timepoints = 10, #' E = 0.4, overlap = .25, externalscore = TRUE) #' #' multiple_output = CICA(DataList = CICA_data$X, nComp = 2:6, nClus = 1:5, #' userGrid = NULL, RanStarts = 30, RatStarts = NULL, pseudo = c(0.1, 0.2), #' pseudoFac = 2, userDef = NULL, scalevalue = 1000, center = TRUE, #' maxiter = 100, verbose = TRUE, ctol = .000001) #' #' summary(multiple_output$Q_5_R_4) #' } #' #' @export summary.MultipleCICA <- function(object, ...){ cat('MultipleCICA object, Sequential Scree procedure used to determine optimal model\n') modsel <- SequentialScree(object) if(length(modsel$optimalQ)==0){ stop("Scree values cannot be computed. Check if you provided at least 3 values for the nComp input argument of CICA") } id <- paste('Q',modsel$optimalQ,'R',modsel$optimalR, sep = '_') cat('Optimal model: ', id, '\n') id <- which(id == names(object)) object <- object[[id]] cat('Partitioning matrix P: \n' ) PB <- matrix(0, nrow = length(object$P), ncol = length(unique(object$P))) for(i in 1:nrow(PB)){ PB[i, object$P[i]] <- 1 } colnames(PB) <- paste('Cluster',sort(unique(object$P))) rownames(PB) <- names(object$P) cat('\n') print(PB) cat('\n') cat('Tabulation of clustering: \n') cat('\n') tab <- table(object$P) names(tab) <- paste('Cluster',sort(unique(object$P))) print( tab ) cat('\n') cat('Loss function value of optimal solution is: ', object$Loss,'\n') # out <- list() # out$PM <- PB # out$tab <- tab # out$loss <- object$Loss # # return(out) }
/scratch/gouwar.j/cran-all/cranData/CICA/R/summary.MultipleCICA.R
#' Scale data blocks to have an equal sum of squares #'@description Internal function for CICA package #' @param Xi a single datablock #' @param value desired sum of squares value of the datablock #' #' @keywords internal #' @return a matrix that is scale to have a sum of squares of size \code{value} xscale <- function(Xi, value = 1000){ f <- sqrt(value/sum(Xi^2)) return(f*Xi) }
/scratch/gouwar.j/cran-all/cranData/CICA/R/xscale.R
custom.measure <- function(X,fun=NULL,cond=NULL,verbose=TRUE,with.se=FALSE,...){ if(is.null(fun)){stop("'fun' need to be specified")} if(is.function(fun)==FALSE){stop("'fun' needs to be a function")} if(is.null(X$simulated.data)){stop("Set 'ret=TRUE' in gformula() to work with custom measures.")} if(verbose==TRUE){if(X$setup$i.type=="custom"){cat("Note: you chose custom interventions. \n 'custom.measure' asssumes that the intervention values at the first time point (time=1) are not identical.\n\n")}} if(X$setup$measure=="custom"){stop("You can't apply 'custom measure' on an Xect onto which you already applied 'custom measure'.")} if(X$setup$B==0 & with.se==T){stop("Standard error can only be calculated if B>0")} if(X$setup$B>0){if(X$setup$B!=(length(X$simulated.data)-1)){X$setup$B<- (length(X$simulated.data)-1) }} sdata <- X$simulated.data odata <- X$observed.data results.table <- X$results if(length(grep("mult",X$setup$fams))>0 & X$setup$i.type=="natural"){ if(is.null(sum(sapply(odata[[1]],is.factor))>0)==FALSE){if(sum(sapply(odata[[1]],is.factor))>0){ for(b in 1:(X$setup$B+1)){odata[[b]][,sapply(odata[[b]],is.factor)] <- apply(sapply(( subset(odata[[b]],select=sapply(odata[[b]],is.factor))),as.character),2,as.numeric)} }} } if(X$setup$i.type=="standard"){ for(i in 1:length(sdata[[1]])){ if(is.null(cond)==FALSE){sel <- with(as.data.frame(sdata[[1]][[i]]), eval(parse(text=cond),envir=environment()))}else{sel<-rep(TRUE,nrow(sdata[[1]][[i]]))} results.table[results.table$a1==X$setup$abar[i],"psi"] <- apply(as.matrix(sdata[[1]][[i]][sel,X$setup$Ynodes],ncol=length(X$setup$Ynodes)),2,fun,...) if(X$setup$B>0){ sbdata <- lapply(sdata, '[[', i); bfs <- matrix(NA,ncol=length(X$setup$Ynodes),nrow=X$setup$B) for(b in 2:(X$setup$B+1)){bfs[b-1,] <- apply(data.matrix(sbdata[[b]][sel,X$setup$Ynodes]),2,fun,...) } results.table[results.table$a1==X$setup$abar[i],c("l95","u95")] <- t(apply(bfs,2,quantile,probs=c(0.025,0.975))) if(with.se==TRUE){ if(i==1){results.table$se<-NA} results.table[results.table$a1==X$setup$abar[i],c("se")] <- apply(bfs,2,sd)} } }} if(X$setup$i.type=="custom"){ for(i in 1:length(sdata[[1]])){ if(is.null(cond)==FALSE){sel <- with(as.data.frame(sdata[[1]][[i]]), eval(parse(text=cond),envir=environment()))}else{sel<-rep(TRUE,nrow(sdata[[1]][[i]]))} results.table[results.table$a1==X$setup$abar[i,1],"psi"] <- apply(as.matrix(sdata[[1]][[i]][sel,X$setup$Ynodes],ncol=length(X$setup$Ynodes)),2,fun,...) if(X$setup$B>0){ sbdata <- lapply(sdata, '[[', i); bfs <- matrix(NA,ncol=length(X$setup$Ynodes),nrow=X$setup$B) for(b in 2:(X$setup$B+1)){bfs[b-1,] <- apply(data.matrix(sbdata[[b]][sel,X$setup$Ynodes]),2,fun,...) } results.table[results.table$a1==X$setup$abar[i],c("l95","u95")] <- t(apply(bfs,2,quantile,probs=c(0.025,0.975))) if(with.se==TRUE){ if(i==1){results.table$se<-NA} results.table[results.table$a1==X$setup$abar[i],c("se")] <- apply(bfs,2,sd)} } }} if(X$setup$i.type=="natural"){ if(is.null(cond)==FALSE){sel_nat <- with(as.data.frame(sdata[[1]][[1]]), eval(parse(text=cond),envir=environment()))}else{sel_nat<-rep(TRUE,nrow(sdata[[1]][[1]]))} if(is.null(cond)==FALSE){sel_obs <- with(as.data.frame(odata[[1]]), eval(parse(text=cond),envir=environment()))}else{sel_obs<-rep(TRUE,nrow(odata[[1]]))} results.table[results.table$a1=="natural","psi"] <- apply(as.matrix(sdata[[1]][[1]][sel_nat,X$setup$Ynodes],ncol=length(X$setup$Ynodes)),2,fun,...) results.table[results.table$a1=="observed","psi"] <- try(apply(data.frame(odata[[1]][sel_obs,X$setup$Ynodes]),2,fun,...)) if(is.null(X$setup$Lnodes)==FALSE){ if(verbose==TRUE){cat("Note: specified function and condition will also be applied to counterfactual Lnodes. \n\n")} lblocks <- rep(NA,length(X$setup$Ynodes)) for(i in 1:(length(X$setup$Ynodes))){ blocks <- make.interval(which(colnames(odata[[1]])%in%X$setup$Ynodes)) lblocks[i] <- sum(which(colnames(odata[[1]])%in%X$setup$Lnodes)%in%blocks[[i]]) } if(is.wholenumber(length(X$setup$Lnodes)/length(X$setup$Ynodes)) | X$setup$n.t==1){ results.table[results.table$a1=="natural",paste0("L_",1:(length(X$setup$Lnodes)/X$setup$n.t))] <- matrix(apply(matrix(sdata[[1]][[1]][sel_nat,X$setup$Lnodes],ncol=length(X$setup$Lnodes)),2,fun,...),ncol=(length(X$setup$Lnodes)/X$setup$n.t),byrow=T) results.table[results.table$a1=="observed",paste0("L_",1:(length(X$setup$Lnodes)/X$setup$n.t))] <- matrix(try(apply(data.frame(odata[[1]][sel_obs,X$setup$Lnodes]),2,fun,...)),ncol=(length(X$setup$Lnodes)/X$setup$n.t),byrow=T) results.table[results.table$a1=="difference",paste0("L_",1:(length(X$setup$Lnodes)/X$setup$n.t))] <- results.table[results.table$a1=="natural",paste0("L_",1:(length(X$setup$Lnodes)/X$setup$n.t))] - results.table[results.table$a1=="observed",paste0("L_",1:(length(X$setup$Lnodes)/X$setup$n.t))] }else{ if(length(lblocks)>1 & length(unique(lblocks[-1]))==1){ results.table[results.table$a1=="natural" & results.table$time!=1,paste0("L_",1:max(lblocks))] <- matrix(apply(matrix(sdata[[1]][[1]][sel_nat,X$setup$Lnodes],ncol=length(X$setup$Lnodes)),2,fun,...),ncol=max(lblocks),byrow=T) results.table[results.table$a1=="observed"& results.table$time!=1,paste0("L_",1:max(lblocks))] <- matrix(try(apply(data.frame(odata[[1]][sel_obs,X$setup$Lnodes]),2,fun,...)),ncol=max(lblocks),byrow=T) if(verbose==TRUE){cat("Note: it is not entirely clear to which time points your Lnodes belong to. I guessed what could make sense, but please check.\n\n")} }else{ if(max(lblocks,na.rm=T)==1){ updat.index <- unlist(lapply(apply(t(outer(which(colnames(odata[[1]])%in%X$setup$Lnodes), which(colnames(odata[[1]])%in%X$setup$Ynodes), "<")),1,which),max)) updt.Lnodes <- apply(as.matrix(sdata[[1]][[1]][sel_nat,X$setup$Lnodes],ncol=length(X$setup$Lnodes)),2,fun,...)[updat.index] updt.Lnodes2 <- try(apply(data.frame(odata[[1]][sel_obs,X$setup$Lnodes]),2,fun,...))[updat.index] results.table[results.table$a1=="natural",paste0("L_",1)] <- updt.Lnodes results.table[results.table$a1=="observed",paste0("L_",1)] <- updt.Lnodes2 }else{if(verbose==TRUE){cat("Note: your number of Lnodes are not a multiple of your number of Ynodes.\n This is fine, but you seem to have more than one Lnode per time point, and maybe unequally distributed. \n It is difficult for me to guess which Lnodes belong 'together', and at which time point. \n Thus, no natural course values for your Lnodes are calculated. \n Use 'ret=TRUE' and calculate manually.\n")}} }} } results.table[results.table$a1=="difference","psi"] <- results.table[results.table$a1=="natural","psi"] - results.table[results.table$a1=="observed","psi"] if(X$setup$B>0){ sbdata <- lapply(sdata, '[[', 1); bfs <- ofs <- matrix(NA,ncol=length(c(X$setup$Ynodes,X$setup$Lnodes)),nrow=X$setup$B,dimnames=list(NULL,c(X$setup$Ynodes,X$setup$Lnodes))) for(b in 2:(X$setup$B+1)){ if(is.null(cond)==FALSE){sel <- with(as.data.frame(sbdata[[b]]), eval(parse(text=cond)))}else{sel<-rep(TRUE,nrow(sbdata[[b]]))} bfs[b-1,] <- apply(data.matrix(sbdata[[b]][sel,c(X$setup$Ynodes,X$setup$Lnodes)]),2,fun,...) } for(b in 2:(X$setup$B+1)){ if(is.null(cond)==FALSE){sel <- with(as.data.frame(odata[[b]]), eval(parse(text=cond)))}else{sel<-rep(TRUE,nrow(odata[[b]]))} ofs[b-1,] <- apply(data.matrix( odata[[b]][sel,c(X$setup$Ynodes,X$setup$Lnodes)]),2,fun,...) } dfs <- bfs-ofs results.table[results.table$a1=="natural",c("l95","u95")] <- t(apply(subset(bfs,select=X$setup$Ynodes),2,quantile,probs=c(0.025,0.975))) results.table[results.table$a1=="observed",c("l95","u95")] <- t(apply(subset(ofs,select=X$setup$Ynodes),2,quantile,probs=c(0.025,0.975))) results.table[results.table$a1=="difference",c("l95","u95")] <- t(apply(subset(dfs,select=X$setup$Ynodes),2,quantile,probs=c(0.025,0.975))) if(with.se==TRUE){ results.table$se<-NA results.table[results.table$a1=="natural",c("se")] <- apply(subset(bfs,select=X$setup$Ynodes),2,sd) results.table[results.table$a1=="observed",c("se")] <- apply(subset(ofs,select=X$setup$Ynodes),2,sd) results.table[results.table$a1=="difference",c("se")] <- apply(subset(dfs,select=X$setup$Ynodes),2,sd) } if(is.null(X$setup$Lnodes)==FALSE){ if(is.wholenumber(length(X$setup$Lnodes)/length(X$setup$Ynodes)) | X$setup$n.t==1){ results.table[results.table$a1=="natural",grep(":l95",colnames(results.table))] <- matrix(apply(bfs[,X$setup$Lnodes],2,quantile,probs=c(0.025)),ncol=length(X$setup$Lnodes)/X$setup$n.t,byrow=T) results.table[results.table$a1=="natural",grep(":u95",colnames(results.table))] <- matrix(apply(bfs[,X$setup$Lnodes],2,quantile,probs=c(0.975)),ncol=length(X$setup$Lnodes)/X$setup$n.t,byrow=T) results.table[results.table$a1=="observed",grep(":l95",colnames(results.table))] <- matrix(apply(ofs[,X$setup$Lnodes],2,quantile,probs=c(0.025)),ncol=length(X$setup$Lnodes)/X$setup$n.t,byrow=T) results.table[results.table$a1=="observed",grep(":u95",colnames(results.table))] <- matrix(apply(ofs[,X$setup$Lnodes],2,quantile,probs=c(0.975)),ncol=length(X$setup$Lnodes)/X$setup$n.t,byrow=T) results.table[results.table$a1=="difference",grep(":l95",colnames(results.table))] <- matrix(apply(dfs[,X$setup$Lnodes],2,quantile,probs=c(0.025)),ncol=length(X$setup$Lnodes)/X$setup$n.t,byrow=T) results.table[results.table$a1=="difference",grep(":u95",colnames(results.table))] <- matrix(apply(dfs[,X$setup$Lnodes],2,quantile,probs=c(0.975)),ncol=length(X$setup$Lnodes)/X$setup$n.t,byrow=T) if(with.se==TRUE){ results.table[results.table$a1=="natural",paste0("L_",1:(length(X$setup$Lnodes)/X$setup$n.t),":se")] <- matrix(apply(bfs[,X$setup$Lnodes],2,sd),ncol=(length(X$setup$Lnodes)/X$setup$n.t),byrow=T) results.table[results.table$a1=="observed",paste0("L_",1:(length(X$setup$Lnodes)/X$setup$n.t),":se")] <- matrix(apply(ofs[,X$setup$Lnodes],2,sd),ncol=(length(X$setup$Lnodes)/X$setup$n.t),byrow=T) results.table[results.table$a1=="difference",paste0("L_",1:(length(X$setup$Lnodes)/X$setup$n.t),":se")] <- matrix(apply(dfs[,X$setup$Lnodes],2,sd),ncol=(length(X$setup$Lnodes)/X$setup$n.t),byrow=T)} }else{ if(length(lblocks)>1 & length(unique(lblocks[-1]))==1){ results.table[results.table$a1=="natural" & results.table$time!=1,grep(":l95",colnames(results.table))] <- matrix(apply(bfs[,X$setup$Lnodes],2,quantile,probs=c(0.025)),ncol=max(lblocks),byrow=T) results.table[results.table$a1=="natural" & results.table$time!=1,grep(":u95",colnames(results.table))] <- matrix(apply(bfs[,X$setup$Lnodes],2,quantile,probs=c(0.975)),ncol=max(lblocks),byrow=T) results.table[results.table$a1=="observed" & results.table$time!=1,grep(":l95",colnames(results.table))] <- matrix(apply(ofs[,X$setup$Lnodes],2,quantile,probs=c(0.025)),ncol=max(lblocks),byrow=T) results.table[results.table$a1=="observed" & results.table$time!=1,grep(":u95",colnames(results.table))] <- matrix(apply(ofs[,X$setup$Lnodes],2,quantile,probs=c(0.975)),ncol=max(lblocks),byrow=T) results.table[results.table$a1=="difference" & results.table$time!=1,grep(":l95",colnames(results.table))] <- matrix(apply(dfs[,X$setup$Lnodes],2,quantile,probs=c(0.025)),ncol=max(lblocks),byrow=T) results.table[results.table$a1=="difference" & results.table$time!=1,grep(":u95",colnames(results.table))] <- matrix(apply(dfs[,X$setup$Lnodes],2,quantile,probs=c(0.975)),ncol=max(lblocks),byrow=T) if(with.se==TRUE){ results.table[results.table$a1=="natural" & results.table$time!=1,paste0("L_",1:max(lblocks),":se")] <- matrix(apply(bfs[,X$setup$Lnodes],2,sd),ncol=max(lblocks),byrow=T) results.table[results.table$a1=="observed" & results.table$time!=1,paste0("L_",1:max(lblocks),":se")] <- matrix(apply(ofs[,X$setup$Lnodes],2,sd),ncol=max(lblocks),byrow=T) results.table[results.table$a1=="difference" & results.table$time!=1,paste0("L_",1:max(lblocks),":se")] <- matrix(apply(dfs[,X$setup$Lnodes],2,sd),ncol=max(lblocks),byrow=T)} }else{ if(max(lblocks,na.rm=T)==1){ results.table[results.table$a1=="natural", paste(paste0("L_",1),"l95",sep=":")] <- matrix(apply(bfs[,X$setup$Lnodes],2,quantile,probs=c(0.025)),ncol=1,byrow=T)[updat.index] results.table[results.table$a1=="natural", paste(paste0("L_",1),"u95",sep=":")] <- matrix(apply(bfs[,X$setup$Lnodes],2,quantile,probs=c(0.975)),ncol=1,byrow=T)[updat.index] results.table[results.table$a1=="observed", c(paste(paste0("L_",1),"l95",sep=":"))] <- apply(ofs[,X$setup$Lnodes],2,quantile,probs=c(0.025))[updat.index] results.table[results.table$a1=="observed", c(paste(paste0("L_",1),"u95",sep=":"))] <- apply(ofs[,X$setup$Lnodes],2,quantile,probs=c(0.975))[updat.index] col.order <- c(1:grep("psi",colnames(results.table)),which(colnames(results.table)%in%c("l95","u95"))) col.order <- c(col.order,sort(grep(paste0("L_",1),colnames(results.table)))) if(with.se==TRUE){col.order<-c(col.order, which(colnames(results.table)%in%c("se")))} results.table <- results.table[,col.order] results.table[results.table$a1=="difference", paste(paste0("L_",1),"l95",sep=":")] <- apply(bfs[,X$setup$Lnodes]-ofs[,X$setup$Lnodes],2,quantile,probs=c(0.025))[updat.index] results.table[results.table$a1=="difference", paste(paste0("L_",1),"u95",sep=":")] <- apply(bfs[,X$setup$Lnodes]-ofs[,X$setup$Lnodes],2,quantile,probs=c(0.975))[updat.index] if(with.se==TRUE){ results.table[results.table$a1=="natural",paste0("L_",1,":se")] <- matrix(apply(bfs[,X$setup$Lnodes],2,sd),ncol=1,byrow=T)[updat.index] results.table[results.table$a1=="observed",paste0("L_",1,":se")] <- matrix(apply(ofs[,X$setup$Lnodes],2,sd),ncol=1,byrow=T)[updat.index] results.table[results.table$a1=="difference",paste0("L_",1,":se")] <- matrix(apply(dfs[,X$setup$Lnodes],2,sd),ncol=1,byrow=T)[updat.index]} }else{ if(verbose==TRUE){cat("Note: your number of Lnodes are not a multiple of your number of Ynodes.\n This is fine, but you seem to have more than one Lnode per time point, and maybe unequally distributed. \n It is difficult for me to guess which Lnodes belong 'together', and at which time point. \n Thus, no natural course values for your Lnodes are calculated. \n Use 'ret=TRUE' and calculate manually.\n")} }} } } } } custom.setup <- X$setup custom.setup$measure<-"custom" bsa <- ofa <- dfa <- NULL; if(with.se==TRUE){bsa<-bfs if(X$setup$i.type=="natural"){ofa<-ofs; dfa<-dfs}} results <- list(results=results.table,diagnostics=X$diagnostics,setup=custom.setup,b.results = bsa, b.results2 = list(ofa,dfa)) class(results) <- "gformula" results }
/scratch/gouwar.j/cran-all/cranData/CICI/R/custom.measure.r
fit.updated.formulas <- function(formulas,X){ all.models <- rep(list(NULL),length(formulas)) for(i in 1:length(all.models)){ if(is.null(formulas[[i]])==FALSE){ all.models[[i]] <- rep(list(NULL),length(formulas[[i]])) families <- extract.families(formulas[[i]],fdata=X) for(j in 1:length(all.models[[i]])){ if(substr(families[j],1,4)!="mult"){gf<-formula(formulas[[i]][j])}else{gf<-eval(parse(text=formulas[[i]][j]))} all.models[[i]][[j]] <- try(gam(gf,data=X,family=families[j], control=list(keepData=T)),silent=T) # note: keepData argument sometimes produced hidden(?) error message related to cache if(class(all.models[[i]][[j]])[1]=="try-error"){all.models[[i]][[j]] <- "updated model could not be fitted"} }}} all.summaries <- all.models robust.summary <- function(go){return(tryCatch(mgcv::summary.gam(go), error=function(e) "model could not be fitted"))} for(i in 1:length(all.summaries)){if(is.null(all.summaries[[i]])==FALSE){all.summaries[[i]]<-try(lapply(all.summaries[[i]],robust.summary),silent=TRUE)}} names(all.models) <- names(all.summaries) <- names(formulas) return(list(fitted.models=all.models,all.summaries=all.summaries)) }
/scratch/gouwar.j/cran-all/cranData/CICI/R/fit.updated.formulas.r
# X <- Odat[,-1] # Lnodes <- colnames(X)[sort(c(grep("L1_",colnames(X)),grep("L2_",colnames(X))))] # Ynodes <- colnames(X)[sort(c(grep("Y_",colnames(X))))] # Anodes <- colnames(X)[sort(c(grep("A_",colnames(X))))] # Cnodes <- colnames(X)[sort(c(grep("C_",colnames(X))))] # survivalY <- FALSE # a.min <- round(min(X[,grep("A_",colnames(X))],na.rm=T)-1,digits=0);a.max <- round(max(X[,grep("A_",colnames(X))],na.rm=T)+1,digits=0);n.int<-10 # abar <- seq(a.min,a.max,length.out=n.int) # could also be a matrix of size n.int times t # cbar <- "uncensored" # Yform <- Aform <- Cform <- Lform <- "GLM" # calc.support = FALSE # B = 0 # verbose=TRUE # ret=F # ncores=1 # prog=NULL # seed = NULL ### # optional: plot Strategy names for custom interventions at bottom? # 6) calc.support for custom interventions: does not make sense. Not allow? # 7) natural bounds # 8) shift # 9) SACE ; and competing() and revisit definitions of cbar # 10) visit variables gformula <- function(X, Anodes, Ynodes, Lnodes = NULL, Cnodes = NULL, abar = NULL, cbar = "uncensored", survivalY = FALSE, Yform = "GLM", Lform = "GLM", Aform = "GLM", Cform="GLM", calc.support = FALSE, B = 0, ret=FALSE, ncores=1, verbose=TRUE, seed=NULL, prog=NULL,...){ ### checks and setup ### if(is.null(prog)==FALSE){write(matrix("started with setup..."),file=paste(prog,"/progress.txt",sep=""))} model.families <- assign.family(X) # if(is.null(seed)==FALSE){set.seed(seed)} if(cbar[1]!="uncensored" & cbar[1]!="natural" & calc.support==TRUE){calc.support<-FALSE; if(verbose==TRUE){cat("Note: For custom cbar interventions no support is calculated so far \n")}} if(is.data.frame(X)==FALSE){stop("'X' (i.e. your data) needs to be a data.frame")} if(missing(Anodes)){stop("'Anodes' is missing. Please specify your intervention node(s).")} if(missing(Ynodes)){stop("'Ynodes' is missing. Please specify your outcome node(s).")} if(min(which(colnames(X)%in%Ynodes))<min(which(colnames(X)%in%Anodes))){stop("Ynodes can not occur before Anodes.\n Likely you specified pre-intervention variables as Ynode?")} if(is.character(Anodes)==FALSE & is.null(Anodes)==FALSE){stop("'Anodes' needs to be a character vector containing the respective variable names.")} if(is.character(Cnodes)==FALSE & is.null(Cnodes)==FALSE){stop("'Cnodes' needs to be a character vector containing the respective variable names.")} if(is.character(Lnodes)==FALSE & is.null(Lnodes)==FALSE){stop("'Lnodes' needs to be a character vector containing the respective variable names.")} if(is.character(Ynodes)==FALSE & is.null(Ynodes)==FALSE){stop("'Ynodes' needs to be a character vector containing the respective variable names.")} if(is.null(Lnodes)==FALSE){if(min(which(colnames(X)%in%Lnodes))<min(which(colnames(X)%in%Anodes))){ base.L <- colnames(X)[which(colnames(X)%in%Lnodes)[which(colnames(X)%in%Lnodes)<min(which(colnames(X)%in%Anodes))]] Lnodes <- Lnodes[which(!Lnodes%in%base.L)] ; if(length(Lnodes)==0){Lnodes<-NULL} if(verbose==TRUE){cat(paste("Note: Lnodes are not supposed to appear before Anodes.\n The following Lnodes are treated as pre-intervention variables:",paste(base.L,collapse=" "),"\n"))} }} if(any(colnames(X)[min(which(colnames(X)%in%Anodes)):ncol(X)]%in%c(Anodes,Lnodes,Cnodes, Ynodes)==FALSE)){ stop(paste("The following variables are part of your post-intervention data, but not specififed as L-, A-, C- or Y-node:", paste(colnames(X)[min(which(colnames(X)%in%Anodes)):ncol(X)][colnames(X)[min(which(colnames(X)%in%Anodes)):ncol(X)]%in%c(Anodes,Lnodes,Cnodes, Ynodes)==FALSE], collapse=" "))) } if(any(substr(colnames(X),1,4)=="list")){stop("Variable names that start with 'list' are not allowed. Please rename.")} if(any(c(Ynodes,Lnodes,Anodes,Cnodes)%in%colnames(X)==FALSE)){stop(paste("You have specified the following variable name(s) which are not part of the data:", paste(c(Ynodes,Lnodes,Anodes,Cnodes)[c(Ynodes,Lnodes,Anodes,Cnodes)%in%colnames(X)==FALSE],collapse=" ") ,"\n"))} if(any(sapply(X,is.ordered))){stop("Ordered variables are not allowed")} if(any(abar=="natural") & calc.support==TRUE){calc.support<-FALSE; if(verbose==TRUE){cat("Note: no support can be calculated under natural interventions.\n")}} if(is.matrix(abar)==FALSE & (is.vector(abar)&is.numeric(abar))==FALSE & any(abar=="natural")==FALSE){stop("'abar' not correctly specified. Type ?gformula for help.")} if(is.logical(survivalY)==FALSE){stop("survivalY needs to be TRUE or FALSE")} if(survivalY==TRUE){if(verbose==TRUE){if(is.null(Cnodes)){cat("Warning: you indicate that you have survival data (survivalY=T), but you have no Cnodes specified. \n")}}} if(is.character(Yform)==FALSE){stop("Yform needs to be a character vector")} if(is.character(Cform)==FALSE){stop("Cform needs to be a character vector")} if(is.character(Lform)==FALSE){stop("Lform needs to be a character vector")} if(is.character(Aform)==FALSE){stop("Aform needs to be a character vector")} if(!Yform[1]%in%c("GLM","GAM") & length(Yform)!=length(Ynodes)){stop(paste("You have provided",length(Yform),"model formula(s); but there are",length(Ynodes),"Ynodes"))} if(!Lform[1]%in%c("GLM","GAM") & length(Lform)!=length(Lnodes)){stop(paste("You have provided",length(Lform),"model formula(s); but there are",length(Lnodes),"Lnodes"))} if(!Aform[1]%in%c("GLM","GAM") & length(Aform)!=length(Anodes)){stop(paste("You have provided",length(Aform),"model formula(s); but there are",length(Anodes),"Anodes"))} if(!Cform[1]%in%c("GLM","GAM") & length(Cform)!=length(Cnodes)){stop(paste("You have provided",length(Cform),"model formula(s); but there are",length(Cnodes),"Cnodes"))} if(any(cbar!="uncensored") & any(cbar!="natural") & survivalY==TRUE){stop("custom cbar interventions for survival data currently not supported")} #check again if(is.logical(ret)==FALSE){stop("'ret' needs to either TRUE or FALSE")} if(is.logical(verbose)==FALSE){stop("'verbose' needs to either TRUE or FALSE")} if(is.numeric(ncores)==FALSE){stop("'ncores' needs to be numeric")} if(is.character(prog)==FALSE & is.null(prog)==FALSE){stop("'prog' needs to be a character vector")} if(any(model.families=="binomial")){bin.problem <- !sapply(subset(X,select=(model.families=="binomial")), is.binary) if(any(bin.problem)){if(verbose==TRUE){cat(paste("Binary variables have been recoded:",paste(names(bin.problem)[bin.problem],collapse=","),"\n"))} X[,names(bin.problem)[bin.problem]] <- data.frame(sapply(subset(X,select=names(bin.problem)[bin.problem]),binary.to.zeroone,verb=verbose)) } } if(any(substr(model.families,1,4)=="mult")){fac.problem <- !sapply(subset(X,select=(substr(model.families,1,4)=="mult")), right.coding) if(any(fac.problem)){if(verbose==TRUE){cat(paste("Categorical variables have been recoded:",paste(names(fac.problem)[fac.problem],collapse=","),"\n"))} X[,names(fac.problem)[fac.problem]] <- data.frame(sapply(subset(X,select=names(fac.problem)[fac.problem]),factor.to.numeric,verb=verbose)) } } if(verbose==TRUE){ if(any(abar=="natural")==FALSE){rel.nodes<-c(Ynodes,Lnodes)}else{rel.nodes<-c(Ynodes,Lnodes,Cnodes,Anodes)} gvar <- colnames(X)[model.families=="gaussian"]; bvar <- colnames(X)[model.families=="binomial"]; pvar <- colnames(X)[model.families=="poisson"]; mvar <- colnames(X)[substr(model.families,1,4)=="mult"] cat(paste( "Note:\n linear regression used for:", paste(gvar[gvar%in%rel.nodes],"",collapse=""),"\n", "logistic regression used for:", paste(bvar[bvar%in%rel.nodes],"",collapse=""),"\n", "Poisson regression used for:", paste(pvar[pvar%in%rel.nodes],"",collapse=""),"\n", "Multinomial regression used for:", paste(mvar[mvar%in%rel.nodes],"",collapse=""),"\n")) baseline.var <- colnames(X)[1:(max(1,which(colnames(X)%in%c((colnames(X)[colnames(X)%in%c(Anodes)])[1]))-1))] cat(paste(" Pre-Intervention variables are:",paste(baseline.var,collapse=" "),"\n\n")) } # ### matrices to store results ### n.a <- length(Anodes); n.t <- length(Ynodes); n.l <-length(Lnodes); time.points <- 1:n.t if(is.matrix(abar)==TRUE){interventions <- do.call(rbind, replicate(n.t, abar, simplify=FALSE)); i.type <- "custom"}else{ if(is.vector(abar)){interventions <- do.call(rbind, replicate(n.t, matrix(rep(abar,n.a),ncol=n.a), simplify=FALSE)); i.type<-"standard"} if(any(abar=="natural")){interventions <- matrix(c(rep("natural",n.a),rep("observed",n.a),rep("difference",n.a)),ncol=n.a,byrow=T); i.type="natural"} } if(i.type!="natural"){n.int <- dim(interventions)[1]/n.t}else{n.int <- 2} if(i.type=="natural" & calc.support==TRUE){calc.support<-FALSE; if(verbose==TRUE){cat("Note: For natural interventions no support is calculated \n")}} if(is.matrix(cbar)==FALSE){if(cbar=="uncensored"){cbar <- matrix(0,nrow=nrow(X),ncol=length(Cnodes))}} store.results <- as.data.frame(matrix(NA,nrow=(n.t)*n.int+as.numeric(i.type=="natural")*n.t,ncol=1+n.a+1)) colnames(store.results) <- c("time",paste("a",1:n.a ,sep=""),"psi") store.results$time <- rep(time.points ,each=n.int+as.numeric(i.type=="natural")) if(length(2:(n.a+1))>1){store.results[,2:(n.a+1)] <- interventions}else{store.results[,2:(n.a+1)] <- c(interventions)} if(length(Ynodes)==length(Anodes)){needed <- !(store.results$time<matrix(rep(time.points,nrow(store.results)),nrow=nrow(store.results),byrow=T))}else{ if(i.type!="natural"){needed <- matrix(which(colnames(X)%in%Anodes),nrow=n.int*length(time.points),ncol=length(which(colnames(X)%in%Anodes)),byrow=T) < matrix(rep(which(colnames(X)%in%Ynodes),each=n.int),nrow=n.int*length(time.points),ncol=n.a) }else{ needed <- matrix(which(colnames(X)%in%Anodes),nrow=(n.int+1)*length(time.points),ncol=length(which(colnames(X)%in%Anodes)),byrow=T) < matrix(rep(which(colnames(X)%in%Ynodes),each=(n.int+1)),nrow=(n.int+1)*length(time.points),ncol=n.a) } } store.results[,2:(n.a+1)][needed==FALSE] <- NA ### Parallelization & Setup if(ncores>1){ if(ncores > parallel::detectCores()){ ncores <- parallel::detectCores();if(verbose==TRUE){cat(paste("Note: You only have",ncores,"threads which can be utilized. \n"))} } if(verbose==TRUE){cat(paste("Note: You initialized parallel computation using",ncores,"threads...initializing cluster now... \n"))} cl <- parallel::makeCluster(ncores); doParallel::registerDoParallel(cl) exp.var <- c("make.formula","calculate.support", "extract.families", "projection_linear", "screen.cramersv","screen.glmnet.cramer", "censor", "adjust.sim.surv", "multiResultClass","multi.help","rmulti","rmean") }else{exp.var=NULL; foreach::registerDoSEQ()} if(i.type!="natural"){int.index <- (as.numeric(rownames(store.results[store.results$time==n.t,][1,]))):nrow(store.results)}else{int.index<- 1}#nrow(store.results)-1} sim.data <- rep(list(rep(list(NA),length(int.index))),B+1); obs.data<-rep(list(NA),B+1);obs.data[[1]]<-X if(B>0){analysis.b<- rep(list(NA),B)}else{analysis.b<-NULL} if(is.null(prog)==FALSE){write(matrix("started with g-formula calculations in original data...\n"),file=paste(prog,"/progress.txt",sep=""),append=TRUE)} # Prepare support measures, if relevant if(calc.support==TRUE){ support <- calculate.support(dat=X,A=Anodes,intervention=interventions[store.results$time==1,],...) updat.index2 <- unlist(lapply(apply(t(outer(which(colnames(X)%in%Anodes), which(colnames(X)%in%Ynodes), "<")),1,which),max)) } ### ANALYSIS ### analysis <- foreach(i = int.index, .export=exp.var) %dorng% try({ mydat <- X model.L.names <- paste("m",i,"_",colnames(mydat)[colnames(mydat)%in%c(Lnodes)],sep="") model.Y.names <- paste("m",i,"_",colnames(mydat)[colnames(mydat)%in%c(Ynodes)],sep="") model.L.Ynodes <- colnames(mydat)[colnames(mydat)%in%c(Lnodes)] model.Y.Ynodes <- colnames(mydat)[colnames(mydat)%in%c(Ynodes)] model.L.families <- model.families[colnames(mydat)%in%c(Lnodes)] model.Y.families <- model.families[colnames(mydat)%in%c(Ynodes)] n.L.models <- sum(colnames(mydat)%in%c(Lnodes)) n.Y.models <- sum(colnames(mydat)%in%c(Ynodes)) # Step 1: fit models for(j in 1:n.L.models)try({ L.data <- data.frame(subset(mydat,select=c(1:which(colnames(mydat)%in%model.L.Ynodes[j])))) assign(model.L.names[j],mgcv::gam(make.formula(L.data,approach=Lform,index=j,fam=model.L.families[j]),data=L.data,family=model.L.families[j])) },silent=TRUE) for(j in 1:n.Y.models)try({ Y.data <- data.frame(subset(mydat,select=c(1:which(colnames(mydat)%in%model.Y.Ynodes[j])))) assign(model.Y.names[j],mgcv::gam(make.formula(Y.data,approach=Yform,index=j,fam=model.Y.families[j]),data=Y.data,family=model.Y.families[j])) },silent=TRUE) if(i.type=="natural"){ model.A.names <- paste("m",i,"_",colnames(mydat)[colnames(mydat)%in%c(Anodes)],sep="") model.A.Ynodes <- colnames(mydat)[colnames(mydat)%in%c(Anodes)] model.A.families <- model.families[colnames(mydat)%in%c(Anodes)] n.A.models <- sum(colnames(mydat)%in%c(Anodes)) for(j in 1:n.A.models)try({ A.data <- data.frame(subset(mydat,select=c(1:which(colnames(mydat)%in%model.A.Ynodes[j])))) assign(model.A.names[j],mgcv::gam(make.formula(A.data,approach=Aform,index=j,fam=model.A.families[j]),data=A.data,family=model.A.families[j])) },silent=TRUE) if(is.null(Cnodes)==FALSE){ model.C.names <- paste("m",i,"_",colnames(mydat)[colnames(mydat)%in%c(Cnodes)],sep="") model.C.Ynodes <- colnames(mydat)[colnames(mydat)%in%c(Cnodes)] model.C.families <- model.families[colnames(mydat)%in%c(Cnodes)] n.C.models <- sum(colnames(mydat)%in%c(Cnodes)) for(j in 1:n.C.models)try({ C.data <- data.frame(subset(mydat,select=c(1:which(colnames(mydat)%in%model.C.Ynodes[j])))) assign(model.C.names[j],mgcv::gam(make.formula(C.data,approach=Cform,index=j,fam=model.C.families[j]),data=C.data,family=model.C.families[j])) },silent=TRUE) }} # Step 2: intervene gdata <- mydat first.treatment <- (colnames(mydat)[colnames(mydat)%in%c(Anodes)])[1] all.Anodes <- which(colnames(mydat)%in%c(Anodes)) all.Cnodes <- which(colnames(mydat)%in%c(Cnodes)) gdata[,which(colnames(mydat)%in%first.treatment):ncol(gdata)] <- NA if(i.type!="natural"){ gdata[,all.Anodes] <- (store.results[i,2:(n.a+1)])[is.na(store.results[i,2:(n.a+1)])==F] gdata[,all.Cnodes] <- cbar} # Step 3: simulate sim.nodes <- c(Lnodes,Ynodes); if(i.type=="natural"){sim.nodes <- c(sim.nodes,Anodes,Cnodes)} model.order <- paste("m",i,"_",colnames(mydat)[colnames(mydat)%in%sim.nodes],sep="") var.order <- colnames(mydat)[colnames(mydat)%in%sim.nodes] for(j in 1:length(var.order)){ sim.family <- model.families[which(colnames(mydat)%in%sim.nodes)][j] if(sim.family%in%c("gaussian","binomial")){pm <- predict(get(model.order[j]),newdata=gdata,type="response")}else{ newd <- gdata[,!apply((apply(gdata,2,is.na)),2,all)] pm <- predict(get(model.order[j]),newdata=newd,type="response")} if(sim.family=="gaussian"){gdata[,var.order[j]] <- rnorm(length(pm),mean=pm,sd=sigma(get(model.order[j]))^2)}else{ if(sim.family=="binomial"){gdata[,var.order[j]] <- rbinom(n=length(pm),1,prob=pm)}else{ if(sim.family=="poisson"){gdata[,var.order[j]] <- rpois(n=length(pm),lambda=pm)}else{ if(substr(sim.family,1,4)=="mult"){if(any(is.na(pm))){pm[is.na(pm)]<-1e08;if(verbose==TRUE){cat("\n Note: multinomial prediction led to missing values which were replaced by '0' \n")}} gdata[,var.order[j]] <- rmulti(pm)} }}} } if(is.null(Cnodes)==FALSE){gdata <- t(apply(gdata,1,censor,C.index=which(colnames(X)%in%Cnodes)))} if(survivalY==TRUE){gdata <- t(apply(gdata,1,censor,C.index=which(colnames(X)%in%Ynodes))) gdata<-adjust.sim.surv(gdata,Yn=Ynodes)} # Step 4: estimate psi if(i.type!="natural"){res.nodes<-c(Ynodes)}else{res.nodes<-c(Ynodes,Lnodes)} if(verbose==TRUE & i==min(int.index)){ if(any(apply(t(matrix(model.families,nrow=1,dimnames=list(NULL,colnames(X)))[,res.nodes]),2,substr,start=1,stop=4 )=="mult")){ cat("Note: for reporting the results, your categorical variables have been made numerical and the mean is reported.\n Use 'ret=T' and 'custom.measures()' for meaningful output.\n\n")} } results1 <- apply(subset(gdata,select=colnames(mydat)%in%res.nodes),2,mean,na.rm=TRUE) # return results results2 <- gdata results <- multiResultClass(); results$result1 <- results1; results$result2 <- results2 return(results) },silent=TRUE) ########## # Step 5: Bootstrapping if(B>0){ if(verbose==TRUE){cat("starting with bootstrapping \n")};if(is.null(prog)==FALSE){write(matrix("started with bootstrapping...\n"),file=paste(prog,"/progress.txt",sep=""),append=TRUE)} rng <- rngtools::RNGseq(B*length(int.index), seed); r <- NULL b.index <- apply(matrix(rep(1:nrow(X),B),ncol=B), 2, sample, replace=TRUE) boots <- foreach(b = 1:B) %:% foreach(i = int.index, r=rng[(b-1)*length(int.index) + 1:length(int.index)], .export=exp.var, .errorhandling="pass") %dopar% { if(is.null(seed)==FALSE){rngtools::setRNG(r)} mydat <- X[b.index[,b],] if(is.null(prog)==FALSE & i==min(int.index)){try(write(matrix(paste("performing calculations on bootstrap sample",b)),file=paste(prog,"/progress.txt",sep=""),append=T))} if(verbose==TRUE){if(i==min(int.index)){cat(paste0("...",b));if(b%%10==0){cat("\n")} }} ############################################## model.L.names <- paste("m",i,"_",colnames(mydat)[colnames(mydat)%in%c(Lnodes)],sep="") model.Y.names <- paste("m",i,"_",colnames(mydat)[colnames(mydat)%in%c(Ynodes)],sep="") model.L.Ynodes <- colnames(mydat)[colnames(mydat)%in%c(Lnodes)] model.Y.Ynodes <- colnames(mydat)[colnames(mydat)%in%c(Ynodes)] model.L.families <- model.families[colnames(mydat)%in%c(Lnodes)] model.Y.families <- model.families[colnames(mydat)%in%c(Ynodes)] n.L.models <- sum(colnames(mydat)%in%c(Lnodes)) n.Y.models <- sum(colnames(mydat)%in%c(Ynodes)) # 1 for(j in 1:n.L.models)try({ L.data <- data.frame(subset(mydat,select=c(1:which(colnames(mydat)%in%model.L.Ynodes[j])))) assign(model.L.names[j],mgcv::gam(make.formula(L.data,approach=Lform,index=j,fam=model.L.families[j]),data=L.data,family=model.L.families[j],drop.unused.levels=FALSE)) },silent=TRUE) # what if Lnodes=NULL? for(j in 1:n.Y.models)try({ Y.data <- data.frame(subset(mydat,select=c(1:which(colnames(mydat)%in%model.Y.Ynodes[j])))) assign(model.Y.names[j],mgcv::gam(make.formula(Y.data,approach=Yform,index=j,fam=model.Y.families[j]),data=Y.data,family=model.Y.families[j],drop.unused.levels=FALSE)) },silent=TRUE) if(i.type=="natural"){ model.A.names <- paste("m",i,"_",colnames(mydat)[colnames(mydat)%in%c(Anodes)],sep="") model.A.Ynodes <- colnames(mydat)[colnames(mydat)%in%c(Anodes)] model.A.families <- model.families[colnames(mydat)%in%c(Anodes)] n.A.models <- sum(colnames(mydat)%in%c(Anodes)) for(j in 1:n.A.models)try({ A.data <- data.frame(subset(mydat,select=c(1:which(colnames(mydat)%in%model.A.Ynodes[j])))) assign(model.A.names[j],mgcv::gam(make.formula(A.data,approach=Aform,index=j,fam=model.A.families[j]),data=A.data,family=model.A.families[j],drop.unused.levels=FALSE)) },silent=TRUE) if(is.null(Cnodes)==FALSE){ model.C.names <- paste("m",i,"_",colnames(mydat)[colnames(mydat)%in%c(Cnodes)],sep="") model.C.Ynodes <- colnames(mydat)[colnames(mydat)%in%c(Cnodes)] model.C.families <- model.families[colnames(mydat)%in%c(Cnodes)] n.C.models <- sum(colnames(mydat)%in%c(Cnodes)) for(j in 1:n.C.models)try({ C.data <- data.frame(subset(mydat,select=c(1:which(colnames(mydat)%in%model.C.Ynodes[j])))) assign(model.C.names[j],mgcv::gam(make.formula(C.data,approach=Cform,index=j,fam=model.C.families[j]),data=C.data,family=model.C.families[j],drop.unused.levels=FALSE)) },silent=TRUE) }} # 2 gdata <- mydat first.treatment <- (colnames(mydat)[colnames(mydat)%in%c(Anodes)])[1] all.Anodes <- which(colnames(mydat)%in%c(Anodes)) all.Cnodes <- which(colnames(mydat)%in%c(Cnodes)) gdata[,which(colnames(mydat)%in%first.treatment):ncol(gdata)] <- NA if(i.type!="natural"){ gdata[,all.Anodes] <- (store.results[i,2:(n.t+1)])[is.na(store.results[i,2:(n.t+1)])==F] gdata[,all.Cnodes] <- cbar} # 3 sim.nodes <- c(Lnodes,Ynodes); if(i.type=="natural"){sim.nodes <- c(sim.nodes,Anodes,Cnodes)} model.order <- paste("m",i,"_",colnames(mydat)[colnames(mydat)%in%sim.nodes],sep="") var.order <- colnames(mydat)[colnames(mydat)%in%sim.nodes] for(j in 1:length(var.order)){ sim.family <- model.families[which(colnames(mydat)%in%sim.nodes)][j] if(sim.family%in%c("gaussian","binomial")){pm <- predict(get(model.order[j]),newdata=gdata,type="response")}else{ newd <- gdata[,!apply((apply(gdata,2,is.na)),2,all)] pm <- predict(get(model.order[j]),newdata=newd,type="response")} if(sim.family=="gaussian"){gdata[,var.order[j]] <- rnorm(length(pm),mean=pm,sd=sigma(get(model.order[j]))^2)}else{ if(sim.family=="binomial"){gdata[,var.order[j]] <- rbinom(n=length(pm),1,prob=pm)}else{ if(sim.family=="poisson"){gdata[,var.order[j]] <- rpois(n=length(pm),lambda=pm)}else{ if(substr(sim.family,1,4)=="mult"){if(any(is.na(pm))){pm[is.na(pm)]<-1e08;if(verbose==TRUE){cat("\n Note: multinomial prediction led to missing values which were replaced by '0'")}} gdata[,var.order[j]] <- rmulti(pm)} }}} } if(is.null(Cnodes)==FALSE){gdata <- t(apply(gdata,1,censor,C.index=which(colnames(X)%in%Cnodes)))} if(survivalY==TRUE){gdata <- t(apply(gdata,1,censor,C.index=which(colnames(X)%in%Ynodes))) gdata<-adjust.sim.surv(gdata,Yn=Ynodes)} # 4 if(i.type!="natural"){res.nodes<-c(Ynodes)}else{res.nodes<-c(Ynodes,Lnodes)} results1 <- apply(subset(gdata,select=colnames(mydat)%in%res.nodes),2,mean,na.rm=TRUE) # results2 <- gdata results3 <- mydat results <- multiResultClass(); results$result1 <- results1; results$result2 <- results2; results$result3 <- results3 return(results) ############################################# } } ########## if(ncores>1){parallel::stopCluster(cl)} if(ret==TRUE){sim.data[[1]] <- lapply(analysis, '[[', 2)} analysis <- do.call("rbind",lapply(analysis, '[[', 1)) if(i.type!="natural"){store.results$psi <- c(analysis)}else{ store.results$psi[store.results$a1=="natural"] <- analysis[,Ynodes] store.results$psi[store.results$a1=="observed"] <- sapply(subset(X,select=Ynodes),rmean) if(is.null(Lnodes)==FALSE){ lblocks <- rep(NA,length(Ynodes)) for(i in 1:(length(Ynodes))){ blocks <- make.interval(which(colnames(X)%in%Ynodes)) lblocks[i] <- sum(which(colnames(X)%in%Lnodes)%in%blocks[[i]]) } if(is.wholenumber(length(Lnodes)/length(Ynodes)) | n.t==1){ store.results[store.results$a1=="natural",paste0("L_",1:(length(Lnodes)/n.t))] <- matrix(analysis[,Lnodes],byrow=T,ncol=length(Lnodes)/n.t) store.results[store.results$a1=="observed",paste0("L_",1:(length(Lnodes)/n.t))] <- matrix(sapply(subset(X,select=Lnodes),rmean),byrow=T,ncol=length(Lnodes)/n.t)}else{ if(length(lblocks)>1 & length(unique(lblocks[-1]))==1){ store.results[store.results$a1=="natural" & store.results$time!=1,paste0("L_",1:max(lblocks))] <- matrix(analysis[,Lnodes],byrow=T,ncol=max(lblocks)) store.results[store.results$a1=="observed"& store.results$time!=1,paste0("L_",1:max(lblocks))] <- matrix(sapply(subset(X,select=Lnodes),rmean),byrow=T,ncol=max(lblocks)) if(verbose==TRUE){cat("Note: it is not entirely clear to which time points your Lnodes belong to. I guessed what could make sense, but please check.\n\n")} }else{ if(max(lblocks,na.rm=T)==1){ updat.index <- unlist(lapply(apply(t(outer(which(colnames(X)%in%Lnodes), which(colnames(X)%in%Ynodes), "<")),1,which),max)) updt.Lnodes <- analysis[,Lnodes][updat.index]; updt.Lnodes2 <- sapply(subset(X,select=Lnodes),rmean)[updat.index] store.results[store.results$a1=="natural",paste0("L_",1)] <- updt.Lnodes store.results[store.results$a1=="observed",paste0("L_",1)] <- updt.Lnodes2 }else{ if(verbose==TRUE){cat("Note: your number of Lnodes are not a multiple of your number of Ynodes.\n This is fine, but you seem to have more than one Lnode per time point, and maybe unequally distributed. \n It is difficult for me to guess which Lnodes belong 'together', and at which time point. \n Thus, no natural course values for your Lnodes are calculated. \n Use 'ret=TRUE' and calculate manually.\n")} }} }} store.results[store.results$a1=="difference",grep("psi",colnames(store.results)):ncol(store.results)] <- store.results[store.results$a1=="natural",grep("psi",colnames(store.results)):ncol(store.results)] - store.results[store.results$a1=="observed",grep("psi",colnames(store.results)):ncol(store.results)] } if(B>0){ for(b in 1:B){ analysis.b[[b]] <- do.call("rbind",lapply(boots[[b]], '[[', 1)) obs.data[[b+1]] <- boots[[b]][[1]]$result3 if(ret==TRUE){for(i in 1:length(int.index)){sim.data[[b+1]][[i]]<- boots[[b]][[i]]$result2}} } boot.failure <- lapply(analysis.b,is.character) if(sum(unlist(boot.failure))>0){boots <- boots[-c(1:B)[unlist(boot.failure)]];analysis.b <- analysis.b[-c(1:B)[unlist(boot.failure)]] obs.data <- obs.data[-c(2:(B+1))[unlist(boot.failure)]]; sim.data <- sim.data[-c(2:(B+1))[unlist(boot.failure)]] if(verbose==TRUE){cat(paste("Caution:",sum(unlist(boot.failure)),"bootstrap sample(s) were removed due to errors \n"))} } newB <- B-sum(unlist(boot.failure)) if(i.type!="natural"){store.results[,c("l95","u95")] <- t(apply(matrix(unlist(analysis.b),ncol=newB),1,quantile,probs=c(0.025,0.975)))}else{ sim.results <- matrix(unlist(analysis.b),ncol=newB,dimnames=list(colnames(analysis.b[[1]]),NULL)) store.results[store.results$a1=="natural",c("l95","u95")] <- t(apply(subset(sim.results,subset=rownames(sim.results)%in%Ynodes),1,quantile,probs=c(0.025,0.975))) store.results[store.results$a1=="observed",c("l95","u95")] <- t(apply(matrix(unlist(lapply(obs.data[-1],lrmean,ind=Ynodes)),ncol=newB),1,quantile,probs=c(0.025,0.975))) store.results[store.results$a1=="difference",c("l95","u95")] <- t(apply(sim.results[rownames(sim.results)%in%Ynodes,]-matrix(unlist(lapply(obs.data[-1],lrmean,ind=Ynodes)),ncol=newB),1,quantile,probs=c(0.025,0.975))) if(is.null(Lnodes)==FALSE){ if(is.wholenumber(length(Lnodes)/length(Ynodes)) | n.t==1){ store.results[store.results$a1=="natural", paste(paste0("L_",1:(length(Lnodes)/n.t)),"l95",sep=":")] <- matrix(apply(sim.results[rownames(sim.results)%in%Lnodes,],1,quantile,probs=c(0.025)),ncol=(length(Lnodes)/n.t),byrow=T) store.results[store.results$a1=="natural", paste(paste0("L_",1:(length(Lnodes)/n.t)),"u95",sep=":")] <- matrix(apply(sim.results[rownames(sim.results)%in%Lnodes,],1,quantile,probs=c(0.975)),ncol=(length(Lnodes)/n.t),byrow=T) store.results[store.results$a1=="observed", c(paste(paste0("L_",1:(length(Lnodes)/n.t)),"l95",sep=":"))] <- matrix(t(apply(matrix(unlist(lapply(obs.data[-1],lrmean,ind=Lnodes)),ncol=newB),1,quantile,probs=c(0.025))),ncol=(length(Lnodes)/n.t),byrow=TRUE) store.results[store.results$a1=="observed", c(paste(paste0("L_",1:(length(Lnodes)/n.t)),"u95",sep=":"))] <- matrix(t(apply(matrix(unlist(lapply(obs.data[-1],lrmean,ind=Lnodes)),ncol=newB),1,quantile,probs=c(0.975))),ncol=(length(Lnodes)/n.t),byrow=TRUE) col.order <- c(1:grep("psi",colnames(store.results)),which(colnames(store.results)%in%c("l95","u95"))) for(i in 1:(length(Lnodes)/n.t)){col.order <- c(col.order,sort(grep(paste0("L_",i),colnames(store.results)))) } store.results <- store.results[,col.order] store.results[store.results$a1=="difference", paste(paste0("L_",1:(length(Lnodes)/n.t)),"l95",sep=":")] <- matrix(apply(sim.results[rownames(sim.results)%in%Lnodes,]-matrix(unlist(lapply(obs.data[-1],lrmean,ind=Lnodes)),ncol=newB),1,quantile,probs=c(0.025)),ncol=(length(Lnodes)/n.t),byrow=T) store.results[store.results$a1=="difference", paste(paste0("L_",1:(length(Lnodes)/n.t)),"u95",sep=":")] <- matrix(apply(sim.results[rownames(sim.results)%in%Lnodes,]-matrix(unlist(lapply(obs.data[-1],lrmean,ind=Lnodes)),ncol=newB),1,quantile,probs=c(0.975)),ncol=(length(Lnodes)/n.t),byrow=T) }else{ if(length(lblocks)>1 & length(unique(lblocks[-1]))==1){ store.results[store.results$a1=="natural" & store.results$time!=1, paste(paste0("L_",1:max(lblocks)),"l95",sep=":")] <- matrix(apply(sim.results[rownames(sim.results)%in%Lnodes,],1,quantile,probs=c(0.025)),ncol=max(lblocks),byrow=T) store.results[store.results$a1=="natural" & store.results$time!=1, paste(paste0("L_",1:max(lblocks)),"u95",sep=":")] <- matrix(apply(sim.results[rownames(sim.results)%in%Lnodes,],1,quantile,probs=c(0.975)),ncol=max(lblocks),byrow=T) store.results[store.results$a1=="observed" & store.results$time!=1, c(paste(paste0("L_",1:max(lblocks)),"l95",sep=":"))] <- matrix(t(apply(matrix(unlist(lapply(obs.data[-1],lrmean,ind=Lnodes)),ncol=newB),1,quantile,probs=c(0.025))),ncol=max(lblocks),byrow=TRUE) store.results[store.results$a1=="observed" & store.results$time!=1, c(paste(paste0("L_",1:max(lblocks)),"u95",sep=":"))] <- matrix(t(apply(matrix(unlist(lapply(obs.data[-1],lrmean,ind=Lnodes)),ncol=newB),1,quantile,probs=c(0.975))),ncol=max(lblocks),byrow=TRUE) col.order <- c(1:grep("psi",colnames(store.results)),which(colnames(store.results)%in%c("l95","u95"))) for(i in 1:max(lblocks)){col.order <- c(col.order,sort(grep(paste0("L_",i),colnames(store.results)))) } store.results <- store.results[,col.order] store.results[store.results$a1=="difference" & store.results$time!=1, paste(paste0("L_",1:max(lblocks)),"l95",sep=":")] <- matrix(apply(sim.results[rownames(sim.results)%in%Lnodes,]-matrix(unlist(lapply(obs.data[-1],lrmean,ind=Lnodes)),ncol=newB),1,quantile,probs=c(0.025)),ncol=max(lblocks),byrow=T) store.results[store.results$a1=="difference" & store.results$time!=1, paste(paste0("L_",1:max(lblocks)),"u95",sep=":")] <- matrix(apply(sim.results[rownames(sim.results)%in%Lnodes,]-matrix(unlist(lapply(obs.data[-1],lrmean,ind=Lnodes)),ncol=newB),1,quantile,probs=c(0.975)),ncol=max(lblocks),byrow=T) }else{ if(max(lblocks,na.rm=T)==1){ store.results[store.results$a1=="natural", paste(paste0("L_",1),"l95",sep=":")] <- matrix(apply(sim.results[rownames(sim.results)%in%Lnodes,],1,quantile,probs=c(0.025))[updat.index],ncol=1,byrow=T) store.results[store.results$a1=="natural", paste(paste0("L_",1),"u95",sep=":")] <- matrix(apply(sim.results[rownames(sim.results)%in%Lnodes,],1,quantile,probs=c(0.975))[updat.index],ncol=1,byrow=T) store.results[store.results$a1=="observed", c(paste(paste0("L_",1),"l95",sep=":"))] <- matrix(t(apply(matrix(unlist(lapply(obs.data[-1],lrmean,ind=Lnodes)),ncol=newB),1,quantile,probs=c(0.025))),1,byrow=TRUE)[,updat.index] store.results[store.results$a1=="observed", c(paste(paste0("L_",1),"u95",sep=":"))] <- matrix(t(apply(matrix(unlist(lapply(obs.data[-1],lrmean,ind=Lnodes)),ncol=newB),1,quantile,probs=c(0.975))),1,byrow=TRUE)[,updat.index] col.order <- c(1:grep("psi",colnames(store.results)),which(colnames(store.results)%in%c("l95","u95"))) col.order <- c(col.order,sort(grep(paste0("L_",1),colnames(store.results)))) store.results <- store.results[,col.order] store.results[store.results$a1=="difference", paste(paste0("L_",1),"l95",sep=":")] <- matrix(apply(sim.results[rownames(sim.results)%in%Lnodes,]-matrix(unlist(lapply(obs.data[-1],lrmean,ind=Lnodes)),ncol=newB),1,quantile,probs=c(0.025)),ncol=1,byrow=T)[updat.index,] store.results[store.results$a1=="difference", paste(paste0("L_",1),"u95",sep=":")] <- matrix(apply(sim.results[rownames(sim.results)%in%Lnodes,]-matrix(unlist(lapply(obs.data[-1],lrmean,ind=Lnodes)),ncol=newB),1,quantile,probs=c(0.975)),ncol=1,byrow=T)[updat.index,] }} } }} } if(ret==FALSE){sim.data <- obs.data <- NULL} if(i.type!="natural"){obs.data<-NULL} # Step 6: calculate support if desired if(calc.support==TRUE){ if(n.int<6 & n.int>2 & verbose==TRUE){cat(paste("Note: you have specified only",n.int,"interventions. The reported support diagnostics may not be reliable here. \n"))} # if(length(Ynodes)==length(Anodes)){ # store.results$crude_weights <- c(support$crude_weights) # store.results$cond_weights <- c(support$cond_weights)}else{ # store.results$crude_weights <- c(support$crude_weights[,updat.index2]) # store.results$cond_weights <- c(support$cond_weights[,updat.index2]) # } diagn <- list(crude_support=support$crude_support,conditional_support=support$cond_support) cn <- paste("a",1:n.a ,sep=""); if(i.type=="standard"){rn <- as.character(abar)}else{rn <- paste("Strategy",1:nrow(abar))} diagn <- lapply(diagn,as.data.frame) rownames(diagn$crude_support) <- rn; rownames(diagn$conditional_support) <- rn; colnames(diagn$crude_support) <- cn; colnames(diagn$conditional_support) <- cn }else{diagn<-NULL} if(is.null(prog)==FALSE){write(matrix("finished calculations.\n"),file=paste(prog,"/progress.txt",sep=""),append=TRUE)} # Step 7: return results res= list(results=store.results, diagnostics=diagn, simulated.data=sim.data, observed.data=obs.data, setup=list(i.type = i.type, n.t=n.t, B=B, fams=model.families, measure="default", Ynodes = Ynodes, Anodes=Anodes, Lnodes=Lnodes, Cnodes=Cnodes, abar=abar, support=calc.support, survival=survivalY) ) class(res) <- "gformula" res # }
/scratch/gouwar.j/cran-all/cranData/CICI/R/gformula.r
###################### # helper functions # ###################### ncat <- function(myvec){length(unique(myvec[is.na(myvec)==F]))} is.wholenumber <- function(myvec, tol = .Machine$double.eps^0.5){if(is.numeric(myvec)){abs(myvec - round(myvec)) < tol}else{rep(FALSE,length(myvec))}} test.binary <- function(myvec){if(ncat(myvec)==2){return(TRUE)}else{return(FALSE)}} test.poisson <- function(myvec){if(ncat(myvec)%in%seq(3,20) & all(is.wholenumber(myvec[is.na(myvec)==F])) & is.numeric(myvec[is.na(myvec)==F])){return(TRUE)}else{return(FALSE)}} test.multinomial <- function(myvec){if(ncat(myvec)%in%seq(3,9) & is.factor(myvec[is.na(myvec)==F])){return(TRUE)}else{return(FALSE)}} is.binary <- function(myvec){all(myvec[is.na(myvec)==F]%in%c(0,1))} #as.numeric.factor <- function(x) {as.numeric(levels(x))[x]} assign.family <- function(mymat,specify=NULL){ if(is.null(specify)==TRUE){ bin.ind <- pois.ind <- mult.ind <- vector(mode = "logical", length = ncol(mymat)) ncat.mat <- apply(mymat,2,ncat) for(i in 1:ncol(mymat)){bin.ind[i] <- test.binary(mymat[,i]) pois.ind[i] <- test.poisson(mymat[,i]) mult.ind[i] <- test.multinomial(mymat[,i])} fam <- rep("gaussian",ncol(mymat)) fam[bin.ind] <- "binomial" fam[pois.ind] <- "poisson" fam[mult.ind] <- paste0("multinom(K=",ncat.mat[mult.ind]-1,")") }else{fam<-specify} return(fam) } make.formula <- function(dat,approach,index,fam){ if(approach[1]%in%c("GLM","GAM")){ outc <- colnames(dat)[length(colnames(dat))] dat2 <- subset(dat,select=-length(colnames(dat))) if(length(colnames(dat))==1){covar <- "1"}else{ if(approach=="GLM"){covar <- paste(colnames(dat)[-length(colnames(dat))],collapse="+")} if(approach=="GAM"){ cts.x <- apply(dat2, 2, function(x) (length(unique(x)) > 10)) if(sum(!cts.x) > 0 & sum(cts.x) > 0){ covar <-paste(paste(paste("s(", colnames(dat2[, cts.x, drop = FALSE]), ")", sep = ""), collapse = "+"), "+", paste(colnames(dat2[, !cts.x, drop = FALSE]), collapse = "+")) } if(sum(!cts.x) > 0 & sum(cts.x) == 0){ covar <- paste(colnames(dat2[, !cts.x, drop = FALSE]), collapse = "+") } if(sum(!cts.x) == 0 & sum(cts.x) > 0){ covar <- paste(paste(paste("s(", colnames(dat2[, cts.x, drop = FALSE]), ")", sep = ""), collapse = "+")) } } } gam.formula <- paste(outc,"~",covar); gam.formula <- as.formula(gam.formula) if(substr(fam,1,4)=="mult"){ gam.formula.2 <- paste("~",as.character(gam.formula)[3]) gam.formula.3 <- paste0("as.numeric(as.character(",as.character(gam.formula)[2],"))","~",as.character(gam.formula)[3]) gam.formula <- lapply(c(gam.formula.3,rep(list(gam.formula.2),as.numeric(substr(fam,12,12))-1)),as.formula) } }else{gam.formula<-eval(parse(text=approach[index]))} return(gam.formula) } calculate.support <- function(dat,A,intervention,projection=projection_linear,...){ if(length(A)==1){size<-1; dat$placeholder <- dat[,A]; A <- c(A,"placeholder"); intervention <- cbind(intervention,intervention)}else{size<-2} # this fixes the problem when we only have one A column dat2 <- dat3 <-dat if(dim(dat[,A])[2]!=ncol(intervention)){stop("Number of columns of A and intervention don't match")} my.cuts <- matrix(NA,ncol=ncol(intervention),nrow=nrow(intervention)-1) for(i in 1:dim(my.cuts)[2]){my.cuts[,i] <- (intervention[,i][-length(intervention[,i])] + intervention[,i][-1])/2} # definition of intervals (and epsilon indirectly) for(i in 1:length(A)){ dat[,A][,i] <- cut(subset(dat,select=A)[,i],breaks=c(-Inf,my.cuts[,i],Inf)) # needs adaption if epsilon would be controlled directly } cut.intervals <- rep(list(NULL),length(A)) support.model.names <- paste("sm_",as.vector(outer(A, c(seq(1:length(intervention[,1]))), paste, sep="_")),sep="") followed_A <- rep(list(rep(list(NULL),length(A))),nrow(intervention)) followed_A_mat <- rep(list(NA),nrow(intervention)) followed_A_consec <- rep(list(NA),length(A)) for(i in 1:length(cut.intervals)){cut.intervals[[i]] <- cbind(c(-Inf,my.cuts[,i],Inf)[-length(c(-Inf,my.cuts[,i],Inf))] , c(-Inf,my.cuts[,i],Inf)[-1] )} for(i in 1:length(A)){ for(j in 1:nrow(intervention)){ followed_A[[j]][[i]] <- as.numeric((dat2[,A][,i] > cut.intervals[[i]][j,1]) & (dat2[,A][,i] < cut.intervals[[i]][j,2])) # crude }} for(i in 1:length(followed_A)){followed_A_mat[[i]]<-matrix(unlist(followed_A[[i]]),ncol=length(followed_A[[i]]))} # crude followed_A_consec <- followed_A_mat itt <- function(myvec){myvec[is.na(myvec)]<-0;for(i in 2:length(myvec)){if(myvec[i-1]==0){myvec[i]<-0}} return(myvec)} itt2 <- function(mymatrix){t(apply(mymatrix,1,itt))} followed_A_consec <- lapply(followed_A_consec,itt2) # -> if you don't follow rule at time t, you can't follow in future include_time0 <- function(mymat){return(cbind(1,mymat))} include<- lapply(followed_A_consec,include_time0) # at time 0, before intervention, everyone follows the rule # CRUCIAL: who to include in support model. Currently, only those who follow "rule" for(i in 1:length(A)){ for(j in 1:nrow(intervention)){ dat3[,A][,i] <- as.numeric((dat2[,A][,i] > cut.intervals[[i]][j,1]) & (dat2[,A][,i] < cut.intervals[[i]][j,2])) support.model <- suppressWarnings(try(glm(as.formula(paste(A[i],"~.")),data=dat3[as.logical(include[[j]][,i]),1:(which(colnames(dat3)%in%A[i]))],family=binomial),silent=TRUE)) # support given FULL past, adapt as needed if required assign(paste("sm_",A[i],"_",c(seq(1:length(intervention[,1])))[j],sep=""),support.model) dat3[,A][,i] <- dat2[,A][,i] }} include_list <- lapply(lapply(include,as.data.frame),as.list) # list, to define subset which follows the "rule" of interest all.predictions <- all.predictions.2 <- rep(list(rep(list(rep(0,nrow(dat))),length(A))),nrow(intervention)) for(i in 1:length(A)){ for(j in 1:nrow(intervention)){ pred.model <- try(get(paste("sm_",A[i],"_",c(seq(1:length(intervention[,1])))[j],sep="")),silent=TRUE) # TO DO: this model, or variable screening? if(!inherits(pred.model, "try-error")){all.predictions[[j]][[i]][as.logical(include_list[[j]][[i]])]<-suppressWarnings(try(predict(pred.model,type="response",newdata=pred.model$data),silent=TRUE))} #all.predictions[[j]][[i]][followed_A_consec[[j]][,i]==0]<- 0 #check? Should predictions for those that don't follow rule be zero? -> 13.2.21: ? }} mymean <- function(mymat){apply(mymat,2,mean)} crude_support <- matrix(unlist(lapply(followed_A_consec,mymean)),nrow=nrow(intervention),ncol=ncol(intervention),byrow=T) # CRUDE SUPPORT, i.e. ga exp.support <- function(vec){mean(vec)} mnz.list <- function(lis){lapply(lis,exp.support)} cond_support <- suppressWarnings(matrix(unlist(lapply(all.predictions,mnz.list)),nrow=nrow(intervention),ncol=ncol(intervention),byrow=T)) # suppress Warnings, as min(empty)=INf -> warning cond_support[is.na(cond_support) | is.infinite(cond_support)] <-0 cond_support <- round(t(apply(cond_support,1,cumprod)),digits=6) crude_weights <- apply(crude_support,2,projection,...) cond_weights <- apply(cond_support,2,projection,...) if(size==1){crude_support <- crude_support[,1,drop=F];cond_support <- cond_support[,1,drop=F]} return(list(crude_weights=crude_weights,cond_weights=cond_weights,crude_support=crude_support,cond_support=cond_support, gal = all.predictions)) } projection_linear <- function(x,c1=0.1,c2=0.1){ if(c1<0 | c1>1){stop("c1 needs to be in [0, 1]")} if(c2<0 | c2>1){stop("c2 needs to be in [0, 1]")} w <- x; w[x>=c2] <- 1; w[x<c2] <- c1 + ((1-c1)/(c2))*x[x<c2]; w[x==0] <- c1 return(w) } # # projection_galga <- function(gal_ga,gal,c1=0.1){ # if(c1<0 | c1>1){stop("c1 needs to be in [0, 1]")} # w <- gal_ga; w[gal>=c1] <- 1 # return(w) # } require.package <- function(package, message = paste("loading required package (", package, ") failed; please install", sep = "")){ if (!requireNamespace(package, quietly = FALSE)) { stop(message, call. = FALSE) } invisible(TRUE) } screen.cramersv <- function(dat, form, nscreen=4, cts.num=10, ...){ if(length(all.vars(formula(form))[-1])>1){ dat <- na.omit(dat[,all.vars(formula(form))] ) var_cont <- apply(dat, 2, function(x) (length(unique(x)) > cts.num)) cutf <- function(x){cut(x, unique(quantile(x, prob = c(0, 0.2, 0.4, 0.6, 0.8, 1))),include.lowest=T)} if(any(var_cont)){dat[, var_cont] <- apply(dat[, var_cont, drop = FALSE], 2, cutf)} Y <- dat[,all.vars(formula(form))[1]]; X <- dat[,all.vars(formula(form))[-1]] calc_cram_v <- function(x_var, y_var) cramer(table(y_var, x_var)) cramers_v <- apply(X, 2, calc_cram_v, y_var = Y) whichVariable <- colnames(X)[unname(rank(-cramers_v, ties.method = "random") <= nscreen)]}else{whichVariable <- NULL} return(whichVariable) } screen.glmnet.cramer <- function(dat, form, alpha = 1, pw=T, nfolds = 10, nlambda = 150, ...){ require.package("glmnet") if(substr(form,1,4)=="list"){form<-paste(strsplit(strsplit(form,"))")[[1]][1],"\\(")[[1]][4],"~",strsplit(strsplit(form,",")[[1]][1],"~")[[1]][2])} if(length(all.vars(formula(form)))>2){ dat <- na.omit(dat[,all.vars(formula(form))] ) Y <- as.vector(as.matrix(dat[,all.vars(formula(form))[1]])); X <- as.data.frame(dat[,all.vars(formula(form))[-1]]) savedat<-dat; saveX<-X myfamily <- assign.family(data.frame(dat[,all.vars(formula(form))[1]])) if(substr(myfamily,1,4)=="mult"){myfamily<-"multinomial"} # needed for factor variables later on if (ncol(X) > 26 * 27) stop("Too many variables for this screening algorithm.\n Contact Michael Schomaker for solution.") let <- c(letters, sort(do.call("paste0", expand.grid(letters, letters[1:26])))) names(X) <- let[1:ncol(X)] # factors are coded as dummies which are standardized in cv.glmnet() # intercept is not in model.matrix() because its already in cv.glmnet() is_fact_var <- sapply(X, is.factor) X <- try(model.matrix(~ -1 + ., data = X), silent = FALSE) successfulfit <- FALSE cvIndex <- rep(1:nfolds,trunc(nrow(X)/nfolds)+1)[1:nrow(X)] fitCV <- try(glmnet::cv.glmnet( x = X, y = Y, lambda = NULL, type.measure = "deviance", nfolds = nfolds, family = myfamily, alpha = alpha, nlambda = nlambda, keep = T, foldid=cvIndex ), silent = TRUE) # if no variable was selected, penalization might have been too strong, try log(lambda) if(!inherits(fitCV,"try-error")){if (all(fitCV$nzero == 0) | all(is.na(fitCV$nzero))) { fitCV <- try(glmnet::cv.glmnet( x = X, y = Y, lambda = log(fitCV$glmnet.fit$lambda + 1), type.measure = "deviance", nfolds = nfolds, family = myfamily, alpha = alpha, keep = T, foldid=cvIndex ), silent = TRUE) }} if(inherits(fitCV,"try-error")){successfulfit <- FALSE}else{successfulfit <- TRUE} whichVariable <- NULL if(successfulfit==TRUE){ coefs <- coef(fitCV$glmnet.fit, s = fitCV$lambda.min) if(myfamily!="multinomial"){if(all(coefs[-1]==0)){whichVariable<-NULL}}else{ min1<-function(vec){vec[-1]} if(all(unlist(lapply(coefs,min1))==0)){whichVariable<-NULL}} #}else{ if(myfamily!="multinomial"){var_nms <- coefs@Dimnames[[1]]}else{ var_nms <- coefs[[1]]@Dimnames[[1]] allzero<-function(vec){all(vec==0)} sel<-apply(do.call("cbind",coefs)[-1,],1,allzero) coefs <- coefs[[1]][-1];coefs[sel]<-0;coefs[!sel]<-0.1 coefs <- c(0,coefs) } # Instead of Group Lasso: # If any level of a dummy coded factor is selected, the whole factor is selected if (any(is_fact_var)) { nms_fac <- names(which(is_fact_var)) is_selected <- coefs[-1] != 0 # drop intercept # model.matrix adds numbers to dummy coded factors which we need to get rid of var_nms_sel <- gsub("[^::a-z::]", "", var_nms[-1][is_selected]) sel_fac <- nms_fac[nms_fac %in% var_nms_sel] sel_numer <- var_nms_sel[!var_nms_sel %in% sel_fac] all_sel_vars <- c(sel_fac, sel_numer) whichVariable <- names(is_fact_var) %in% all_sel_vars } else { # metric variables only whichVariable <- coefs[-1] != 0 } whichVariable <- colnames(saveX)[whichVariable] } #} if(is.null(whichVariable)){whichVariable<-screen.cramersv(dat=savedat,form=form) if(pw==T){cat("Lasso failed and screening was based on Cramer's V (for ",form,")\n")}} }else{whichVariable<-NULL} return(whichVariable) } censor <- function(vec,C.index){ start.cens <- (which(vec==1)[which(vec==1)%in%C.index])[1] if(is.na(start.cens)==FALSE){if(start.cens!=length(vec)){vec[(start.cens+1):length(vec)] <- NA}} return(vec) } adjust.sim.surv <- function(mat,Yn){ #improve for-loop mymin <- function(vec){if(length(vec)>0){return(min(vec))}else{return(NA)}} find.first <- function(vec){mymin(which(vec==1))} first.event <- apply(mat[,Yn],1,find.first) censor.at <- Yn[first.event] position <- rep(NA,nrow(mat)) for(i in 1:nrow(mat)){if(length(which(censor.at[i]==colnames(mat)))>0){position[i]<-which(censor.at[i]==colnames(mat))}} for(i in 1:nrow(mat)){ if(is.na(position[i])==FALSE){ if(position[i]+1<=ncol(mat)){ mat[i,(position[i]+1):ncol(mat)]<-NA mat[i,Yn[(min(first.event[i]+1,length(Yn))):length(Yn)]]<-1 } }} return(mat) } multiResultClass <- function(result1=NULL,result2=NULL) { me <- list( result1 = result1, result2 = result2 ) class(me) <- append(class(me),"multiResultClass") return(me) } multi.help <- function(vec){which(t(rmultinom(1,1,vec))==1)-1} rmulti <- function(probmat){apply(probmat,1,multi.help)} prop <- function(vec,categ=0){vec <- na.omit(vec);sum(vec==categ)/length(vec)} rmean <- function(vec){ vec <- na.omit(vec) if(!is.factor(vec)){mean(vec)}else{mean(as.numeric(as.character(vec)))}} lrmean <- function(mmat,ind){sapply(subset(mmat,select=ind),rmean)} factor.to.numeric <- function(vec,verb){nf <- levels(na.omit(vec)) nums <- 0:(length(nf)-1) code <- data.frame(nf,nums) recoding <- paste(apply(code,1,paste,collapse=" replaced by "),collapse=" ; ") vec2 <- rep(NA,length(vec)) for(i in 1:length(nums)){vec2[vec==code$nf[i]]<-code$nums[i]} if(verb==TRUE){cat(paste(recoding,"\n"))} return(as.numeric(vec2)) } binary.to.zeroone<-function(vec,verb){nf <- unique(na.omit(vec)) nums <- c(0,1) code <- data.frame(nf,nums) recoding <- paste(apply(code,1,paste,collapse=" replaced by "),collapse=" ; ") vec2 <- rep(NA,length(vec)) for(i in 1:length(nums)){vec2[vec==code$nf[i]]<-code$nums[i]} if(verb==TRUE){cat(paste(recoding,"\n"))} return(vec2) } right.coding<-function(vec){ uv <- unique(na.omit(vec)) pc <- factor(0:(length(uv)-1)) if(identical(levels(uv),levels(pc))){return(TRUE)}else{return(FALSE)} } extract.families <- function(forms=NULL,fdata){ if(is.null(forms)==FALSE){ fams <- matrix(assign.family(fdata),nrow=1,dimnames=list(NULL,colnames(fdata))) outcomes <- model.fams <- rep(NA,length(forms)) for(i in 1:length(forms)){outcomes[i]<- strsplit(forms[i],"~")[[1]][1]} for(i in 1:length(outcomes)){if(nchar(outcomes[i])>4){if(substr(outcomes[i],1,4)=="list"){outcomes[i]<-strsplit(strsplit(outcomes[i],"\\(")[[1]][4],"\\)")[[1]][1]}}} #outcomes <- gsub('.{1}$', '', outcomes) for(i in 1:length(forms)){model.fams[i] <- fams[which(colnames(fams)%in%outcomes[i])]} return(model.fams) }else{return(NULL)} } missing.data <- function(ml){any(lapply(ml,is.matrix)==FALSE)} cramer<-function(mt){ allterms <- matrix(NA,nrow=nrow(mt),ncol=ncol(mt)) n <- sum(mt) for(i in 1:nrow(mt)){ for(j in 1:ncol(mt)){ allterms[i,j]<- ((mt[i,j]- ((sum(mt[i,])*sum(mt[,j]))/(n)) )^2)/(((sum(mt[i,])*sum(mt[,j]))/(n))) }} cramer <- sqrt(sum(allterms)/(n*(min(nrow(mt),ncol(mt))-1))) cramer } make.interval <- function(vec){ ni <- length(vec) intvs <- rep(list(NA),ni) nv <- c(0,vec) for(i in 1:ni){intvs[[i]] <- seq(nv[i],nv[i+1])} intvs } .onAttach <- function(libname = find.package("CICI"), pkgname = "CICI") { packageStartupMessage("The manual for this package will be available soon. \n Type ?CICI for a first overview.") } mi.inference <- function (est, std.err, confidence = 0.95){ qstar <- est[[1]] for (i in 2:length(est)) { qstar <- cbind(qstar, est[[i]]) } qbar <- apply(qstar, 1, mean) u <- std.err[[1]] for (i in 2:length(std.err)) { u <- cbind(u, std.err[[i]]) } u <- u^2 ubar <- apply(u, 1, mean) bm <- apply(qstar, 1, var) m <- dim(qstar)[2] tm <- ubar + ((1 + (1/m)) * bm) rem <- (1 + (1/m)) * bm/ubar nu <- (m - 1) * (1 + (1/rem))^2 alpha <- 1 - (1 - confidence)/2 low <- qbar - qt(alpha, nu) * sqrt(tm) up <- qbar + qt(alpha, nu) * sqrt(tm) result <- list(est = qbar, std.err = sqrt(tm), df = nu, lower = low, upper = up, r = rem) result } correct.models <- list( "L"=c("adherence.1 ~ comorbidity.0 + efv.0", "weight.1 ~ sex + log_age", "comorbidity.1 ~ log_age + weight.0 + comorbidity.0", "list(as.numeric(as.character(dose.1)) ~ I(sqrt(weight.1)) + dose.0, ~ I(sqrt(weight.1)) + dose.0, ~ I(sqrt(weight.1)) + dose.0)", "adherence.2 ~ comorbidity.1 + adherence.1 + efv.1", "weight.2 ~ weight.1 + comorbidity.1", "comorbidity.2 ~ log_age + weight.1 + comorbidity.1", "list(as.numeric(as.character(dose.2)) ~ I(sqrt(weight.2)) + dose.1, ~ I(sqrt(weight.2)) + dose.1, ~ I(sqrt(weight.2)) + dose.1)", "adherence.3 ~ comorbidity.2 + adherence.2 + efv.2", "weight.3 ~ weight.2 + comorbidity.2", "comorbidity.3 ~ log_age + weight.2 + comorbidity.2", "list(as.numeric(as.character(dose.3)) ~ I(sqrt(weight.3)) + dose.2, ~ I(sqrt(weight.3)) + dose.2, ~ I(sqrt(weight.3)) + dose.2)", "adherence.4 ~ comorbidity.3 + adherence.3 + efv.3", "weight.4 ~ weight.3 + comorbidity.3", "comorbidity.4 ~ log_age + weight.2 + comorbidity.2", "list(as.numeric(as.character(dose.4)) ~ I(sqrt(weight.4)) + dose.3, ~ I(sqrt(weight.4)) + dose.3, ~ I(sqrt(weight.4)) + dose.3)" ), "A"=c("efv.0 ~ log_age + metabolic*dose.0", "efv.1 ~ log_age + dose.0 + metabolic*adherence.1", "efv.2 ~ log_age + dose.0 + metabolic*adherence.2*dose.1", "efv.3 ~ log_age + dose.0 + metabolic*adherence.3*dose.2", "efv.4 ~ log_age + dose.0 + metabolic*adherence.4*dose.3" ), "Y"=c("VL.0 ~ I(sqrt(efv.0))", "VL.1 ~ I(sqrt(efv.1)) + comorbidity.0", "VL.2 ~ I(sqrt(efv.2)) + comorbidity.1", "VL.3 ~ I(sqrt(efv.3)) + comorbidity.2", "VL.4 ~ I(sqrt(efv.4)) + comorbidity.3" ) )
/scratch/gouwar.j/cran-all/cranData/CICI/R/helper.r
make.model.formulas <- function(X, Ynodes=NULL, Lnodes=NULL, Cnodes=NULL, Anodes=NULL, survival=FALSE, evaluate=FALSE){ if(survival==T & is.null(Cnodes)){stop("If you specify survival=T, then Cnodes can not be NULL")} m.model.families <- assign.family(X) A.model.formulas.m <- C.model.formulas.m <- L.model.formulas.m <- Y.model.formulas.m <-NULL fitted.models <- fitted.model.summary <- NULL fitted.model.summary.L <- fitted.model.summary.Y <- fitted.model.summary.A <- fitted.model.summary.C <- NULL m.model.A.names <- m.model.C.names <- m.model.Y.names <- m.model.L.names <- "ph"; ph <- NULL if(is.null(Lnodes)==FALSE){ m.model.L.names <- paste("m","_",colnames(X)[colnames(X)%in%c(Lnodes)],sep="") m.model.L.Ynodes <- colnames(X)[colnames(X)%in%c(Lnodes)] m.model.L.families <- m.model.families[colnames(X)%in%c(Lnodes)] n.L.models.m <- sum(colnames(X)%in%c(Lnodes)) L.model.formulas.m <- c(rep(NA,n.L.models.m)) for(j in 1:n.L.models.m){ L.data <- subset(X,select=c(1:which(colnames(X)%in%m.model.L.Ynodes[j]))) if(survival==T |(survival==F & is.null(Cnodes)==F)){ siC <- which(colnames(L.data)%in%Cnodes[1:j]); if(length(siC)==0){siC<-NULL} if(survival==T){siY <- which(colnames(L.data)%in%Ynodes[1:j]); if(length(siY)==0){siY<-NULL}}else{siY<-NULL} si <- c(siY,siC) if(is.null(si)==FALSE){L.data <- subset(L.data, select=-si)} } L.model.formulas.m[j] <- Reduce(paste, deparse(make.formula(L.data,approach="GLM",fam=m.model.L.families[j]))) if(evaluate==TRUE){assign(m.model.L.names[j],mgcv::gam(make.formula(L.data,approach="GLM",fam=m.model.L.families[j]),data=L.data,control=list(keepData=T),family=m.model.L.families[j]))} } } if(is.null(Ynodes)==FALSE){ m.model.Y.names <- paste("m","_",colnames(X)[colnames(X)%in%c(Ynodes)],sep="") m.model.Y.Ynodes <- colnames(X)[colnames(X)%in%c(Ynodes)] m.model.Y.families <- m.model.families[colnames(X)%in%c(Ynodes)] n.Y.models.m <- sum(colnames(X)%in%c(Ynodes)) Y.model.formulas.m <- c(rep(NA,n.Y.models.m)) for(j in 1:n.Y.models.m){ Y.data <- subset(X,select=c(1:which(colnames(X)%in%m.model.Y.Ynodes[j]))) if(survival==T |(survival==F & is.null(Cnodes)==F)){ if(survival==T){if(j>1){siY <- which(colnames(Y.data)%in%Ynodes[1:(j-1)])}else{siY<-NULL}}else{siY<-NULL} siC <- which(colnames(Y.data)%in%Cnodes[1:j]); if(length(siC)==0){siC<-NULL} si <- c(siY,siC) if(is.null(si)==FALSE){Y.data <- subset(Y.data, select=-si)} } Y.model.formulas.m[j] <- Reduce(paste, deparse(make.formula(Y.data,approach="GLM",fam=m.model.Y.families[j]))) if(evaluate==TRUE){assign(m.model.Y.names[j],mgcv::gam(make.formula(Y.data,approach="GLM",fam=m.model.Y.families[j]),data=Y.data, control=list(keepData=T),family=m.model.Y.families[j]))} } } if(is.null(Anodes)==FALSE){ m.model.A.names <- paste("m","_",colnames(X)[colnames(X)%in%c(Anodes)],sep="") m.model.A.Ynodes <- colnames(X)[colnames(X)%in%c(Anodes)] m.model.A.families <- m.model.families[colnames(X)%in%c(Anodes)] n.A.models.m <- sum(colnames(X)%in%c(Anodes)) A.model.formulas.m <- c(rep(NA,n.A.models.m)) for(j in 1:n.A.models.m){ A.data <- subset(X,select=c(1:which(colnames(X)%in%m.model.A.Ynodes[j]))) if(survival==T |(survival==F & is.null(Cnodes)==F)){ siC <- which(colnames(A.data)%in%Cnodes[1:j]); if(length(siC)==0){siC<-NULL} if(survival==T){siY <- which(colnames(A.data)%in%Ynodes[1:j]); if(length(siY)==0){siY<-NULL}}else{siY<-NULL} si <- c(siY,siC) if(is.null(si)==FALSE){A.data <- subset(A.data, select=-si)} } A.model.formulas.m[j] <- Reduce(paste, deparse(make.formula(A.data,approach="GLM",fam=m.model.A.families[j]))) if(evaluate==TRUE){assign(m.model.A.names[j],mgcv::gam(make.formula(A.data,approach="GLM",fam=m.model.A.families[j]),data=A.data,family=m.model.A.families[j]))} } } if(is.null(Cnodes)==FALSE){ m.model.C.names <- paste("m","_",colnames(X)[colnames(X)%in%c(Cnodes)],sep="") m.model.C.Ynodes <- colnames(X)[colnames(X)%in%c(Cnodes)] m.model.C.families <- m.model.families[colnames(X)%in%c(Cnodes)] n.C.models.m <- sum(colnames(X)%in%c(Cnodes)) C.model.formulas.m <- c(rep(NA,n.C.models.m)) for(j in 1:n.C.models.m){ C.data <- subset(X,select=c(1:which(colnames(X)%in%Cnodes[j]))) if(survival==T){ if(j>1){siC <- which(colnames(C.data)%in%Cnodes[1:(j-1)])}else{siC<-NULL} siY <- which(colnames(C.data)%in%Ynodes[1:j]); if(length(siY)==0){siY<-NULL} si <- c(siY,siC) if(is.null(si)==FALSE){C.data <- subset(C.data, select=-si)} }else{ if(j>1){si <- which(colnames(C.data)%in%Cnodes[1:(j-1)])}else{si<-NULL} if(is.null(si)==FALSE){C.data <- subset(C.data, select=-si)} } C.model.formulas.m[j] <- Reduce(paste, deparse(make.formula(C.data,approach="GLM",fam=m.model.C.families[j]))) if(evaluate==TRUE){assign(m.model.C.names[j],mgcv::gam(make.formula(C.data,approach="GLM",fam=m.model.C.families[j]),data=C.data,family=m.model.C.families[j]))} }} model.names <- list(Lnames=L.model.formulas.m,Ynames=Y.model.formulas.m,Anames=A.model.formulas.m,Cnames=C.model.formulas.m) for(i in 1:4){if(is.null(model.names[[i]])==FALSE){for(j in 1:length(model.names[[i]])){model.names[[i]][j]<-gsub(" ", "",model.names[[i]][j])}}} if(evaluate==TRUE){fitted.models <- list(fitted.L=mget(m.model.L.names),fitted.Y=mget(m.model.Y.names), fitted.A=mget(m.model.A.names),fitted.C=mget(m.model.C.names))} if(is.null(Lnodes)==FALSE){if(evaluate==TRUE){fitted.model.summary.L <- lapply(fitted.models$fitted.L,summary)}} if(is.null(Ynodes)==FALSE){if(evaluate==TRUE){fitted.model.summary.Y <- lapply(fitted.models$fitted.Y,summary)}} if(is.null(Anodes)==FALSE){if(evaluate==TRUE){fitted.model.summary.A <- lapply(fitted.models$fitted.A,summary)}} if(is.null(Cnodes)==FALSE){if(evaluate==TRUE){fitted.model.summary.C <- lapply(fitted.models$fitted.C,summary)}} fitted.model.summary <- list(L=fitted.model.summary.L,Y=fitted.model.summary.Y,A=fitted.model.summary.A,C=fitted.model.summary.C) return(list(model.names=model.names,fitted.models=fitted.models,fitted.model.summary=fitted.model.summary)) }
/scratch/gouwar.j/cran-all/cranData/CICI/R/make.model.formulas.r
mi.boot <- function(x,fun,cond=NULL,pooled=FALSE,...){ # checks if(any(unlist(lapply(x,class))!="gformula")){stop("Please provide a list of objects of class 'gformula'")} get.type <- function(xx){xx$setup$i.type} if(x[[1]]$setup$measure=="custom"){stop("Don't use 'mi.boot' on results produced by 'custom.measure'.\n Use mi.boot's options 'fun' and 'cond' to produce custom measures.\n")} if(is.list(x)==FALSE | (is.list(x)==TRUE & length(x)==1)){stop("Please provide a list (of length>1)")} i.type <- unlist(lapply(x,get.type)) if(missing(fun)){stop("You have to supply 'fun'. \n If you are interested in the expectation, simply use 'fun=mean'.\n (and possibly pass on the option 'na.rm=T.')")} if(length(unique(i.type))>1){stop("You can only combine results of the same type")}else{i.type <- i.type[1]} if(is.null(x[[1]]$simulated.data)){stop("Set 'ret=TRUE' in gformula() to work with custom measures.")} # table mi.table <- x[[1]]$results # produce custom measure and calculate bootstrap s.e. if(x[[1]]$setup$B>0){x <- lapply(x,custom.measure,fun=fun,cond=cond,with.se=TRUE,verbose=FALSE,...)}else{ x <- lapply(x,custom.measure,fun=fun,cond=cond,with.se=FALSE,verbose=FALSE,...) } # psi getpsi <- function(xx){xx$results$psi} mi.psi <- apply(do.call("rbind",lapply(x,getpsi)),2,mean) mi.table$psi <- mi.psi # covariates if abar="natural" if(i.type=="natural" & is.null(x[[1]]$setup$Lnodes)==FALSE){ rel.L.cols <- colnames(x[[1]]$results)[!grepl(":",colnames(x[[1]]$results)) & grepl("L_",colnames(x[[1]]$results))] if(length(rel.L.cols)>0){ get.Ls <- function(xx){c(xx$results[,rel.L.cols])} mi.L <- apply(do.call("rbind",lapply(x,get.Ls)),2,mean) mi.table[,rel.L.cols] <- mi.L }else{x[[1]]$setup$Lnodes<-NULL;cat("natural course scenario for Lnodes not possible because values have not been provided\n")} # fix in future: with unequally distributed L's over time gformula struggles, and thus omit natural course for L's for now } # confidence intervals get.B <- function(xx){xx$setup$B} all.B <- unlist(lapply(x,get.B)) if(all(all.B>1)){ if(pooled==FALSE){ getse <- function(xx){xx$results$se} mi.results <- mi.inference(est=lapply(x,getpsi),std.err=lapply(x,getse)) mi.table$l95 <- mi.results$lower; mi.table$u95 <- mi.results$upper if(i.type=="natural" & is.null(x[[1]]$setup$Lnodes)==FALSE){ getse.L <- function(xx){L.index <- grep(":se",colnames(x[[1]]$results)); c(xx$results[,L.index]) } mi.results.L <- mi.inference(est=lapply(x,get.Ls),std.err=lapply(x,getse.L)) res.index <- grep(":l95",colnames(x[[1]]$results)); res.index2 <- grep(":u95",colnames(x[[1]]$results)) mi.table[,res.index] <- mi.results.L$lower mi.table[,res.index2]<- mi.results.L$upper } }else{ get.bs <- function(xx){xx$b.results} if(i.type!="natural"){ mi.results <- apply(do.call("rbind",lapply(x,get.bs)),2,quantile,probs=c(0.025,0.975)) mi.table$l95 <- mi.results[1,]; mi.table$u95 <- mi.results[2,] }else{ mi.results <- apply(do.call("rbind",lapply(x,get.bs)),2,quantile,probs=c(0.025,0.975)) mi.table$l95[mi.table$a1=="natural"] <- mi.results[1,colnames(mi.results)%in%x[[1]]$setup$Ynodes] mi.table$u95[mi.table$a1=="natural"] <- mi.results[2,colnames(mi.results)%in%x[[1]]$setup$Ynodes] get.bs.obs <- function(xx){xx$b.results2[[1]]} get.bs.diff <- function(xx){xx$b.results2[[2]]} mi.results2 <- apply(do.call("rbind",lapply(x,get.bs.obs)),2,quantile,probs=c(0.025,0.975)) mi.results3 <- apply(do.call("rbind",lapply(x,get.bs.diff)),2,quantile,probs=c(0.025,0.975)) mi.table$l95[mi.table$a1=="observed"] <- mi.results2[1,colnames(mi.results)%in%x[[1]]$setup$Ynodes] mi.table$u95[mi.table$a1=="observed"] <- mi.results2[2,colnames(mi.results)%in%x[[1]]$setup$Ynodes] mi.table$l95[mi.table$a1=="difference"] <- mi.results3[1,colnames(mi.results)%in%x[[1]]$setup$Ynodes] mi.table$u95[mi.table$a1=="diffreence"] <- mi.results3[2,colnames(mi.results)%in%x[[1]]$setup$Ynodes] if(is.null(x[[1]]$setup$Lnodes)==FALSE){ res.index <- grep(":l95",colnames(x[[1]]$results)); res.index2 <- grep(":u95",colnames(x[[1]]$results)) mi.table[,c(res.index,res.index2)]<-NA cat("Still to implement CI's for L's \n") } } } } # weights & diagnostics if(any(grepl("crude_",colnames(x[[1]]$results)))){ getweights <- function(xx){unlist(subset(xx$results,select=c("crude_weights","cond_weights")))} mi.table[,c("crude_weights","cond_weights")] <- apply(do.call("rbind",lapply(x,getweights)),2,mean) } mi.diagnostics<-NULL if(is.null(x[[1]]$diagnostics)==FALSE){ getdiag1 <- function(xx){xx$diagnostics$crude_support} getdiag2 <- function(xx){xx$diagnostics$conditional_support} mi.crude <- x[[1]]$diagnostics$crude_support; mi.crude[1:nrow(mi.crude),1:ncol(mi.crude)] <- apply(do.call("rbind",lapply(lapply(x,getdiag1),unlist)),2,mean) mi.conditional <- x[[1]]$diagnostics$conditional_support; mi.conditional[1:nrow(mi.conditional),1:ncol(mi.conditional)] <- apply(do.call("rbind",lapply(lapply(x,getdiag2),unlist)),2,mean) mi.diagnostics <- list( crude_support = mi.crude, conditional_support = mi.conditional ) } #return appropriate object of class gformula results <- list(results=mi.table,diagnostics=mi.diagnostics,setup=x[[1]]$setup) class(results) <- "gformula" results }
/scratch/gouwar.j/cran-all/cranData/CICI/R/mi.boot.r
model.formulas.update <- function(formulas,X,screening=screen.glmnet.cramer,with.s=FALSE,by=NA,...){ if(is.list(formulas)==FALSE){stop("Please provide an appropriate list (see help file)\n")} selected.variables <- rep(list(NULL),length(formulas)); sf <- screening for(i in 1:length(formulas)){ if(is.null(formulas[[i]])==FALSE){ selected.variables[[i]] <- rep(list(NA),length(formulas[[i]])) for(j in 1:length(formulas[[i]])){ sv <- try(sf(X,formulas[[i]][j],...),silent=T) if(is.null(sv)==FALSE & !inherits(sv, "try-error")){selected.variables[[i]][[j]] <- sv} if(inherits(sv, "try-error")){selected.variables[[i]][[j]] <- NA} }}} new.formulas <- formulas for(i in 1:length(new.formulas)){ if(is.null(new.formulas[[i]])==FALSE){ for(j in 1:length(new.formulas[[i]])){ covar <- "1" if(is.na(selected.variables[[i]][[j]][1])==FALSE){ if(with.s==FALSE){covar <- paste(selected.variables[[i]][[j]],collapse=" + ")}else{ X2 <- subset(X,select=selected.variables[[i]][[j]]) cts.x <- apply(X2, 2, function(x) (length(unique(x)) > 10)) if(sum(!cts.x) > 0 & sum(cts.x) > 0){ covar <-paste(paste(paste("s(", colnames(X2[, cts.x, drop = FALSE]), ", by=", by, ")", sep = ""), collapse = " + "), "+", paste(colnames(X2[, !cts.x, drop = FALSE]), collapse = " + ")) } if(sum(!cts.x) > 0 & sum(cts.x) == 0){ covar <- paste(colnames(X2[, !cts.x, drop = FALSE]), collapse = " + ") } if(sum(!cts.x) == 0 & sum(cts.x) > 0){ covar <- paste(paste(paste("s(", colnames(X2[, cts.x, drop = FALSE]), ", by=", by, ")", sep = ""), collapse = " + ")) }} } if(substr(new.formulas[[i]][j],1,4)=="list"){new.formulas[[i]][j]<-paste(strsplit(strsplit(new.formulas[[i]][j],"))")[[1]][1],"\\(")[[1]][4],"~",strsplit(strsplit(new.formulas[[i]][j],",")[[1]][1],"~")[[1]][2])} new.formulas[[i]][j] <- paste(all.vars(formula(new.formulas[[i]][j]))[1],"~",covar) if(substr(formulas[[i]][j],1,4)=="list"){ gam.formula.2 <- paste("~",strsplit(new.formulas[[i]][j],"~")[[1]][2]) gam.formula.3 <- paste0("as.numeric(as.character(",strsplit(new.formulas[[i]][j],"~")[[1]][1],"))",gam.formula.2) new.formulas[[i]][j] <- paste0("list(",paste(unlist(c(gam.formula.3,rep(list(gam.formula.2),length(strsplit(formulas[[i]][j],",")[[1]])-1))),collapse=","),")") } } }} for(i in 1:length(new.formulas)){if(is.null(new.formulas[[i]])==FALSE){for(j in 1:length(new.formulas[[i]])){new.formulas[[i]][j]<-gsub(" ", "",new.formulas[[i]][j])}}} return(new.formulas) }
/scratch/gouwar.j/cran-all/cranData/CICI/R/model.formulas.update.r
model.update <- function(gam.object,form){ if(gam.object$family$family=="multinom"){stop("Please update multinomial models manually.\n")}else{ return(update(gam.object,form,data=gam.object$data,family=gam.object$family$family))} }
/scratch/gouwar.j/cran-all/cranData/CICI/R/model.update.r
plot.gformula <- function(x, msm.method=c("line","loess","gam","none"), CI=FALSE, time.points=NULL, cols=NULL, weight=NULL, survival=FALSE, variable="psi", difference=FALSE, ...){ a1<-psi<-l95<-u95<-relvar<-Strategy<-sel.l95<-sel.u95<-NULL gobject <- x msm.method <- match.arg(msm.method) if(msm.method=="none" & is.null(weight)==FALSE){stop("For weighted MSM estimation, `msm.method' cannot be `none'")} if(gobject$setup$i.type=="natural"){if(length(unique(gobject$results$time))==1){stop("Natural course scenario for 1 time point can not be plotted. \n Simply look at the results table.")}} if(CI==TRUE & gobject$setup$B==0){CI<-FALSE;cat("No confidence intervals printed because B=0")} if(survival==T & gobject$setup$survival==F){survival<-F; cat("Note: survival curves can only displayed for survival setups. Thus survival is set back to FALSE." )} if(survival==T & gobject$setup$n.t==1){survival<-F; cat("Note: survival curves can only displayed for >1 time points." )} if(survival==T & length(time.points)==1){stop("Survival curves can only displayed for >1 time points." )} if(survival==T & msm.method!="none"){cat("Note: no step functions provided. \n Use msm.method='none' for plot without connecting lines. \n")} if(all(gobject$setup$abar%in%c(0,1))){bin.int=TRUE}else{bin.int <- FALSE} n.t <- gobject$setup$n.t if(bin.int==TRUE & n.t==1){gobject$setup$i.type<-"standard"; msm.method<-"none"} if(bin.int==TRUE & n.t>1){gobject$setup$i.type<-"custom"} if(survival==T){gobject$setup$i.type<-"custom"} results <- gobject$results if(is.null(time.points)==FALSE){results<-results[results$time%in%time.points,]} mycolors <- c("black", "orangered3","dodgerblue4", "springgreen3","gold","greenyellow","purple",sample(rainbow(25))) #if(is.null(weight)==FALSE){if(weight=="crude"){weight<-results$crude_weights}else{if(weight=="cond"){weight<-results$cond_weights}}} ##### if(gobject$setup$i.type=="standard"){ if(is.null(cols)==FALSE){if(length(cols)!=length(unique(results$time))){stop(paste("Provide",length(unique(results$time)),"colours under `cols' (not more, not less - or use default colours)"))}} if(is.null(cols)){cols<-mycolors[1:length(unique(results$time))]} gg1 <- ggplot(results, aes(x=a1,y=psi,col=as.factor(time))) + geom_point(size=1.75) + theme_bw() if(msm.method=="none"){gg2<-gg1} if(msm.method=="line" & bin.int==FALSE){gg2<-gg1+ geom_line(linetype=3, linewidth=1.05)} if(msm.method=="loess" | msm.method=="gam"){mymethod=paste("(estimated with ",msm.method,")",sep="") gg2<- gg1+ geom_smooth(method = msm.method, se = FALSE, aes(weight=weight))}else{mymethod=NULL} if(CI==TRUE & bin.int==FALSE){gg2 <- gg2 + geom_ribbon(aes(ymin = l95, ymax = u95, fill=as.factor(time)), alpha=0.1,show.legend = FALSE)} if(CI==TRUE & bin.int==TRUE & n.t==1){gg2 <- gg2 + geom_pointrange(aes(ymin = l95, ymax = u95))} gg3 <- gg2 + scale_color_manual(values = cols) + scale_fill_manual(values = cols) + scale_x_continuous("Intervention", breaks=round(c(seq(min(results$a1),max(results$a1),length.out=length(results$a1[results$time==min(results$time)]))),digits=1) ) + scale_y_continuous(expression(psi)) + guides(fill = guide_legend(keywidth = 2, keyheight = 2, title="Time")) + ggtitle(paste("Dose-response curves",mymethod)) + theme(axis.title.x = element_text(size=13), axis.text.x = element_text(size=13),axis.title.y = element_text(size=13, angle = 90), axis.text.y = element_text(size=13), legend.text = element_text(size=13), legend.title = element_text(size=13, face = "bold", hjust = 0),legend.position = "bottom") + guides(col=guide_legend(title="Time")) } ##### ##### if(gobject$setup$i.type=="natural"){ if(is.null(weight)==FALSE){warning("It is not meaningful to specify weights for the natural course scenario. \n Weights are being ignored.")} if(variable=="psi"){label<-expression(psi)}else{label<-variable} # if(difference==FALSE){ results <- results[results$a1!="difference",] if(is.null(cols)==FALSE){if(length(cols)!=length(results$time[results$time==1])){stop(paste("Provide",length(results$time[results$time==1]),"colours under `cols' (not more, not less - or use default colours)"))}} if(is.null(cols)){cols<-mycolors[1:length(results$time[results$time==1])]} results$Strategy <- rep(c("natural \n intervention", "observed \n data"),length(unique(results$time))) colnames(results)[colnames(results)==variable] <- "relvar" if(variable=="psi"){colnames(results)[colnames(results)%in%c("l95","u95")]<-c("sel.l95","sel.u95")}else{ colnames(results)[grep(paste0(variable,":"),colnames(results))]<-c("sel.l95","sel.u95")} gg1 <- ggplot(results, aes(x=time,y=relvar,col=as.factor(Strategy))) + geom_point(size=1.75, position = position_dodge(width = 0+0.25*(CI==T & msm.method=="none"))) + theme_bw() if(msm.method=="none"){gg2<-gg1} if(msm.method!="none"){gg2<-gg1+ geom_line(linetype=3, linewidth=1.05)} if(msm.method=="loess" | msm.method=="gam"){cat("Note: MSM methods 'loess' and 'gam' not supported for natural interventions. \n Too few observations available for modeling (typically). \n msm.method='line' is used. \n")} if(CI==TRUE & msm.method!="none"){gg2 <- gg2 + geom_ribbon(aes(ymin = sel.l95, ymax = sel.u95, fill=as.factor(Strategy)), alpha=0.1,show.legend = FALSE)} if(CI==TRUE & msm.method=="none"){gg2 <- gg2 + geom_pointrange(aes(ymin = sel.l95, ymax = sel.u95), linewidth=1.05, show.legend=FALSE, position = position_dodge(width = 0.25))} gg3 <- gg2 + scale_color_manual(values = cols) + scale_fill_manual(values = cols) + scale_x_continuous("Time",breaks=unique(results$time)) + scale_y_continuous(label) + ggtitle("Natural Course Scenario") + theme(axis.title.x = element_text(size=13), axis.text.x = element_text(size=13),axis.title.y = element_text(size=13, angle = 90), axis.text.y = element_text(size=13), legend.text = element_text(size=13), legend.title = element_text(size=13, face = "bold", hjust = 0),legend.position = "right") + guides(col=guide_legend(title="Strategies")) }else{ # if(variable=="psi"){label<-expression(psi)}else{label<-expression(variable)} colnames(results)[colnames(results)==variable] <- "relvar" diff.results <- results[results$a1=="difference",] if(variable=="psi"){colnames(diff.results)[colnames(diff.results)%in%c("l95","u95")]<-c("sel.l95","sel.u95")}else{ colnames(diff.results)[grep(paste0(variable,":"),colnames(diff.results))]<-c("sel.l95","sel.u95")} if(is.null(cols)==FALSE){cols <- "black"} gg1 <- ggplot(diff.results, aes(x=time,y=relvar)) + geom_point(size=1.75, position = position_dodge(width = 0+0.3*(CI==T & msm.method=="none"))) + theme_bw() if(msm.method=="none"){gg2<-gg1} if(msm.method!="none"){gg2<-gg1+ geom_line(linetype=3, linewidth=1.05)} if(msm.method=="loess" | msm.method=="gam"){cat("Note: MSM methods 'loess' and 'gam' not supported for natural interventions. \n Too few observations available for modeling (typically). \n MSM method='line' is used. \n")} if(CI==TRUE & msm.method!="none"){gg2 <- gg2 + geom_ribbon(aes(ymin = sel.l95, ymax = sel.u95), alpha=0.1,show.legend = FALSE)} if(CI==TRUE & msm.method=="none"){gg2 <- gg2 + geom_pointrange(aes(ymin = sel.l95, ymax = sel.u95), linewidth=1.05, show.legend=FALSE, position = position_dodge(width = 0.25))} gg3 <- gg2 + scale_color_manual(values = cols) + scale_fill_manual(values = cols) + scale_x_continuous("Time",breaks=unique(results$time)) + scale_y_continuous("Difference") + geom_hline(yintercept = 0) + ggtitle("Difference between observed data \n and estimates under natural intervention") + theme(axis.title.x = element_text(size=13), axis.text.x = element_text(size=13),axis.title.y = element_text(size=13, angle = 90), axis.text.y = element_text(size=13), legend.text = element_text(size=13), legend.title = element_text(size=13, face = "bold", hjust = 0),legend.position = "right") + guides(col=guide_legend(title="Strategies")) } } ##### ##### if(gobject$setup$i.type=="custom"){ if(is.null(weight)==FALSE){warning("Weights for custom estimands are being ignored. \n As for custom estimands `time' is on the x-axis *weighted* smoothing is not ideal if t is small. \n Plot your own weighted graphs as required. \n")} if(is.null(cols)==FALSE){if(length(cols)!=length(results$time[results$time==1])){stop(paste("Provide",length(results$time[results$time==1]),"colours under `cols' (not more, not less - or use default colours)"))}} if(is.null(cols)){cols<-mycolors[1:length(results$time[results$time==1])]} results$Strategy <- rep(paste("Strategy:",apply(round(results[results$time==max(results$time),grep("a",colnames(results))],digits=2),1,paste,collapse="; ")),length(unique(results$time))) gg1 <- ggplot(results, aes(x=time,y=psi,col=as.factor(Strategy), fill=as.factor(Strategy))) + geom_point(size=1.75,show.legend = T, position = position_dodge(width = 0+0.3*(CI==T & msm.method=="none"))) + theme_bw() if(msm.method=="none"){gg2<-gg1} if(msm.method!="none"){gg2<-gg1+ geom_line(linetype=3, linewidth=1.05, show.legend = FALSE)} if(msm.method=="loess" | msm.method=="gam"){msm.method<-"line"; cat("Note: MSM methods 'loess' and 'gam' not supported for custom interventions (and survival setting). \n Too few observations available for modeling (typically). \n msm.method='line' is used. \n")} if(CI==TRUE & bin.int==FALSE & msm.method=="line"){gg2 <- gg2 + geom_ribbon(aes(ymin = l95, ymax = u95), alpha=0.1,show.legend = FALSE)} if(CI==TRUE & (bin.int==TRUE | msm.method=="none")){gg2 <- gg2 + geom_pointrange(aes(ymin = l95, ymax = u95), show.legend=FALSE, position = position_dodge(width = 0.3))} gg3 <- gg2 + scale_color_manual(values = cols) + scale_fill_manual(values = cols) + scale_x_continuous("Time",breaks=unique(results$time)) + scale_y_continuous(expression(psi)) + ggtitle("Effect of Strategies over Time") + theme(axis.title.x = element_text(size=13), axis.text.x = element_text(size=13),axis.title.y = element_text(size=13, angle = 90), axis.text.y = element_text(size=13), legend.text = element_text(size=13), legend.title = element_text(size=13, face = "bold", hjust = 0),legend.position = "right") + guides(col=guide_legend(title="Strategies"), fill="none") } suppressMessages(plot(gg3)) }
/scratch/gouwar.j/cran-all/cranData/CICI/R/plot.gformula.r
print.gformula<-function(x, ...){ selcol <- c(which(colnames(x$results)=="psi"):dim(x$results)[2]) x$results[,selcol] <- apply(subset(x$results,select=selcol),2,round, digits=5) print(x$results) }
/scratch/gouwar.j/cran-all/cranData/CICI/R/print.gformula.r
#' CIEE: Causal inference based on estimating equations #' #' Functions to perform CIEE under the GLM or AFT setting: #' \code{\link{ciee}} obtains point and standard error estimates of all parameter estimates, #' and p-values for testing the absence of effects; \code{\link{ciee_loop}} performs #' \code{\link{ciee}} in separate analyses of multiple exposure variables with the same #' outcome measures and factors ond only returns point estimates, standard error #' estimates and p-values for the exposure variables. Both functions can also compute #' estimates and p-values from the two traditional regression methods and from the #' structural equation modeling method. #' #' For the computation of CIEE, point estimates of the parameters are obtained #' using the \code{\link{get_estimates}} function. Robust sandwich (recommended), #' bootstrap, or naive standard error estimates of the parameter estimates are #' obtained using the \code{\link{sandwich_se}}, \code{\link{bootstrap_se}} #' or \code{\link{naive_se}} function. Large-sample Wald-type tests are performed #' for testing the absence of effects, using either the robust sandwich or #' bootstrap standard errors. #' #' Regarding the traditional regression methods, the multiple regression or #' regression of residual approaches can be computed using the #' \code{\link{mult_reg}} and \code{\link{res_reg}} functions. Finally, the #' structural equation modeling approachcan be performed using the #' \code{\link{sem_appl}} function. #' #' @param setting String with value \code{"GLM"} or \code{"AFT"} indicating #' whether a normally-distributed (\code{"GLM"}) or censored #' time-to-event (\code{"AFT"}) primary outcome \code{Y} is #' analyzed. #' @param estimates String vector with possible values \code{"ee"}, \code{"mult_reg"}, #' \code{"res_reg"}, \code{"sem"} indicating which methods #' are computed. \code{"ee"} computes CIEE, \code{"mult_reg"} #' the traditional multiple regression method, \code{"res_reg"} #' the traditional regression of residuals method, and #' \code{"sem"} the structural equation modeling approach. #' Multiple methods can be specified. #' @param ee_se String with possible values \code{"sandwich"}, \code{"bootstrap"}, #' \code{"naive"} indicating how the standard error estimates #' of the parameter estiamtes are computed for CIEE approach. #' \code{"sandwich"} computes the robust sandwich estimates (default, #' recommended), \code{"bootstrap"} the bootstrap estimates and #' \code{"naive"} the naive unadjusted standard error estimates #' (not recommended, only for comparison). #' One method has to be specified. #' @param BS_rep Integer indicating the number of bootstrap samples that are #' drawn (recommended 1000) if bootstrap standard errors are computed. #' @param Y Numeric input vector for the primary outcome. #' @param X Numeric input vector for the exposure variable if the \code{\link{ciee}} #' function is used; or numeric input dataframe containing the exposure #' variables as columns if the \code{\link{ciee_loop}} function is used. #' @param K Numeric input vector for the intermediate outcome. #' @param L Numeric input vector for the observed confounding factor. #' @param C Numeric input vector for the censoring indicator under the AFT setting #' (must be coded 0 = censored, 1 = uncensored). #' #' @return Object of class \code{ciee}, for which the summary function #' \code{\link{summary.ciee}} is implemented. #' \code{\link{ciee}} returns a list containing the point and standard error #' estimates of all parameters as well as p-values from hypothesis tests #' of the absence of effects, for each specified approach. #' \code{\link{ciee_loop}} returns a list containing the point and standard #' error estimates only of the exposure variables as well as p-values from #' hypothesis tests of the absence of effects, for each specified approach. #' #' @examples #' #' # Generate data under the GLM setting with default values #' maf <- 0.2 #' n <- 100 #' dat <- generate_data(n = n, maf = maf) #' datX <- data.frame(X = dat$X) #' names(datX)[1] <- "X1" #' # Add 9 more exposure variables names X2, ..., X10 to X #' for (i in 2:10){ #' X <- stats::rbinom(n, size = 2, prob = maf) #' datX$X <- X #' names(datX)[i] <- paste("X", i, sep="") #' } #' #' # Perform analysis of one exposure variable using all four methods #' ciee(Y = dat$Y, X = datX$X1, K = dat$K, L = dat$L) #' #' # Perform analysis of all exposure variables only for CIEE #' ciee_loop(estimates = "ee", Y = dat$Y, X = datX, K = dat$K, L = dat$L) #' #' @export #' ciee <- function(setting = "GLM", estimates = c("ee", "mult_reg", "res_reg", "sem"), ee_se = c("sandwich"), BS_rep = NULL, Y = NULL, X = NULL, K = NULL, L = NULL, C = NULL) { if (is.null(setting)) { stop("setting has to be supplied.") } if (is.null(estimates)) { stop("At least one method has to be computed.") } if ((("ee" %in% estimates) & is.null(ee_se)) | (("ee" %in% estimates) & length(ee_se) > 1)) { stop("If the estimating equations approach is chosen, one approach has to be chosen for the computation of standard errors.") } if (("bootstrap" %in% estimates) & is.null(BS_rep)) { stop("For the computation of bootstrap standard errors, the number of bootstrap samples has to be chosen.") } if (is.null(Y) | is.null(X) | is.null(K) | is.null(L)) { stop("Data of one or more variables is not supplied.") } if (setting == "AFT" & is.null(C)) { stop("C has to be supplied for the AFT setting.") } if (setting == "AFT" & ("sem" %in% estimates)) { stop("The structural equations modeling approach is only implemented for the GLM setting.") } if (setting == "AFT" & ("res_reg" %in% estimates)) { stop("The regression of residuals approach is only implemented for the GLM setting.") } if (setting == "GLM") { data_help <- data.frame(Y = Y, X = X, K = K, L = L) data_help <- data_help[stats::complete.cases(data_help), ] if ("sem" %in% estimates) { results_sem <- sem_appl(Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L) } if ("mult_reg" %in% estimates) { results_mult_reg <- mult_reg(setting = setting, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L) } if ("res_reg" %in% estimates) { results_res_reg <- res_reg(Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L) } if ("ee" %in% estimates) { point_estimates_ee <- get_estimates(setting = setting, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L) if (ee_se == "sandwich") { # Obtain estimating functions expressions estfunct <- est_funct_expr(setting = "GLM") # Obtain matrices with all first and second derivatives derivobj <- deriv_obj(setting = setting, logL1 = estfunct$logL1, logL2 = estfunct$logL2, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L, estimates = point_estimates_ee) # Obtain score and hessian matrices results_scores <- scores(derivobj) results_hessian <- hessian(derivobj) # Obtain sandwich standard error estimates of the parameters se_estimates_ee <- sandwich_se(setting = setting, scores = results_scores, hessian = results_hessian) } if (ee_se == "bootstrap") { se_estimates_ee <- bootstrap_se(setting = setting, BS_rep = BS_rep, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L) } if (ee_se == "naive") { se_estimates_ee <- naive_se(setting = setting, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L) } wald_test_stat_ee <- point_estimates_ee[1:8]/se_estimates_ee pvalues_ee <- 2 * stats::pnorm(-abs(wald_test_stat_ee)) results_ee <- list(point_estimates = point_estimates_ee[1:8], SE_estimates = se_estimates_ee, wald_test_stat = wald_test_stat_ee, pvalues = pvalues_ee) } } if (setting == "AFT") { data_help <- data.frame(Y = Y, X = X, K = K, L = L, C = C) data_help <- data_help[stats::complete.cases(data_help), ] if ("mult_reg" %in% estimates) { results_mult_reg <- mult_reg(setting = setting, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L, C = data_help$C) } if ("ee" %in% estimates) { point_estimates_ee <- get_estimates(setting = setting, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L, C = data_help$C) if (ee_se == "sandwich") { # Obtain estimating functions expressions estfunct <- est_funct_expr(setting = setting) # Obtain matrices with all first and second derivatives derivobj <- deriv_obj(setting = setting, logL1 = estfunct$logL1, logL2 = estfunct$logL2, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L, C = data_help$C, estimates = point_estimates_ee) # Obtain score and hessian matrices results_scores <- scores(derivobj) results_hessian <- hessian(derivobj) # Obtain sandwich standard error estimates of the parameters se_estimates_ee <- sandwich_se(setting = setting, scores = results_scores, hessian = results_hessian) } if (ee_se == "bootstrap") { se_estimates_ee <- bootstrap_se(setting = setting, BS_rep = BS_rep, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L, C = data_help$C) } if (ee_se == "naive") { se_estimates_ee <- naive_se(setting = setting, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L, C = data_help$C) } wald_test_stat_ee <- point_estimates_ee[1:8]/se_estimates_ee pvalues_ee <- 2 * stats::pnorm(-abs(wald_test_stat_ee)) results_ee <- list(point_estimates = point_estimates_ee[1:8], SE_estimates = se_estimates_ee, wald_test_stat = wald_test_stat_ee, pvalues = pvalues_ee) } } output <- list() if ("ee" %in% estimates) { output$results_ee <- results_ee } if ("mult_reg" %in% estimates) { output$results_mult_reg <- results_mult_reg } if ("res_reg" %in% estimates) { output$results_res_reg <- results_res_reg } if ("sem" %in% estimates) { output$results_sem <- results_sem } class(output) <- "ciee" return(output) } #' @rdname ciee #' @export ciee_loop <- function(setting = "GLM", estimates = c("ee", "mult_reg", "res_reg", "sem"), ee_se = c("sandwich"), BS_rep = NULL, Y = NULL, X = NULL, K = NULL, L = NULL, C = NULL) { if (is.null(setting)) { stop("setting has to be supplied.") } if (is.null(estimates)) { stop("At least one method has to be computed.") } if ((("ee" %in% estimates) & is.null(ee_se)) | (("ee" %in% estimates) & length(ee_se) > 1)) { stop("If the estimating equations approach is chosen, one approach has to be chosen for the computation of standard errors.") } if (("bootstrap" %in% estimates) & is.null(BS_rep)) { stop("For the computation of bootstrap standard errors, the number of bootstrap samples has to be chosen.") } if (is.null(Y) | is.null(X) | is.null(K) | is.null(L)) { stop("Data of one or more variables is not supplied.") } if (setting == "AFT" & is.null(C)) { stop("C has to be supplied for the AFT setting.") } if (setting == "AFT" & ("sem" %in% estimates)) { stop("The structural equations modeling approach is only implemented for the GLM setting.") } if (setting == "AFT" & ("res_reg" %in% estimates)) { stop("The regression of residuals approach is only implemented for the GLM setting.") } if ("sem" %in% estimates) { results_sem <- list(point_estimates = NULL, SE_estimates = NULL, pvalues = NULL) } if ("mult_reg" %in% estimates) { results_mult_reg <- list(point_estimates = NULL, SE_estimates = NULL, pvalues = NULL) } if ("res_reg" %in% estimates) { results_res_reg <- list(point_estimates = NULL, SE_estimates = NULL, pvalues = NULL) } if ("ee" %in% estimates) { results_ee <- list(point_estimates = NULL, SE_estimates = NULL, wald_test_stat = NULL, pvalues = NULL) } k <- dim(X)[2] for (i in 1:k) { Xi <- X[, i] if (setting == "GLM") { data_help <- data.frame(Y = Y, X = Xi, K = K, L = L) data_help <- data_help[stats::complete.cases(data_help), ] if ("sem" %in% estimates) { sem_help <- sem_appl(Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L) results_sem$point_estimates[i] <- sem_help$point_estimates[5] results_sem$SE_estimates[i] <- sem_help$SE_estimates[5] results_sem$pvalues[i] <- sem_help$pvalues[5] names(results_sem$point_estimates)[i] <- names(results_sem$SE_estimates)[i] <- names(results_sem$pvalues)[i] <- names(X)[i] } if ("mult_reg" %in% estimates) { mult_reg_help <- mult_reg(setting = setting, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L) results_mult_reg$point_estimates[i] <- mult_reg_help$point_estimates[3] results_mult_reg$SE_estimates[i] <- mult_reg_help$SE_estimates[3] results_mult_reg$pvalues[i] <- mult_reg_help$pvalues[3] names(results_mult_reg$point_estimates)[i] <- names(results_mult_reg$SE_estimates)[i] <- names(results_mult_reg$pvalues)[i] <- names(X)[i] } if ("res_reg" %in% estimates) { res_reg_help <- res_reg(Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L) results_res_reg$point_estimates[i] <- res_reg_help$point_estimates[5] results_res_reg$SE_estimates[i] <- res_reg_help$SE_estimates[5] results_res_reg$pvalues[i] <- res_reg_help$pvalues[5] names(results_res_reg$point_estimates)[i] <- names(results_res_reg$SE_estimates)[i] <- names(results_res_reg$pvalues)[i] <- names(X)[i] } if ("ee" %in% estimates) { point_estimates_ee <- get_estimates(setting = setting, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L) if (ee_se == "sandwich") { # Obtain estimating functions expressions estfunct <- est_funct_expr(setting = "GLM") # Obtain matrices with all first and second derivatives derivobj <- deriv_obj(setting = setting, logL1 = estfunct$logL1, logL2 = estfunct$logL2, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L, estimates = point_estimates_ee) # Obtain score and hessian matrices results_scores <- scores(derivobj) results_hessian <- hessian(derivobj) # Obtain sandwich standard error estimates of the parameters se_estimates_ee <- sandwich_se(setting = setting, scores = results_scores, hessian = results_hessian) } if (ee_se == "bootstrap") { se_estimates_ee <- bootstrap_se(setting = setting, BS_rep = BS_rep, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L) } if (ee_se == "naive") { se_estimates_ee <- naive_se(setting = setting, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L) } results_ee$point_estimates[i] <- point_estimates_ee[7] results_ee$SE_estimates[i] <- se_estimates_ee[7] results_ee$wald_test_stat[i] <- point_estimates_ee[7]/ se_estimates_ee[7] results_ee$pvalues[i] <- 2 * stats::pnorm(-abs(point_estimates_ee[7]/ se_estimates_ee[7])) names(results_ee$point_estimates)[i] <- names(results_ee$SE_estimates)[i] <- names(results_ee$wald_test_stat)[i] <- names(results_ee$pvalues)[i] <- names(X)[i] } } if (setting == "AFT") { data_help <- data.frame(Y = Y, X = Xi, K = K, L = L, C = C) data_help <- data_help[stats::complete.cases(data_help), ] if ("mult_reg" %in% estimates) { mult_reg_help <- mult_reg(setting = setting, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L, C = data_help$C) results_mult_reg$point_estimates[i] <- mult_reg_help$point_estimates[3] results_mult_reg$SE_estimates[i] <- mult_reg_help$SE_estimates[3] results_mult_reg$pvalues[i] <- mult_reg_help$pvalues[3] names(results_mult_reg$point_estimates)[i] <- names(results_mult_reg$SE_estimates)[i] <- names(results_mult_reg$pvalues)[i] <- names(X)[i] } if ("ee" %in% estimates) { point_estimates_ee <- get_estimates(setting = setting, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L, C = data_help$C) if (ee_se == "sandwich") { # Obtain estimating functions expressions estfunct <- est_funct_expr(setting = setting) # Obtain matrices with all first and second derivatives derivobj <- deriv_obj(setting = setting, logL1 = estfunct$logL1, logL2 = estfunct$logL2, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L, C = data_help$C, estimates = point_estimates_ee) # Obtain score and hessian matrices results_scores <- scores(derivobj) results_hessian <- hessian(derivobj) # Obtain sandwich standard error estimates of the parameters se_estimates_ee <- sandwich_se(setting = setting, scores = results_scores, hessian = results_hessian) } if (ee_se == "bootstrap") { se_estimates_ee <- bootstrap_se(setting = setting, BS_rep = BS_rep, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L, C = data_help$C) } if (ee_se == "naive") { se_estimates_ee <- naive_se(setting = setting, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L, C = data_help$C) } results_ee$point_estimates[i] <- point_estimates_ee[7] results_ee$SE_estimates[i] <- se_estimates_ee[7] results_ee$wald_test_stat[i] <- point_estimates_ee[7]/ se_estimates_ee[7] results_ee$pvalues[i] <- 2 * stats::pnorm(-abs(point_estimates_ee[7]/ se_estimates_ee[7])) names(results_ee$point_estimates)[i] <- names(results_ee$SE_estimates)[i] <- names(results_ee$wald_test_stat)[i] <- names(results_ee$pvalues)[i] <- names(X)[i] } } } output <- list() if ("ee" %in% estimates) { output$results_ee <- results_ee } if ("mult_reg" %in% estimates) { output$results_mult_reg <- results_mult_reg } if ("res_reg" %in% estimates) { output$results_res_reg <- results_res_reg } if ("sem" %in% estimates) { output$results_sem <- results_sem } class(output) <- "ciee" return(output) }
/scratch/gouwar.j/cran-all/cranData/CIEE/R/ciee.R
#' Score and hessian matrix based on the estimating functions. #' #' Functions to compute the score and hessian matrices of the parameters #' based on the estimating functions, under the GLM and AFT setting for #' the analysis of a normally-distributed or censored time-to-event #' primary outcome. The score and hessian matrices are further used in #' the functions \code{\link{sandwich_se}}, \code{\link{ciee}} and #' \code{\link{ciee_loop}} to obtain robust sandwich error estimates of the #' parameter estimates of #' \eqn{\alpha_0, \alpha_1, \alpha_2, \alpha_3, \sigma_1^2, \alpha_4, \alpha_{XY}, \sigma_2^2}{\alpha0, \alpha1, \alpha2, \alpha3, \sigma1^2, \alpha4, \alphaXY, \sigma2^2} #' under the GLM setting and #' \eqn{\alpha_0, \alpha_1, \alpha_2, \alpha_3, \sigma_1, \alpha_4, \alpha_{XY}, \sigma_2^2}{\alpha0, \alpha1, \alpha2, \alpha3, \sigma1, \alpha4, \alphaXY, \sigma2^2} #' under the AFT setting. #' #' For the computation of the score and hessian matrices, first, the help function #' \code{\link{deriv_obj}} is used. In a first step, the expression of all first #' and second derivatives of the parameters is computed using the expressions of #' \code{logL1} and \code{logL2} from the \code{\link{est_funct_expr}} as input. #' Then, the numerical values of all first and second derivatives are obtained #' for the observed data \code{Y}, \code{X}, \code{K}, \code{L} (and \code{C} under #' the AFT setting) and point estimates (\code{estimates}) of the parameters, #' for all observed individuals. #' #' Second, the functions \code{\link{scores}} and \code{\link{hessian}} are used #' to extract the relevant score and hessian matrices with respect to \code{logL1} #' and \code{logL2} from the output of \code{\link{deriv_obj}} and piece them together. #' For further details, see the vignette. #' #' @param setting String with value \code{"GLM"} or \code{"AFT"} indicating #' whether the matrices are computed under the GLM or AFT setting. #' @param logL1 Expression of the function \code{logL1} generated by #' the \code{\link{est_funct_expr}} function. #' @param logL2 Expression of the function \code{logL2} generated by #' the \code{\link{est_funct_expr}} function. #' @param Y Numeric input vector for the primary outcome. #' @param X Numeric input vector for the exposure variable. #' @param K Numeric input vector for the intermediate outcome. #' @param L Numeric input vector for the observed confounding factor. #' @param C Numeric input vector for the censoring indicator under the AFT setting #' (must be coded 0 = censored, 1 = uncensored). #' @param estimates Numeric input vector with point estimates of the parameters #' \eqn{\alpha_0, \alpha_1, \alpha_2, \alpha_3, \sigma_1^2,}{\alpha0, \alpha1, \alpha2, \alpha3, \sigma1^2,} #' \eqn{\alpha_4, \alpha_{XY}, \sigma_2^2}{\alpha4, \alphaXY, \sigma2^2} #' under the GLM setting and of #' \eqn{\alpha_0, \alpha_1, \alpha_2, \alpha_3, \sigma_1, \alpha_4, \alpha_{XY}, \sigma_2^2}{\alpha0, \alpha1, \alpha2, \alpha3, \sigma1, \alpha4, \alphaXY, \sigma2^2} #' under the AFT setting. Under the AFT setting, #' \code{estimates} must also contain the mean of the estimated #' true survival times \code{"y_adj_bar"}. #' @param derivobj Output of the \code{\link{deriv_obj}} function used as input in #' the \code{\link{scores}} and \code{\link{hessian}} functions. #' #' @return The \code{\link{deriv_obj}} function returns a list with #' objects \code{logL1_deriv}, \code{logL2_deriv} which #' contain the score and hessian matrices based on \code{logL1}, #' \code{logL2}, respectively. #' @return The \code{\link{scores}} function returns the \eqn{(n \times 8)}{(n x 8)} #' score matrix. #' @return The \code{\link{hessian}} function returns the \eqn{(n \times 8 \times 8)}{(n x 8 x 8)} #' hessian matrix. #' #' @examples #' #' # Generate data including Y, K, L, X under the GLM setting #' dat <- generate_data(setting = "GLM") #' #' # Obtain estimating functions' expressions #' estfunct <- est_funct_expr(setting = "GLM") #' #' # Obtain point estimates of the parameters #' estimates <- get_estimates(setting = "GLM", Y = dat$Y, X = dat$X, #' K = dat$K, L = dat$L) #' #' # Obtain matrices with all first and second derivatives #' derivobj <- deriv_obj(setting = "GLM", logL1 = estfunct$logL1, #' logL2 = estfunct$logL2, Y = dat$Y, X = dat$X, #' K = dat$K, L = dat$L, estimates = estimates) #' names(derivobj) #' head(derivobj$logL1_deriv$gradient) #' #' # Obtain score and hessian matrices #' scores(derivobj) #' hessian(derivobj) #' #' @name score_and_hessian_matrix_functions NULL #' @rdname score_and_hessian_matrix_functions #' @export deriv_obj <- function(setting = "GLM", logL1 = NULL, logL2 = NULL, Y = NULL, X = NULL, K = NULL, L = NULL, C = NULL, estimates = NULL) { if (is.null(setting) | is.null(logL1) | is.null(logL2) | is.null(estimates)) { stop("One or more arguments of the function are missing.") } if (is.null(Y) | is.null(X) | is.null(K) | is.null(L)) { stop("Data of one or more variables are not supplied.") } if (setting == "AFT" & is.null(C)) { stop("C has to be supplied for the AFT setting.") } n <- length(Y) if (setting == "GLM") { data_help <- data.frame(Y = Y, X = X, K = K, L = L) data_help <- data_help[stats::complete.cases(data_help), ] U12345_i <- stats::deriv(expr = logL1, namevec = c("alpha0", "alpha1", "alpha2", "alpha3", "sigma1sq", "alpha4", "alphaXY", "sigma2sq"), function.arg = c("y_i", "k_i", "x_i", "l_i", "alpha0", "alpha1", "alpha2", "alpha3", "sigma1sq"), func = T, hessian = T) U678_i <- stats::deriv(expr = logL2, namevec = c("alpha0", "alpha1", "alpha2", "alpha3", "sigma1sq", "alpha4", "alphaXY", "sigma2sq"), function.arg = c("y_i", "k_i", "x_i", "y_bar", "k_bar", "alpha1", "alpha4", "alphaXY", "sigma2sq"), func = T, hessian = T) logL1_deriv <- attributes(U12345_i(y_i = data_help$Y, k_i = data_help$K, x_i = data_help$X, l_i = data_help$L, alpha0 = estimates[names(estimates) == "alpha_0"], alpha1 = estimates[names(estimates) == "alpha_1"], alpha2 = estimates[names(estimates) == "alpha_2"], alpha3 = estimates[names(estimates) == "alpha_3"], sigma1sq = estimates[names(estimates) == "sigma_1_sq"])) logL2_deriv <- attributes(U678_i(y_i = data_help$Y, k_i = data_help$K, x_i = data_help$X, y_bar = mean(data_help$Y), k_bar = mean(data_help$K), alpha1 = estimates[names(estimates) == "alpha_1"], alpha4 = estimates[names(estimates) == "alpha_4"], alphaXY = estimates[names(estimates) == "alpha_XY"], sigma2sq = estimates[names(estimates) == "sigma_2_sq"])) deriv_obj <- list(logL1_deriv = logL1_deriv, logL2_deriv = logL2_deriv) } if (setting == "AFT") { data_help <- data.frame(Y = Y, X = X, K = K, L = L, C = C) data_help <- data_help[stats::complete.cases(data_help), ] U12345_i <- stats::deriv(expr = logL1, namevec = c("alpha0", "alpha1", "alpha2", "alpha3", "sigma1", "alpha4", "alphaXY", "sigma2sq"), function.arg = c("y_i", "c_i", "k_i", "x_i", "l_i", "alpha0", "alpha1", "alpha2", "alpha3", "sigma1"), func = T, hessian = T) U678_i <- stats::deriv(expr = logL2, namevec = c("alpha0", "alpha1", "alpha2", "alpha3", "sigma1", "alpha4", "alphaXY", "sigma2sq"), function.arg = c("y_i", "c_i", "k_i", "x_i", "l_i", "y_adj_bar", "k_bar", "alpha0", "alpha1", "alpha2", "alpha3", "sigma1", "alpha4", "alphaXY", "sigma2sq"), func = T, hessian = T) logL1_deriv <- attributes(U12345_i(y_i = data_help$Y, c_i = data_help$C, k_i = data_help$K, x_i = data_help$X, l_i = data_help$L, alpha0 = estimates[names(estimates) == "alpha_0"], alpha1 = estimates[names(estimates) == "alpha_1"], alpha2 = estimates[names(estimates) == "alpha_2"], alpha3 = estimates[names(estimates) == "alpha_3"], sigma1 = estimates[names(estimates) == "sigma_1"])) logL2_deriv <- attributes(U678_i(y_i = data_help$Y, c_i = data_help$C, k_i = data_help$K, x_i = data_help$X, l_i = data_help$L, y_adj_bar = estimates[names(estimates) == "y_adj_bar"], k_bar = mean(data_help$K), alpha0 = estimates[names(estimates) == "alpha_0"], alpha1 = estimates[names(estimates) == "alpha_1"], alpha2 = estimates[names(estimates) == "alpha_2"], alpha3 = estimates[names(estimates) == "alpha_3"], sigma1 = estimates[names(estimates) == "sigma_1"], alpha4 = estimates[names(estimates) == "alpha_4"], alphaXY = estimates[names(estimates) == "alpha_XY"], sigma2sq = estimates[names(estimates) == "sigma_2_sq"])) deriv_obj <- list(logL1_deriv = logL1_deriv, logL2_deriv = logL2_deriv) } return(deriv_obj) } #' @rdname score_and_hessian_matrix_functions #' @export scores <- function(derivobj = NULL) { if (is.null(derivobj)) { stop("derivobj has to be supplied.") } scores_out <- cbind(derivobj[[1]]$gradient[, 1:5], derivobj[[2]]$gradient[, 6:8]) return(scores_out) } #' @rdname score_and_hessian_matrix_functions #' @export hessian <- function(derivobj = NULL) { if (is.null(derivobj)) { stop("derivobj has to be supplied.") } hessian_out <- derivobj[[1]]$hessian hessian_out[, 6:8, ] <- derivobj[[2]]$hessian[, 6:8, ] return(hessian_out) }
/scratch/gouwar.j/cran-all/cranData/CIEE/R/deriv_functions.R
#' Estimating functions. #' #' Function to compute \code{logL1} and \code{logL2} under the GLM and AFT setting #' for the analysis of a normally-distributed and of a censored time-to-event #' primary outcome. \code{logL1} and \code{logL2} are functions which underlie #' the estimating functions of CIEE for the derivation of point estimates and #' standard error estimates. \code{\link{est_funct_expr}} computes their #' expression, which is then further used in the functions \code{\link{deriv_obj}}, #' \code{\link{ciee}} and \code{\link{ciee_loop}}. #' #' Under the GLM setting for the analysis of a normally-distributed primary #' outcome \code{Y}, the goal is to obtain estimates for the pararameters #' \eqn{\alpha_0, \alpha_1, \alpha_2, \alpha_3, \sigma_1^2, \alpha_4, \alpha_{XY}, \sigma_2^2}{\alpha0, \alpha1, \alpha2, \alpha3, \sigma1^2, \alpha4, \alphaXY, \sigma2^2} #' under the model #' \deqn{Y = \alpha_0 + \alpha_1 \cdot K + \alpha_2 \cdot X + \alpha_3 \cdot L + \epsilon_1, \epsilon_1 \sim N(0,\sigma_1^2)}{Y = \alpha0 + \alpha1*K + \alpha2*X + \alpha3*L + \epsilon1, \epsilon1 ~ N(0,\sigma1^2)} #' \deqn{Y^* = Y - \overline{Y} - \alpha_1 \cdot (K-\overline{K})}{Y* = Y - mean(Y) - \alpha1*(K-mean(K))} #' \deqn{Y^* = \alpha_0 + \alpha_{XY} \cdot X + \epsilon_2, \epsilon_2 \sim N(0,\sigma_2^2)}{Y* = \alpha0 + \alphaXY*X + \epsilon2, \epsilon2 ~ N(0,\sigma2^2).} #' \code{logL1} underlies the estimating functions for the derivation of the #' first 5 parameters #' \eqn{\alpha_0, \alpha_1, \alpha_2, \alpha_3, \sigma_1^2}{\alpha0, \alpha1, \alpha2, \alpha3, \sigma1^2} #' and #' \code{logL2} underlies the estimating functions for the derivation of the #' last 3 parameters #' \eqn{\alpha_4, \alpha_{XY}, \sigma_2^2}{\alpha4, \alphaXY, \sigma2^2}. #' #' Under the AFT setting for the analysis of a censored time-to-event primary #' outcome \code{Y}, the goal is to obtain estimates of the parameters #' \eqn{\alpha_0, \alpha_1, \alpha_2, \alpha_3, \sigma_1, \alpha_4, \alpha_{XY}, \sigma_2^2}{\alpha0, \alpha1, \alpha2, \alpha3, \sigma1, \alpha4, \alphaXY, \sigma2^2}. #' Here, \code{logL1} similarly underlies the estimating functions #' for the derivation of the first 5 parameters and \code{logL2} underlies the #' estimating functions for the derivation of the last 3 parameters. #' #' \code{logL1}, \code{logL2} equal the log-likelihood functions (\code{logL2} #' given that \eqn{\alpha_1}{\alpha1} is known). For more details and the underlying model, #' see the vignette. #' #' @param setting String with value \code{"GLM"} or \code{"AFT"} indicating whether #' the expression of \code{logL1} and \code{logL2} is computed #' under the GLM or AFT setting. #' @return Returns a list containing the expression of the functions \code{logL1} #' and \code{logL2}. #' #' @examples #' #' est_funct_expr(setting = "GLM") #' est_funct_expr(setting = "AFT") #' #' @export #' est_funct_expr <- function(setting = "GLM") { if (is.null(setting)) { stop("setting has to be supplied.") } if (setting == "GLM") { logL1 <- expression(log((1/sqrt(sigma1sq)) * dnorm((y_i - alpha0 - alpha1 * k_i - alpha2 * x_i - alpha3 * l_i)/ sqrt(sigma1sq), mean = 0, sd = 1))) logL2 <- expression(log((1/sqrt(sigma2sq)) * dnorm((y_i - y_bar - alpha1 * (k_i - k_bar) - alpha4 - alphaXY * x_i)/ sqrt(sigma2sq), mean = 0, sd = 1))) } if (setting == "AFT") { logL1 <- expression(-c_i * log(sigma1) + c_i * log(dnorm((y_i - alpha0 - alpha1 * k_i - alpha2 * x_i - alpha3 * l_i)/sigma1, mean = 0, sd = 1)) + (1 - c_i) * log(1 - pnorm((y_i - alpha0 - alpha1 * k_i - alpha2 * x_i - alpha3 * l_i)/ sigma1, mean = 0, sd = 1))) logL2 <- expression(log((1/sqrt(sigma2sq)) * dnorm(((c_i * y_i + (1 - c_i) * ((alpha0 + alpha1 * k_i + alpha2 * x_i + alpha3 * l_i) + (sigma1 * dnorm((y_i - alpha0 - alpha1 * k_i - alpha2 * x_i - alpha3 * l_i)/sigma1, mean = 0, sd = 1)/(1 - pnorm((y_i - alpha0 - alpha1 * k_i - alpha2 * x_i - alpha3 * l_i)/sigma1, mean = 0, sd = 1))))) - y_adj_bar - alpha1 * (k_i - k_bar) - alpha4 - alphaXY * x_i)/sqrt(sigma2sq), mean = 0, sd = 1))) } return(list(logL1 = logL1, logL2 = logL2)) }
/scratch/gouwar.j/cran-all/cranData/CIEE/R/estimating_funct_expr.R
#' Data generation function #' #' Function to generate data with \code{n} observations of a primary #' outcome \code{Y}, secondary outcome \code{K}, exposure \code{X}, and #' measured as well as unmeasured confounders \code{L} and \code{U}, where #' the primary outcome is a quantitative normally-distributed variable #' (\code{setting} = \code{"GLM"}) or censored time-to-event outcome under #' an accelerated failure time (AFT) model (\code{setting} = \code{"AFT"}). #' Under the AFT setting, the observed time-to-event variable \code{T=exp(Y)} #' as well as the censoring indicator \code{C} are also computed. \code{X} #' is generated as a genetic exposure variable in the form of a single #' nucleotide variant (SNV) in 0-1-2 additive coding with minor allele #' frequency \code{maf}. \code{X} can be generated independently of \code{U} #' (\code{X_orth_U} = \code{TRUE}) or dependent on \code{U} #' (\code{X_orth_U} = \code{FALSE}). For more details regarding the underlying #' model, see the vignette. #' #' @param setting String with value \code{"GLM"} or \code{"AFT"} indicating #' whether the primary outcome is generated as a #' normally-distributed quantitative outcome (\code{"GLM"}) or #' censored time-to-event outcome (\code{"AFT"}). #' @param n Numeric. Sample size. #' @param maf Numeric. Minor allele frequency of the genetic exposure variable. #' @param cens Numeric. Desired percentage of censored individuals and has to be #' specified under the AFT setting. Note that the actual censoring #' rate is generated through specification of the parameters #' \code{a} and \code{b}, and \code{cens} is mostly used as a check #' whether the desired censoring rate is obtained through \code{a} #' and \code{b} (otherwise, a warning is issued). #' @param a Integer for generating the desired censoring rate under the AFT #' setting. Has to be specified under the AFT setting. #' @param b Integer for generating the desired censoring rate under the AFT #' setting. Has to be specified under the AFT setting. #' @param aUL Numeric. Size of the effect of \code{U} on \code{L}. #' @param aXL Numeric. Size of the effect of \code{X} on \code{L}. #' @param aXK Numeric. Size of the effect of \code{X} on \code{K}. #' @param aLK Numeric. Size of the effect of \code{L} on \code{K}. #' @param aUY Numeric. Size of the effect of \code{U} on \code{Y}. #' @param aKY Numeric. Size of the effect of \code{K} on \code{Y}. #' @param aXY Numeric. Size of the effect of \code{X} on \code{Y}. #' @param aLY Numeric. Size of the effect of \code{L} on \code{Y}. #' @param mu_U Numeric. Expected value of \code{U}. #' @param sd_U Numeric. Standard deviation of \code{U}. #' @param X_orth_U Logical. Indicator whether \code{X} should be generated #' independently of \code{U} (\code{X_orth_U} = \code{TRUE}) #' or dependent on \code{U} (\code{X_orth_U} = \code{FALSE}). #' @param mu_X Numeric. Expected value of \code{X}. #' @param sd_X Numeric. Standard deviation of \code{X}. #' @param mu_L Numeric. Expected value of \code{L}. #' @param sd_L Numeric. Standard deviation of \code{L}. #' @param mu_K Numeric. Expected value of \code{K}. #' @param sd_K Numeric. Standard deviation of \code{K}. #' @param mu_Y Numeric. Expected value of \code{Y}. #' @param sd_Y Numeric. Standard deviation of \code{Y}. #' #' @return A dataframe containing \code{n} observations of the variables \code{Y}, #' \code{K}, \code{X}, \code{L}, \code{U}. Under the AFT setting, #' \code{T=exp(Y)} and the censoring indicator \code{C} (0 = censored, #' 1 = uncensored) are also computed. #' #' @examples #' # Generate data under the GLM setting with default values #' dat_GLM <- generate_data() #' head(dat_GLM) #' #' # Generate data under the AFT setting with default values #' dat_AFT <- generate_data(setting = "AFT", a = 0.2, b = 4.75) #' head(dat_AFT) #' #' @export #' generate_data <- function(setting = "GLM", n = 1000, maf = 0.2, cens = 0.3, a = NULL, b = NULL, aXK = 0.2, aXY = 0.1, aXL = 0, aKY = 0.3, aLK = 0, aLY = 0, aUY = 0, aUL = 0, mu_X = NULL, sd_X = NULL, X_orth_U = TRUE, mu_U = 0, sd_U = 1, mu_K = 0, sd_K = 1, mu_L = 0, sd_L = 1, mu_Y = 0, sd_Y = 1) { U_out <- stats::rnorm(n, mean = mu_U, sd = sd_U) if (setting == "AFT" & (is.null(a) | is.null(b))) { stop("a and b have to be specified under the AFT setting.") } if (X_orth_U == TRUE) { X_out <- stats::rbinom(n, size = 2, prob = maf) } if (X_orth_U == FALSE) { X_out <- stats::pnorm(U_out, mean = mu_X, sd = sd_X) p <- 1 - maf for (j in 1:length(X_out)) { if (X_out[j] < p^2) { X_out[j] <- 0 next } if (X_out[j] >= p^2 & X_out[j] < p^2 + 2 * p * (1 - p)) { X_out[j] <- 1 next } if (X_out[j] >= p^2 + 2 * p * (1 - p)) { X_out[j] <- 2 next } } } L_out <- aUL * U_out + aXL * X_out + stats::rnorm(n, mean = mu_L, sd = sd_L) K_out <- aXK * X_out + aLK * L_out + stats::rnorm(n, mean = mu_K, sd = sd_K) Y_out <- aUY * U_out + aKY * K_out + aXY * X_out + aLY * L_out + stats::rnorm(n, mean = mu_Y, sd = sd_Y) data <- data.frame(Y = Y_out, K = K_out, X = X_out, L = L_out, U = U_out) if (setting == "AFT") { T_help <- exp(Y_out) ### Create censoring indicator and censored times no censoring if (cens == 0) { T_out <- T_help C_out <- rep(1, n) # C_out==0 is censored, C_out==1 is uncensored } if (!cens == 0) { # there is censoring; cens is the percentage of censored data T_cens <- stats::runif(n, min = a, max = b) # a, b for desired censoring rate C_out <- as.numeric(T_help < T_cens) # C==0 censored, C==1 uncensored T_out <- pmin(T_help, T_cens) Y_out <- log(T_out) } cens_out <- sum(abs(C_out - 1))/n data <- data.frame(Y = Y_out, K = K_out, X = X_out, L = L_out, U = U_out, T = T_out, C = C_out) print(paste("The empirical censoring rate obtained through the specified parameters a=", a, " and b=", b, " is ", cens_out, ".", sep = "")) if (abs(cens_out - cens) > 0.1) { warning(paste("This obtained empirical censoring rate is quite different from the desired censoring rate cens=", cens, ". Please check and adapt values for a and b.", sep = "")) } } return(data) }
/scratch/gouwar.j/cran-all/cranData/CIEE/R/generate_data.R
#' CIEE parameter point estimates #' #' Function to perform CIEE to obtain point estimates under the GLM or AFT #' setting for the analysis of a normally-distributed or censored time-to-event #' primary outcome. #' #' Under the GLM setting for the analysis of a normally-distributed primary #' outcome Y, estimates of the parameters #' \eqn{\alpha_0, \alpha_1, \alpha_2, \alpha_3, \sigma_1^2, \alpha_4, \alpha_{XY}, \sigma_2^2}{\alpha0, \alpha1, \alpha2, \alpha3, \sigma1^2, \alpha4, \alphaXY, \sigma2^2} #' are obtained by constructing estimating equations for the models #' \deqn{Y = \alpha_0 + \alpha_1 \cdot K + \alpha_2 \cdot X + \alpha_3 \cdot L + \epsilon_1, \epsilon_1 \sim N(0,\sigma_1^2)}{Y = \alpha0 + \alpha1*K + \alpha2*X + \alpha3*L + \epsilon1, \epsilon1 ~ N(0,\sigma1^2)} #' \deqn{Y^* = Y - \overline{Y} - \alpha_1 \cdot (K-\overline{K})}{Y* = Y - mean(Y) - \alpha1*(K-mean(K))} #' \deqn{Y^* = \alpha_0 + \alpha_{XY} \cdot X + \epsilon_2, \epsilon_2 \sim N(0,\sigma_2^2).}{Y* = \alpha0 + \alphaXY*X + \epsilon2, \epsilon2 ~ N(0,\sigma2^2).} #' Under the AFT setting for the analysis of a censored time-to-event primary #' outcome, estimates of the parameters #' \eqn{\alpha_0, \alpha_1, \alpha_2, \alpha_3, \sigma_1, \alpha_4, \alpha_{XY}, \sigma_2^2}{\alpha0, \alpha1, \alpha2, \alpha3, \sigma1, \alpha4, \alphaXY, \sigma2^2} #' are obtained by constructing #' similar estimating equations based on a censored regression model and adding #' an additional computation to estimate the true underlying survival times. #' In addition to the parameter estimates, the mean of the estimated true #' survival times is computed and returned in the output. For more details and #' the underlying model, see the vignette. #' #' For both settings, the point estimates based on estimating equations equal #' least squares (and maximum likelihood) estimates, and are obtained using #' the \code{\link[stats]{lm}} and \code{\link[survival]{survreg}} #' functions for computational purposes. #' #' @param setting String with value \code{"GLM"} or \code{"AFT"} indicating #' whether CIEE point estimates are obtained for a #' normally-distributed (\code{"GLM"}) or censored time-to-event #' (\code{"AFT"}) primary outcome \code{Y}. #' @param Y Numeric input vector for the primary outcome. #' @param X Numeric input vector for the exposure variable. #' @param K Numeric input vector for the intermediate outcome. #' @param L Numeric input vector for the observed confounding factor. #' @param C Numeric input vector for the censoring indicator under the AFT setting #' (must be coded 0 = censored, 1 = uncensored). #' #' @return Returns a list with point estimates of the parameters. Under the #' AFT setting, the mean of the estimated true survival times is also #' computed and returned. #' #' @examples #' #' dat_GLM <- generate_data(setting = "GLM") #' get_estimates(setting = "GLM", Y = dat_GLM$Y, X = dat_GLM$X, K = dat_GLM$K, #' L = dat_GLM$L) #' #' dat_AFT <- generate_data(setting = "AFT", a = 0.2, b = 4.75) #' get_estimates(setting = "AFT", Y = dat_AFT$Y, X = dat_AFT$X, K = dat_AFT$K, #' L = dat_AFT$L, C = dat_AFT$C) #' #' @export #' get_estimates <- function(setting = "GLM", Y = NULL, X = NULL, K = NULL, L = NULL, C = NULL) { if (!requireNamespace("survival", quietly = TRUE)) { stop("Pkg needed for this function to work. Please install it.", call. = FALSE) } if (is.null(setting)) { stop("setting has to be supplied.") } if (is.null(Y) | is.null(X) | is.null(K) | is.null(L)) { stop("Data of one or more variables are not supplied.") } if (setting == "AFT" & is.null(C)) { stop("C has to be supplied for the AFT setting.") } n <- length(Y) if (setting == "GLM") { data_help <- data.frame(Y = Y, X = X, K = K, L = L) data_help <- data_help[stats::complete.cases(data_help), ] ######### Stage 1 ######### fit_stage_1 <- stats::lm(data_help$Y ~ data_help$K + data_help$X + data_help$L) alpha_0_out <- summary(fit_stage_1)$coefficients[1, 1] alpha_1_out <- summary(fit_stage_1)$coefficients[2, 1] alpha_2_out <- summary(fit_stage_1)$coefficients[3, 1] alpha_3_out <- summary(fit_stage_1)$coefficients[4, 1] sigma_1_sq_out <- (n - 4)/n * summary(fit_stage_1)$sigma^2 ######### Stage 2 ######### Y_tilde <- data_help$Y - mean(data_help$Y) - alpha_1_out * (data_help$K - mean(data_help$K)) fit_stage_2 <- stats::lm(Y_tilde ~ data_help$X) alpha_4_out <- summary(fit_stage_2)$coefficients[1, 1] alpha_XY_out <- summary(fit_stage_2)$coefficients[2, 1] sigma_2_sq_out <- (n - 2)/n * summary(fit_stage_2)$sigma^2 point_estimates <- c(alpha_0_out, alpha_1_out, alpha_2_out, alpha_3_out, sigma_1_sq_out, alpha_4_out, alpha_XY_out, sigma_2_sq_out) names(point_estimates) <- c("alpha_0", "alpha_1", "alpha_2", "alpha_3", "sigma_1_sq", "alpha_4", "alpha_XY", "sigma_2_sq") } if (setting == "AFT") { data_help <- data.frame(Y = Y, X = X, K = K, L = L, C = C) data_help <- data_help[stats::complete.cases(data_help), ] ######### Stage 1 ######### fit_stage_1 <- survival::survreg(survival::Surv(data_help$Y, data_help$C) ~ data_help$K + data_help$X + data_help$L, dist = "gaussian") alpha_0_out <- summary(fit_stage_1)$table[1, 1] alpha_1_out <- summary(fit_stage_1)$table[2, 1] alpha_2_out <- summary(fit_stage_1)$table[3, 1] alpha_3_out <- summary(fit_stage_1)$table[4, 1] sigma_1_out <- fit_stage_1$scale ######### Stage 2 ######### mu <- fit_stage_1$linear.predictors Y_adj <- data_help$C * data_help$Y + (1 - data_help$C) * (mu + (sigma_1_out * stats::dnorm((data_help$Y - mu)/sigma_1_out, mean = 0, sd = 1)/(1 - stats::pnorm((data_help$Y - mu)/sigma_1_out, mean = 0, sd = 1)))) Y_tilde <- Y_adj - mean(Y_adj) - alpha_1_out * (data_help$K - mean(data_help$K)) fit_stage_2 <- stats::lm(Y_tilde ~ data_help$X) alpha_4_out <- summary(fit_stage_2)$coefficients[1, 1] alpha_XY_out <- summary(fit_stage_2)$coefficients[2, 1] sigma_2_sq_out <- (n - 2)/n * summary(fit_stage_2)$sigma^2 point_estimates <- c(alpha_0_out, alpha_1_out, alpha_2_out, alpha_3_out, sigma_1_out, alpha_4_out, alpha_XY_out, sigma_2_sq_out, mean(Y_adj)) names(point_estimates) <- c("alpha_0", "alpha_1", "alpha_2", "alpha_3", "sigma_1", "alpha_4", "alpha_XY", "sigma_2_sq", "y_adj_bar") } return(point_estimates) }
/scratch/gouwar.j/cran-all/cranData/CIEE/R/point_estimates_ee.R
#' Bootstrap standard error estimates #' #' Function to obtain bootstrap standard error estimates for the parameter #' estimates of the \code{\link{get_estimates}} function, under the generalized #' linear model (GLM) or accelerated failure time (AFT) setting for the analysis #' of a normally-distributed or censored time-to-event primary outcome. #' #' Under the GLM setting for the analysis of a normally-distributed primary #' outcome Y, bootstrap standard error estimates are obtained for the estimates #' of the parameters #' \eqn{\alpha_0, \alpha_1, \alpha_2, \alpha_3, \sigma_1^2, \alpha_4, \alpha_{XY}, \sigma_2^2}{\alpha0, \alpha1, \alpha2, \alpha3, \sigma1^2, \alpha4, \alphaXY, \sigma2^2} #' in the models #' \deqn{Y = \alpha_0 + \alpha_1 \cdot K + \alpha_2 \cdot X + \alpha_3 \cdot L + \epsilon_1, \epsilon_1 \sim N(0,\sigma_1^2)}{Y = \alpha0 + \alpha1*K + \alpha2*X + \alpha3*L + \epsilon1, \epsilon1 ~ N(0,\sigma1^2)} #' \deqn{Y^* = Y - \overline{Y} - \alpha_1 \cdot (K-\overline{K})}{Y* = Y - mean(Y) - \alpha1*(K-mean(K))} #' \deqn{Y^* = \alpha_0 + \alpha_{XY} \cdot X + \epsilon_2, \epsilon_2 \sim N(0,\sigma_2^2),}{Y* = \alpha0 + \alphaXY*X + \epsilon2, \epsilon2 ~ N(0,\sigma2^2),} #' accounting for the additional variability from the 2-stage approach. #' #' Under the AFT setting for the analysis of a censored time-to-event primary #' outcome, bootstrap standard error estimates are similarly obtained of the #' parameter estimates of #' \eqn{\alpha_0, \alpha_1, \alpha_2, \alpha_3, \sigma_1, \alpha_4, \alpha_{XY}, \sigma_2^2}{\alpha0, \alpha1, \alpha2, \alpha3, \sigma1, \alpha4, \alphaXY, \sigma2^2} #' #' @param setting String with value \code{"GLM"} or \code{"AFT"} indicating #' whether standard error estimates are obtained for a #' normally-distributed (\code{"GLM"}) or censored time-to-event #' (\code{"AFT"}) primary outcome \code{Y}. #' @param BS_rep Integer indicating the number of bootstrap samples that are drawn. #' @param Y Numeric input vector for the primary outcome. #' @param X Numeric input vector for the exposure variable. #' @param K Numeric input vector for the intermediate outcome. #' @param L Numeric input vector for the observed confounding factor. #' @param C Numeric input vector for the censoring indicator under the AFT setting #' (must be coded 0 = censored, 1 = uncensored). #' #' @return Returns a vector with the bootstrap standard error estimates #' of the parameter estimates. #' #' @examples #' #' dat <- generate_data(setting = "GLM", n = 100) #' #' # For illustration use here only 100 bootstrap samples, recommended is using 1000 #' bootstrap_se(setting = "GLM", BS_rep = 100, Y = dat$Y, X = dat$X, #' K = dat$K, L = dat$L) #' #' @export #' bootstrap_se <- function(setting = "GLM", BS_rep = 1000, Y = NULL, X = NULL, K = NULL, L = NULL, C = NULL) { if (is.null(setting)) { stop("setting has to be supplied.") } if (is.null(Y) | is.null(X) | is.null(K) | is.null(L)) { stop("Data of one or more variables are not supplied.") } if (setting == "AFT" & is.null(C)) { stop("C has to be supplied for the AFT setting.") } n <- length(Y) if (setting == "GLM") { alpha_0_SE_BS_help <- alpha_1_SE_BS_help <- alpha_2_SE_BS_help <- alpha_3_SE_BS_help <- sigma_1_sq_SE_BS_help <- alpha_4_SE_BS_help <- alpha_XY_SE_BS_help <- sigma_2_sq_SE_BS_help <- NULL } if (setting == "AFT") { alpha_0_SE_BS_help <- alpha_1_SE_BS_help <- alpha_2_SE_BS_help <- alpha_3_SE_BS_help <- sigma_1_SE_BS_help <- alpha_4_SE_BS_help <- alpha_XY_SE_BS_help <- sigma_2_sq_SE_BS_help <- NULL } for (rep in 1:BS_rep) { id <- sample(1:n, n, replace = TRUE) if (setting == "GLM") { data_id <- data.frame(X = X[id], L = L[id], K = K[id], Y = Y[id]) estimates <- get_estimates(setting = setting, Y = data_id$Y, X = data_id$X, K = data_id$K, L = data_id$L) } if (setting == "AFT") { data_id <- data.frame(X = X[id], L = L[id], K = K[id], Y = Y[id], T = T[id], C = C[id]) estimates <- get_estimates(setting = setting, Y = data_id$Y, X = data_id$X, K = data_id$K, L = data_id$L, C = data_id$C) } alpha_0_SE_BS_help[rep] <- estimates[names(estimates) == "alpha_0"] alpha_1_SE_BS_help[rep] <- estimates[names(estimates) == "alpha_1"] alpha_2_SE_BS_help[rep] <- estimates[names(estimates) == "alpha_2"] alpha_3_SE_BS_help[rep] <- estimates[names(estimates) == "alpha_3"] if (setting == "GLM") { sigma_1_sq_SE_BS_help[rep] <- estimates[names(estimates) == "sigma_1_sq"] } if (setting == "AFT") { sigma_1_SE_BS_help[rep] <- estimates[names(estimates) == "sigma_1"] } alpha_4_SE_BS_help[rep] <- estimates[names(estimates) == "alpha_4"] alpha_XY_SE_BS_help[rep] <- estimates[names(estimates) == "alpha_XY"] sigma_2_sq_SE_BS_help[rep] <- estimates[names(estimates) == "sigma_2_sq"] } if (setting == "GLM") { theta_bootstrap_se <- c(stats::sd(alpha_0_SE_BS_help,na.rm=T), stats::sd(alpha_1_SE_BS_help,na.rm=T), stats::sd(alpha_2_SE_BS_help,na.rm=T), stats::sd(alpha_3_SE_BS_help,na.rm=T), stats::sd(sigma_1_sq_SE_BS_help,na.rm=T), stats::sd(alpha_4_SE_BS_help,na.rm=T), stats::sd(alpha_XY_SE_BS_help,na.rm=T), stats::sd(sigma_2_sq_SE_BS_help,na.rm=T)) names(theta_bootstrap_se) <- c("alpha_0", "alpha_1", "alpha_2", "alpha_3", "sigma_1_sq", "alpha_4", "alpha_XY", "sigma_2_sq") } if (setting == "AFT") { theta_bootstrap_se <- c(stats::sd(alpha_0_SE_BS_help,na.rm=T), stats::sd(alpha_1_SE_BS_help,na.rm=T), stats::sd(alpha_2_SE_BS_help,na.rm=T), stats::sd(alpha_3_SE_BS_help,na.rm=T), stats::sd(sigma_1_SE_BS_help,na.rm=T), stats::sd(alpha_4_SE_BS_help,na.rm=T), stats::sd(alpha_XY_SE_BS_help,na.rm=T), stats::sd(sigma_2_sq_SE_BS_help,na.rm=T)) names(theta_bootstrap_se) <- c("alpha_0", "alpha_1", "alpha_2", "alpha_3", "sigma_1", "alpha_4", "alpha_XY", "sigma_2_sq") } return(theta_bootstrap_se) }
/scratch/gouwar.j/cran-all/cranData/CIEE/R/se_estimates_bootstrap.R
#' Naive standard error estimates #' #' Function to obtain naive standard error estimates for the parameter #' estimates of the \code{\link{get_estimates}} function, under the GLM or AFT #' setting for the analysis of a normally-distributed or censored time-to-event #' primary outcome. #' #' Under the GLM setting for the analysis of a normally-distributed primary #' outcome Y, naive standard error estimates are obtained for the estimates of the #' parameters #' \eqn{\alpha_0, \alpha_1, \alpha_2, \alpha_3, \alpha_4, \alpha_{XY}}{\alpha0, \alpha1, \alpha2, \alpha3, \alpha4, \alphaXY} #' in the models #' \deqn{Y = \alpha_0 + \alpha_1 \cdot K + \alpha_2 \cdot X + \alpha_3 \cdot L + \epsilon_1, \epsilon_1 \sim N(0,\sigma_1^2)}{Y = \alpha0 + \alpha1*K + \alpha2*X + \alpha3*L + \epsilon1, \epsilon1 ~ N(0,\sigma1^2)} #' \deqn{Y^* = Y - \overline{Y} - \alpha_1 \cdot (K-\overline{K})}{Y* = Y - mean(Y) - \alpha1*(K-mean(K))} #' \deqn{Y^* = \alpha_0 + \alpha_{XY} \cdot X + \epsilon_2, \epsilon_2 \sim N(0,\sigma_2^2),}{Y* = \alpha0 + \alphaXY*X + \epsilon2, \epsilon2 ~ N(0,\sigma2^2),} #' using the \code{\link[stats]{lm}} function, without accounting for the #' additional variability due to the 2-stage approach. #' #' Under the AFT setting for the analysis of a censored time-to-event primary #' outcome, bootstrap standard error estimates are similarly obtained of the #' parameter estimates of #' \eqn{\alpha_0, \alpha_1, \alpha_2, \alpha_3, \alpha_4, \alpha_{XY}}{\alpha0, \alpha1, \alpha2, \alpha3, \alpha4, \alphaXY} #' from the output of the \code{\link[survival]{survreg}} and #' \code{\link[stats]{lm}} functions. #' #' @param setting String with value \code{"GLM"} or \code{"AFT"} indicating #' whether standard error estimates are obtained for a #' normally-distributed (\code{"GLM"}) or censored time-to-event #' (\code{"AFT"}) primary outcome \code{Y}. #' @param Y Numeric input vector for the primary outcome. #' @param X Numeric input vector for the exposure variable. #' @param K Numeric input vector for the intermediate outcome. #' @param L Numeric input vector for the observed confounding factor. #' @param C Numeric input vector for the censoring indicator under the AFT setting #' (must be coded 0 = censored, 1 = uncensored). #' #' @return Returns a vector with the naive standard error estimates of the #' parameter estimates. #' #' @examples #' #' dat <- generate_data(setting = "GLM") #' naive_se(setting = "GLM", Y = dat$Y, X = dat$X, K = dat$K, L = dat$L) #' #' @export #' naive_se <- function(setting = "GLM", Y = NULL, X = NULL, K = NULL, L = NULL, C = NULL) { if (!requireNamespace("survival", quietly = TRUE)) { stop("Pkg needed for this function to work. Please install it.", call. = FALSE) } if (is.null(setting)) { stop("setting has to be supplied.") } if (is.null(Y) | is.null(X) | is.null(K) | is.null(L)) { stop("Data of one or more variables are not supplied.") } if (setting == "AFT" & is.null(C)) { stop("C has to be supplied for the AFT setting.") } n <- length(Y) if (setting == "GLM") { data_help <- data.frame(Y = Y, X = X, K = K, L = L) data_help <- data_help[stats::complete.cases(data_help), ] ######### Stage 1 ######### fit_stage_1 <- stats::lm(data_help$Y ~ data_help$K + data_help$X + data_help$L) alpha_1_out <- summary(fit_stage_1)$coefficients[2, 1] alpha_0_SE_out <- summary(fit_stage_1)$coefficients[1, 2] alpha_1_SE_out <- summary(fit_stage_1)$coefficients[2, 2] alpha_2_SE_out <- summary(fit_stage_1)$coefficients[3, 2] alpha_3_SE_out <- summary(fit_stage_1)$coefficients[4, 2] ######### Stage 2 ######### Y_tilde <- data_help$Y - mean(data_help$Y) - alpha_1_out * (data_help$K - mean(data_help$K)) fit_stage_2 <- stats::lm(Y_tilde ~ data_help$X) alpha_4_SE_out <- summary(fit_stage_2)$coefficients[1, 2] alpha_XY_SE_out <- summary(fit_stage_2)$coefficients[2, 2] } if (setting == "AFT") { data_help <- data.frame(Y = Y, X = X, K = K, L = L, C = C) data_help <- data_help[stats::complete.cases(data_help), ] ######### Stage 1 ######### fit_stage_1 <- survival::survreg(survival::Surv(data_help$Y, data_help$C) ~ data_help$K + data_help$X + data_help$L, dist = "gaussian") alpha_1_out <- summary(fit_stage_1)$table[2, 1] sigma_1_out <- fit_stage_1$scale alpha_0_SE_out <- summary(fit_stage_1)$table[1, 2] alpha_1_SE_out <- summary(fit_stage_1)$table[2, 2] alpha_2_SE_out <- summary(fit_stage_1)$table[3, 2] alpha_3_SE_out <- summary(fit_stage_1)$table[4, 2] ######### Stage 2 ######### mu <- fit_stage_1$linear.predictors Y_adj <- data_help$C * data_help$Y + (1 - data_help$C) * (mu + (sigma_1_out * stats::dnorm((data_help$Y - mu)/sigma_1_out, mean = 0, sd = 1)/ (1 - stats::pnorm((data_help$Y - mu)/sigma_1_out, mean = 0, sd = 1)))) Y_tilde <- Y_adj - mean(Y_adj) - alpha_1_out * (data_help$K - mean(data_help$K)) fit_stage_2 <- stats::lm(Y_tilde ~ data_help$X) alpha_4_SE_out <- summary(fit_stage_2)$coefficients[1, 2] alpha_XY_SE_out <- summary(fit_stage_2)$coefficients[2, 2] } SE_estimates <- c(alpha_0_SE_out, alpha_1_SE_out, alpha_2_SE_out, alpha_3_SE_out, NA, alpha_4_SE_out, alpha_XY_SE_out, NA) names(SE_estimates) <- c("alpha_0", "alpha_1", "alpha_2", "alpha_3", "sigma_1_sq", "alpha_4", "alpha_XY", "sigma_2_sq") return(SE_estimates) }
/scratch/gouwar.j/cran-all/cranData/CIEE/R/se_estimates_naive.R
#' Sandwich standard error estimates #' #' Function to obtain consistent and robust sandwich standard error estimates #' based on estimating equations, for the parameter estimates of the #' \code{\link{get_estimates}} function, under the GLM or AFT setting #' for the analysis of a normally-distributed or censored time-to-event primary #' outcome. #' #' Under the GLM setting for the analysis of a normally-distributed primary #' outcome Y, robust sandwich standard error estimates are obtained for the #' estimates of the parameters #' \eqn{\alpha_0, \alpha_1, \alpha_2, \alpha_3, \sigma_1^2, \alpha_4, \alpha_{XY}, \sigma_2^2}{\alpha0, \alpha1, \alpha2, \alpha3, \sigma1^2, \alpha4, \alphaXY, \sigma2^2} #' in the model #' \deqn{Y = \alpha_0 + \alpha_1 \cdot K + \alpha_2 \cdot X + \alpha_3 \cdot L + \epsilon_1, \epsilon_1 \sim N(0,\sigma_1^2)}{Y = \alpha0 + \alpha1*K + \alpha2*X + \alpha3*L + \epsilon1, \epsilon1 ~ N(0,\sigma1^2)} #' \deqn{Y^* = Y - \overline{Y} - \alpha_1 \cdot (K-\overline{K})}{Y* = Y - mean(Y) - \alpha1*(K-mean(K))} #' \deqn{Y^* = \alpha_0 + \alpha_{XY} \cdot X + \epsilon_2, \epsilon_2 \sim N(0,\sigma_2^2)}{Y* = \alpha0 + \alphaXY*X + \epsilon2, \epsilon2 ~ N(0,\sigma2^2)} #' by using the score and hessian matrices of the parameters. #' #' Under the AFT setting for the analysis of a censored time-to-event primary #' outcome, robust sandwich standard error estimates are similarly obtained of #' the parameter estimates of #' \eqn{\alpha_0, \alpha_1, \alpha_2, \alpha_3, \sigma_1, \alpha_4, \alpha_{XY}, \sigma_2^2}{\alpha0, \alpha1, \alpha2, \alpha3, \sigma1, \alpha4, \alphaXY, \sigma2^2}. #' For more details and the underlying model, see the vignette. #' #' @param setting String with value \code{"GLM"} or \code{"AFT"} indicating #' whether standard error estimates are obtained for a #' normally-distributed (\code{"GLM"}) or censored time-to-event #' (\code{"AFT"}) primary outcome \code{Y}. #' @param scores Score matrix of the parameters, which can be obtained using the #' \code{\link{scores}} function. #' @param hessian Hessian matrix of the parameters, which can be obtained using the #' \code{\link{hessian}} function. #' #' @return Returns a vector with the CIEE sandwich standard error estimates #' of the parameter estimates. #' #' @examples #' #' # Generate data including Y, K, L, X under the GLM setting #' dat <- generate_data(setting = "GLM") #' #' # Obtain estimating functions expressions #' estfunct <- est_funct_expr(setting = "GLM") #' #' # Obtain point estimates of the parameters #' estimates <- get_estimates(setting = "GLM", Y = dat$Y, X = dat$X, #' K = dat$K, L = dat$L) #' #' # Obtain matrices with all first and second derivatives #' derivobj <- deriv_obj(setting = "GLM", logL1 = estfunct$logL1, #' logL2 = estfunct$logL2, Y = dat$Y, X = dat$X, #' K = dat$K, L = dat$L, estimates = estimates) #' #' # Obtain score and hessian matrices #' results_scores <- scores(derivobj) #' results_hessian <- hessian(derivobj) #' #' # Obtain sandwich standard error estimates of the parameters #' sandwich_se(scores = results_scores, hessian = results_hessian) #' #' @export #' sandwich_se <- function(setting = "GLM", scores = NULL, hessian = NULL) { if (is.null(scores) | is.null(hessian)) { stop("scores and hessian have to be supplied.") } n <- dim(scores)[1] ### A_n matrix ### A_n <- matrix(, nrow = 8, ncol = 8) for (A_n_i in 1:8) { for (A_n_j in 1:8) { A_n[A_n_i, A_n_j] <- sum(hessian[, A_n_i, A_n_j]) } } A_n <- -(1/n) * A_n ### B_n matrix ### B_n <- matrix(, nrow = 8, ncol = 8) for (B_n_i in 1:8) { for (B_n_j in 1:8) { B_n[B_n_i, B_n_j] <- sum(scores[, B_n_i] * scores[, B_n_j]) } } B_n <- (1/n) * B_n ### C_n matrix ### C_n <- solve(A_n) %*% B_n %*% t(solve(A_n)) ### Variance estimates of coefficients ### theta_EE_se <- (1/n) * diag(C_n) theta_EE_se <- sqrt(theta_EE_se) if (setting == "GLM") { names(theta_EE_se) <- c("alpha_0", "alpha_1", "alpha_2", "alpha_3", "sigma_1_sq", "alpha_4", "alpha_XY", "sigma_2_sq") } if (setting == "AFT") { names(theta_EE_se) <- c("alpha_0", "alpha_1", "alpha_2", "alpha_3", "sigma_1", "alpha_4", "alpha_XY", "sigma_2_sq") } return(theta_EE_se) }
/scratch/gouwar.j/cran-all/cranData/CIEE/R/se_estimates_sandwich.R
#' Structural equation modeling approach #' #' Function which uses the \code{\link[lavaan]{sem}} function in the #' \code{lavaan} package to fit the model #' \deqn{L = \alpha_0 + \alpha_1 \cdot X + \epsilon_1, \epsilon_1 \sim N(0,\sigma_1^2)}{L = \alpha0 + \alpha1*X + \epsilon1, \epsilon1 ~ N(0,\sigma1^2)} #' \deqn{K = \alpha_2 + \alpha_3 \cdot X + \alpha_4 \cdot L + \epsilon_2, \epsilon_2 \sim~ N(0,\sigma_2^2)}{K = \alpha2 + \alpha3*X + \alpha4*L + \epsilon2, \epsilon2 ~ N(0,\sigma2^2)} #' \deqn{Y = \alpha_5 + \alpha_6 \cdot K + \alpha_{XY} \cdot X + \epsilon_3, \epsilon_3 \sim N(0,\sigma_3^2)}{Y = \alpha5 + \alpha6*K + \alphaXY*X + \epsilon3, \epsilon3 ~ N(0,\sigma3^2)} #' in order to obtain point and standard error estimates #' of the parameters #' \eqn{\alpha_1, \alpha_3, \alpha_4, \alpha_6, \alpha_{XY}}{\alpha1, \alpha3, \alpha4, \alpha6, \alphaXY} #' for the GLM setting. #' See the vignette for more details. #' #' @param Y Numeric input vector for the primary outcome. #' @param X Numeric input vector for the exposure variable. #' @param K Numeric input vector for the intermediate outcome. #' @param L Numeric input vector for the observed confounding factor. #' #' @return Returns a list with point estimates of the parameters #' (\code{point_estimates}), standard error estimates #' (\code{SE_estimates}) and p-values from large-sample #' Wald-type tests (\code{pvalues}). #' #' @examples #' #' dat <- generate_data(setting = "GLM") #' sem_appl(Y = dat$Y, X = dat$X, K = dat$K, L = dat$L) #' #' @export #' sem_appl <- function(Y = NULL, X = NULL, K = NULL, L = NULL) { if (!requireNamespace("lavaan", quietly = TRUE)) { stop("Pkg needed for this function to work. Please install it.", call. = FALSE) } if (is.null(Y) | is.null(X) | is.null(K) | is.null(L)) { stop("Data of one or more variables are not supplied.") } data_help <- data.frame(Y = Y, X = X, K = K, L = L) data_help <- data_help[stats::complete.cases(data_help), ] model <- " L ~ X K ~ X + L Y ~ K + X " fit <- lavaan::sem(model, data = data_help) point_estimates <- c(fit@Fit@est[1], fit@Fit@est[2], fit@Fit@est[3], fit@Fit@est[4], fit@Fit@est[5]) SE_estimates <- c(fit@Fit@se[1], fit@Fit@se[2], fit@Fit@se[3], fit@Fit@se[4], fit@Fit@se[5]) pvalues <- 2 * stats::pnorm(-abs(point_estimates/SE_estimates)) names(point_estimates) <- names(SE_estimates) <- names(pvalues) <- c("alpha_1", "alpha_3", "alpha_4", "alpha_6", "alpha_XY") return(list(point_estimates = point_estimates, SE_estimates = SE_estimates, pvalues = pvalues)) }
/scratch/gouwar.j/cran-all/cranData/CIEE/R/sem_functions.R
#' Summary function. #' #' Summary function for the \code{\link{ciee}} and \code{\link{ciee_loop}} #' functions. #' #' @param object \code{ciee} object (output of the \code{\link{ciee}} #' or \code{\link{ciee_loop}} function). #' @param ... Additional arguments affecting the summary produced. #' #' @return Formatted data frames of the results of all computed methods. #' #' @examples #' #' maf <- 0.2 #' n <- 1000 #' dat <- generate_data(n = n, maf = maf) #' datX <- data.frame(X = dat$X) #' names(datX)[1] <- "X1" #' for (i in 2:10){ #' X <- stats::rbinom(n, size = 2, prob = maf) #' datX$X <- X #' names(datX)[i] <- paste("X", i, sep="") #' } #' #' results1 <- ciee(Y = dat$Y, X = datX$X1, K = dat$K, L = dat$L) #' summary(results1) #' #' results2 <- ciee_loop(Y = dat$Y, X = datX, K = dat$K, L = dat$L) #' summary(results2) #' #' @export #' summary.ciee <- function(object = NULL, ...) { if (is.null(object)) { stop("ciee output has to be supplied.") } res_out <- NULL if ("results_ee" %in% names(object)) { res_ee_out <- data.frame(point_estimates = object$results_ee$point_estimates, SE_estimates = object$results_ee$SE_estimates, wald_test_stat = object$results_ee$wald_test_stat, pvalues = object$results_ee$pvalues) rownames(res_ee_out) <- paste("CIEE", rownames(res_ee_out), sep = "_") print(paste("Results based on estimating equations.")) print(res_ee_out) res_out <- res_ee_out[,c(1,2,4)] } if ("results_mult_reg" %in% names(object)) { res_mr_out <- data.frame(point_estimates = object$results_mult_reg$point_estimates, SE_estimates = object$results_mult_reg$SE_estimates, pvalues = object$results_mult_reg$pvalues) rownames(res_mr_out) <- paste("MR", rownames(res_mr_out), sep = "_") print(paste("Results based on traditional multiple regression.")) print(res_mr_out) res_out <- rbind(res_out, res_mr_out) } if ("results_res_reg" %in% names(object)) { res_rr_out <- data.frame(point_estimates = object$results_res_reg$point_estimates, SE_estimates = object$results_res_reg$SE_estimates, pvalues = object$results_res_reg$pvalues) rownames(res_rr_out) <- paste("RR", rownames(res_rr_out), sep = "_") print(paste("Results based on traditional regression of residuals.")) print(res_rr_out) res_out <- rbind(res_out, res_rr_out) } if ("results_sem" %in% names(object)) { res_sem_out <- data.frame(point_estimates = object$results_sem$point_estimates, SE_estimates = object$results_sem$SE_estimates, pvalues = object$results_sem$pvalues) rownames(res_sem_out) <- paste("SEM", rownames(res_sem_out), sep = "_") print(paste("Results based on structural equation modeling.")) print(res_sem_out) res_out <- rbind(res_out, res_sem_out) } invisible(res_out) }
/scratch/gouwar.j/cran-all/cranData/CIEE/R/summary_function.R
#' Traditional regression approaches. #' #' Functions to fit traditional regression approaches for a quantitative #' normally-distributed primary outcome (\code{setting} = \code{"GLM"}) #' and a censoredtime-to-event primary outcome (\code{setting} = \code{"AFT"}). #' \code{\link{mult_reg}} fits the multiple regression approach and #' \code{\link{res_reg}} computes the regression of residuals approach. #' #' In more detail, for a quantitative normally-distributed primary outcome #' \code{Y}, \code{\link{mult_reg}} fits the model #' \deqn{Y = \alpha_0 + \alpha_1 \cdot K + \alpha_{XY} \cdot X + \alpha_2 \cdot L + \epsilon}{Y = \alpha0 + \alpha1*K + \alphaXY*X + \alpha2*L + \epsilon} #' and obtains point and standard error estimates for the parameters #' \eqn{\alpha_0, \alpha_1, \alpha_{XY}, \alpha_2}{\alpha0, \alpha1, \alphaXY, \alpha2}. #' \code{\link{res_reg}} obtains point and standard #' error estimates for the parameters #' \eqn{\alpha_0, \alpha_1, \alpha_2, \alpha_3, \alpha_{XY}}{\alpha0, \alpha1, \alpha2, \alpha3, \alphaXY} #' by fitting the models #' \deqn{Y = \alpha_0 + \alpha_1 \cdot K + \alpha_2 \cdot L + \epsilon_1}{Y = \alpha0 + \alpha1*K + \alpha2*L + \epsilon1,} #' \deqn{\widehat{\epsilon}_1 = \alpha_3 + \alpha_{XY} \cdot X + \epsilon_2}{hat(\epsilon1) = \alpha3 + \alphaXY*X + \epsilon2.} #' Both functions use the \code{\link[stats]{lm}} function and also report the #' provided p-values from t-tests that each parameter equals 0. #' For the analysis of a censored time-to-event primary outcome \code{Y}, #' only the multiple regression approach is implemented. Here, #' \code{\link{mult_reg}} fits the according censored regression model to obtain #' coefficient and standard error estimates as well as p-values from large-sample #' Wald-type tests by using the \code{\link[survival]{survreg}} function. #' See the vignette for more details. #' #' @param setting String with value \code{"GLM"} or \code{"AFT"} indicating #' whether the approaches are fitted for a normally-distributed #' primary outcome \code{Y} (\code{"GLM"}) or a censored #' time-to-event primary outcome \code{Y} (\code{"AFT"}). Under #' the \code{"AFT"} setting, only \code{mult_reg} is #' available. #' @param Y Numeric input vector of the primary outcome. #' @param X Numeric input vector of the exposure variable. #' @param K Numeric input vector of the intermediate outcome. #' @param L Numeric input vector of the observed confounding factor. #' @param C Numeric input vector of the censoring indicator under the AFT setting #' (must be coded 0 = censored, 1 = uncensored). #' #' @return Returns a list with point estimates of the parameters #' \code{point_estimates}, standard error estimates \code{SE_estimates} #' and p-values \code{pvalues}. #' #' @examples #' #' dat_GLM <- generate_data(setting = "GLM") #' mult_reg(setting = "GLM", Y = dat_GLM$Y, X = dat_GLM$X, K = dat_GLM$K, #' L = dat_GLM$L) #' res_reg(Y = dat_GLM$Y, X = dat_GLM$X, K = dat_GLM$K, L = dat_GLM$L) #' #' dat_AFT <- generate_data(setting = "AFT", a = 0.2, b = 4.75) #' mult_reg(setting = "AFT", Y = dat_AFT$Y, X = dat_AFT$X, K = dat_AFT$K, #' L = dat_AFT$L, C = dat_AFT$C) #' #' @name traditional_regression_functions NULL #' @rdname traditional_regression_functions #' @export mult_reg <- function(setting = "GLM", Y = NULL, X = NULL, K = NULL, L = NULL, C = NULL) { if (!requireNamespace("survival", quietly = TRUE)) { stop("Pkg needed for this function to work. Please install it.", call. = FALSE) } if (is.null(setting)) { stop("setting has to be supplied.") } if (is.null(Y) | is.null(X) | is.null(K) | is.null(L)) { stop("Data of one or more variables are not supplied.") } if (setting == "AFT" & is.null(C)) { stop("C has to be supplied for the AFT setting.") } if (setting == "GLM") { fit_mult_reg <- stats::lm(Y ~ K + X + L) point_estimates <- c(summary(fit_mult_reg)$coefficients[1, 1], summary(fit_mult_reg)$coefficients[2, 1], summary(fit_mult_reg)$coefficients[3, 1], summary(fit_mult_reg)$coefficients[4, 1]) SE_estimates <- c(summary(fit_mult_reg)$coefficients[1, 2], summary(fit_mult_reg)$coefficients[2, 2], summary(fit_mult_reg)$coefficients[3, 2], summary(fit_mult_reg)$coefficients[4, 2]) pvalues <- c(summary(fit_mult_reg)$coefficients[1, 4], summary(fit_mult_reg)$coefficients[2, 4], summary(fit_mult_reg)$coefficients[3, 4], summary(fit_mult_reg)$coefficients[4, 4]) names(point_estimates) <- names(SE_estimates) <- names(pvalues) <- c("alpha_0", "alpha_1", "alpha_XY", "alpha_2") } if (setting == "AFT") { fit_mult_reg <- survival::survreg(survival::Surv(Y, C) ~ K + X + L, dist = "gaussian") point_estimates <- c(summary(fit_mult_reg)$table[1, 1], summary(fit_mult_reg)$table[2, 1], summary(fit_mult_reg)$table[3, 1], summary(fit_mult_reg)$table[4, 1]) SE_estimates <- c(summary(fit_mult_reg)$table[1, 2], summary(fit_mult_reg)$table[2, 2], summary(fit_mult_reg)$table[3, 2], summary(fit_mult_reg)$table[4, 2]) pvalues <- c(summary(fit_mult_reg)$table[1, 4], summary(fit_mult_reg)$table[2, 4], summary(fit_mult_reg)$table[3, 4], summary(fit_mult_reg)$table[4, 4]) names(point_estimates) <- names(SE_estimates) <- names(pvalues) <- c("alpha_0", "alpha_1", "alpha_XY", "alpha_2") } return(list(point_estimates = point_estimates, SE_estimates = SE_estimates, pvalues = pvalues)) } #' @rdname traditional_regression_functions #' @export res_reg <- function(Y = NULL, X = NULL, K = NULL, L = NULL) { if (is.null(Y) | is.null(X) | is.null(K) | is.null(L)) { stop("Data of one or more variables is not supplied.") } data_help <- data.frame(Y = Y, X = X, K = K, L = L) data_help <- data_help[stats::complete.cases(data_help), ] fit_res_reg_1 <- stats::lm(data_help$Y ~ data_help$K + data_help$L) res <- fit_res_reg_1$residuals fit_res_reg_2 <- stats::lm(res ~ data_help$X) point_estimates <- c(summary(fit_res_reg_1)$coefficients[1, 1], summary(fit_res_reg_1)$coefficients[2, 1], summary(fit_res_reg_1)$coefficients[3, 1], summary(fit_res_reg_2)$coefficients[1, 1], summary(fit_res_reg_2)$coefficients[2, 1]) SE_estimates <- c(summary(fit_res_reg_1)$coefficients[1, 2], summary(fit_res_reg_1)$coefficients[2, 2], summary(fit_res_reg_1)$coefficients[3, 2], summary(fit_res_reg_2)$coefficients[1, 2], summary(fit_res_reg_2)$coefficients[2, 2]) pvalues <- c(summary(fit_res_reg_1)$coefficients[1, 4], summary(fit_res_reg_1)$coefficients[2, 4], summary(fit_res_reg_1)$coefficients[3, 4], summary(fit_res_reg_2)$coefficients[1, 4], summary(fit_res_reg_2)$coefficients[2, 4]) names(point_estimates) <- names(SE_estimates) <- names(pvalues) <- c("alpha_0", "alpha_1", "alpha_2", "alpha_3", "alpha_XY") return(list(point_estimates = point_estimates, SE_estimates = SE_estimates, pvalues = pvalues)) }
/scratch/gouwar.j/cran-all/cranData/CIEE/R/traditional_functions.R
## ---- echo=FALSE--------------------------------------------------------- generate_data <- function(setting = "GLM", n = 1000, maf = 0.2, cens = 0.3, a = NULL, b = NULL, aXK = 0.2, aXY = 0.1, aXL = 0, aKY = 0.3, aLK = 0, aLY = 0, aUY = 0, aUL = 0, mu_X = NULL, sd_X = NULL, X_orth_U = TRUE, mu_U = 0, sd_U = 1, mu_K = 0, sd_K = 1, mu_L = 0, sd_L = 1, mu_Y = 0, sd_Y = 1) { U_out <- rnorm(n, mean = mu_U, sd = sd_U) if (setting == "AFT" & (is.null(a) | is.null(b))) { stop("a and b have to be specified under the AFT setting.") } if (X_orth_U == TRUE) { X_out <- rbinom(n, size = 2, prob = maf) } if (X_orth_U == FALSE) { X_out <- pnorm(U_out, mean = mu_X, sd = sd_X) p <- 1 - maf for (j in 1:length(X_out)) { if (X_out[j] < p^2) { X_out[j] <- 0 next } if (X_out[j] >= p^2 & X_out[j] < p^2 + 2 * p * (1 - p)) { X_out[j] <- 1 next } if (X_out[j] >= p^2 + 2 * p * (1 - p)) { X_out[j] <- 2 next } } } L_out <- aUL * U_out + aXL * X_out + rnorm(n, mean = mu_L, sd = sd_L) K_out <- aXK * X_out + aLK * L_out + rnorm(n, mean = mu_K, sd = sd_K) Y_out <- aUY * U_out + aKY * K_out + aXY * X_out + aLY * L_out + rnorm(n, mean = mu_Y, sd = sd_Y) data <- data.frame(Y = Y_out, K = K_out, X = X_out, L = L_out, U = U_out) if (setting == "AFT") { T_help <- exp(Y_out) ### Create censoring indicator and censored times no censoring if (cens == 0) { T_out <- T_help C_out <- rep(1, n) # C_out==0 is censored, C_out==1 is uncensored } if (!cens == 0) { # there is censoring; cens is the percentage of censored data T_cens <- runif(n, min = a, max = b) # a, b for desired censoring rate C_out <- as.numeric(T_help < T_cens) # C==0 censored, C==1 uncensored T_out <- pmin(T_help, T_cens) Y_out <- log(T_out) } cens_out <- sum(abs(C_out - 1))/n data <- data.frame(Y = Y_out, K = K_out, X = X_out, L = L_out, U = U_out, T = T_out, C = C_out) print(paste("The empirical censoring rate obtained through the specified parameters a=", a, " and b=", b, " is ", cens_out, ".", sep = "")) if (abs(cens_out - cens) > 0.1) { warning(paste("This obtained empirical censoring rate is quite different from the desired censoring rate cens=", cens, ". Please check and adapt values for a and b.", sep = "")) } } return(data) } ## ---- echo=FALSE--------------------------------------------------------- mult_reg <- function(setting = "GLM", Y = NULL, X = NULL, K = NULL, L = NULL, C = NULL) { if (!requireNamespace("survival", quietly = TRUE)) { stop("Pkg needed for this function to work. Please install it.", call. = FALSE) } if (is.null(setting)) { stop("setting has to be supplied.") } if (is.null(Y) | is.null(X) | is.null(K) | is.null(L)) { stop("Data of one or more variables are not supplied.") } if (setting == "AFT" & is.null(C)) { stop("C has to be supplied for the AFT setting.") } if (setting == "GLM") { fit_mult_reg <- lm(Y ~ K + X + L) point_estimates <- c(summary(fit_mult_reg)$coefficients[1, 1], summary(fit_mult_reg)$coefficients[2, 1], summary(fit_mult_reg)$coefficients[3, 1], summary(fit_mult_reg)$coefficients[4, 1]) SE_estimates <- c(summary(fit_mult_reg)$coefficients[1, 2], summary(fit_mult_reg)$coefficients[2, 2], summary(fit_mult_reg)$coefficients[3, 2], summary(fit_mult_reg)$coefficients[4, 2]) pvalues <- c(summary(fit_mult_reg)$coefficients[1, 4], summary(fit_mult_reg)$coefficients[2, 4], summary(fit_mult_reg)$coefficients[3, 4], summary(fit_mult_reg)$coefficients[4, 4]) names(point_estimates) <- names(SE_estimates) <- names(pvalues) <- c("alpha_0", "alpha_1", "alpha_XY", "alpha_2") } if (setting == "AFT") { fit_mult_reg <- survival::survreg(survival::Surv(Y, C) ~ K + X + L, dist = "gaussian") point_estimates <- c(summary(fit_mult_reg)$table[1, 1], summary(fit_mult_reg)$table[2, 1], summary(fit_mult_reg)$table[3, 1], summary(fit_mult_reg)$table[4, 1]) SE_estimates <- c(summary(fit_mult_reg)$table[1, 2], summary(fit_mult_reg)$table[2, 2], summary(fit_mult_reg)$table[3, 2], summary(fit_mult_reg)$table[4, 2]) pvalues <- c(summary(fit_mult_reg)$table[1, 4], summary(fit_mult_reg)$table[2, 4], summary(fit_mult_reg)$table[3, 4], summary(fit_mult_reg)$table[4, 4]) names(point_estimates) <- names(SE_estimates) <- names(pvalues) <- c("alpha_0", "alpha_1", "alpha_XY", "alpha_2") } return(list(point_estimates = point_estimates, SE_estimates = SE_estimates, pvalues = pvalues)) } ## ---- echo=FALSE--------------------------------------------------------- res_reg <- function(Y = NULL, X = NULL, K = NULL, L = NULL) { if (is.null(Y) | is.null(X) | is.null(K) | is.null(L)) { stop("Data of one or more variables is not supplied.") } data_help <- data.frame(Y = Y, X = X, K = K, L = L) data_help <- data_help[complete.cases(data_help), ] fit_res_reg_1 <- lm(data_help$Y ~ data_help$K + data_help$L) res <- fit_res_reg_1$residuals fit_res_reg_2 <- lm(res ~ data_help$X) point_estimates <- c(summary(fit_res_reg_1)$coefficients[1, 1], summary(fit_res_reg_1)$coefficients[2, 1], summary(fit_res_reg_1)$coefficients[3, 1], summary(fit_res_reg_2)$coefficients[1, 1], summary(fit_res_reg_2)$coefficients[2, 1]) SE_estimates <- c(summary(fit_res_reg_1)$coefficients[1, 2], summary(fit_res_reg_1)$coefficients[2, 2], summary(fit_res_reg_1)$coefficients[3, 2], summary(fit_res_reg_2)$coefficients[1, 2], summary(fit_res_reg_2)$coefficients[2, 2]) pvalues <- c(summary(fit_res_reg_1)$coefficients[1, 4], summary(fit_res_reg_1)$coefficients[2, 4], summary(fit_res_reg_1)$coefficients[3, 4], summary(fit_res_reg_2)$coefficients[1, 4], summary(fit_res_reg_2)$coefficients[2, 4]) names(point_estimates) <- names(SE_estimates) <- names(pvalues) <- c("alpha_0", "alpha_1", "alpha_2", "alpha_3", "alpha_XY") return(list(point_estimates = point_estimates, SE_estimates = SE_estimates, pvalues = pvalues)) } ## ------------------------------------------------------------------------ dat <- generate_data(setting="GLM", n = 1000, maf = 0.2, cens = 0.3, a = NULL, b = NULL, aUL = 0, aXL = 0, aXK = 0.2, aLK = 0, aUY = 0, aKY = 0.3, aXY = 0.1, aLY = 0, mu_U = 0, sd_U = 1, X_orth_U = TRUE, mu_X = NULL, sd_X = NULL, mu_L = 0, sd_L = 1, mu_K = 0, sd_K = 1, mu_Y = 0, sd_Y = 1) head(dat) mult_reg(setting = "GLM", Y = dat$Y, X = dat$X, K = dat$K, L = dat$L) res_reg(Y = dat$Y, X = dat$X, K = dat$K, L = dat$L) ## ---- echo=FALSE--------------------------------------------------------- sem_appl <- function(setting = "GLM", Y = NULL, X = NULL, K = NULL, L = NULL) { if (!requireNamespace("lavaan", quietly = TRUE)) { stop("Pkg needed for this function to work. Please install it.", call. = FALSE) } if (is.null(setting)) { stop("setting has to be supplied.") } if (setting == "AFT") { stop("Only GLM setting is implemented.") } if (is.null(Y) | is.null(X) | is.null(K) | is.null(L)) { stop("Data of one or more variables are not supplied.") } data_help <- data.frame(Y = Y, X = X, K = K, L = L) data_help <- data_help[complete.cases(data_help), ] model <- " L ~ X K ~ X + L Y ~ K + X " fit <- lavaan::sem(model, data = data_help) point_estimates <- c(fit@Fit@est[1], fit@Fit@est[2], fit@Fit@est[3], fit@Fit@est[4], fit@Fit@est[5]) SE_estimates <- c(fit@Fit@se[1], fit@Fit@se[2], fit@Fit@se[3], fit@Fit@se[4], fit@Fit@se[5]) pvalues <- 2 * pnorm(-abs(point_estimates/SE_estimates)) names(point_estimates) <- names(SE_estimates) <- names(pvalues) <- c("alpha_1", "alpha_3", "alpha_4", "alpha_6", "alpha_XY") return(list(point_estimates = point_estimates, SE_estimates = SE_estimates, pvalues = pvalues)) } ## ------------------------------------------------------------------------ sem_appl(Y = dat$Y, X = dat$X, K = dat$K, L = dat$L) ## ---- echo=FALSE--------------------------------------------------------- est_funct_expr <- function(setting = "GLM") { if (is.null(setting)) { stop("setting has to be supplied.") } if (setting == "GLM") { logL1 <- expression(log((1/sqrt(sigma1sq)) * dnorm((y_i - alpha0 - alpha1 * k_i - alpha2 * x_i - alpha3 * l_i)/ sqrt(sigma1sq), mean = 0, sd = 1))) logL2 <- expression(log((1/sqrt(sigma2sq)) * dnorm((y_i - y_bar - alpha1 * (k_i - k_bar) - alpha4 - alphaXY * x_i)/ sqrt(sigma2sq), mean = 0, sd = 1))) } if (setting == "AFT") { logL1 <- expression(-c_i * log(sigma1) + c_i * log(dnorm((y_i - alpha0 - alpha1 * k_i - alpha2 * x_i - alpha3 * l_i)/sigma1, mean = 0, sd = 1)) + (1 - c_i) * log(1 - pnorm((y_i - alpha0 - alpha1 * k_i - alpha2 * x_i - alpha3 * l_i)/ sigma1, mean = 0, sd = 1))) logL2 <- expression(log((1/sqrt(sigma2sq)) * dnorm(((c_i * y_i + (1 - c_i) * ((alpha0 + alpha1 * k_i + alpha2 * x_i + alpha3 * l_i) + (sigma1 * dnorm((y_i - alpha0 - alpha1 * k_i - alpha2 * x_i - alpha3 * l_i)/sigma1, mean = 0, sd = 1)/(1 - pnorm((y_i - alpha0 - alpha1 * k_i - alpha2 * x_i - alpha3 * l_i)/sigma1, mean = 0, sd = 1))))) - y_adj_bar - alpha1 * (k_i - k_bar) - alpha4 - alphaXY * x_i)/sqrt(sigma2sq), mean = 0, sd = 1))) } return(list(logL1 = logL1, logL2 = logL2)) } ## ------------------------------------------------------------------------ estfunct <- est_funct_expr(setting="GLM") estfunct est_funct_expr(setting = "AFT") ## ---- echo=FALSE--------------------------------------------------------- get_estimates <- function(setting = "GLM", Y = NULL, X = NULL, K = NULL, L = NULL, C = NULL) { if (!requireNamespace("survival", quietly = TRUE)) { stop("Pkg needed for this function to work. Please install it.", call. = FALSE) } if (is.null(setting)) { stop("setting has to be supplied.") } if (is.null(Y) | is.null(X) | is.null(K) | is.null(L)) { stop("Data of one or more variables are not supplied.") } if (setting == "AFT" & is.null(C)) { stop("C has to be supplied for the AFT setting.") } n <- length(Y) if (setting == "GLM") { data_help <- data.frame(Y = Y, X = X, K = K, L = L) data_help <- data_help[complete.cases(data_help), ] ######### Stage 1 ######### fit_stage_1 <- lm(data_help$Y ~ data_help$K + data_help$X + data_help$L) alpha_0_out <- summary(fit_stage_1)$coefficients[1, 1] alpha_1_out <- summary(fit_stage_1)$coefficients[2, 1] alpha_2_out <- summary(fit_stage_1)$coefficients[3, 1] alpha_3_out <- summary(fit_stage_1)$coefficients[4, 1] sigma_1_sq_out <- (n - 4)/n * summary(fit_stage_1)$sigma^2 ######### Stage 2 ######### Y_tilde <- data_help$Y - mean(data_help$Y) - alpha_1_out * (data_help$K - mean(data_help$K)) fit_stage_2 <- lm(Y_tilde ~ data_help$X) alpha_4_out <- summary(fit_stage_2)$coefficients[1, 1] alpha_XY_out <- summary(fit_stage_2)$coefficients[2, 1] sigma_2_sq_out <- (n - 2)/n * summary(fit_stage_2)$sigma^2 point_estimates <- c(alpha_0_out, alpha_1_out, alpha_2_out, alpha_3_out, sigma_1_sq_out, alpha_4_out, alpha_XY_out, sigma_2_sq_out) names(point_estimates) <- c("alpha_0", "alpha_1", "alpha_2", "alpha_3", "sigma_1_sq", "alpha_4", "alpha_XY", "sigma_2_sq") } if (setting == "AFT") { data_help <- data.frame(Y = Y, X = X, K = K, L = L, C = C) data_help <- data_help[complete.cases(data_help), ] ######### Stage 1 ######### fit_stage_1 <- survival::survreg(survival::Surv(data_help$Y, data_help$C) ~ data_help$K + data_help$X + data_help$L, dist = "gaussian") alpha_0_out <- summary(fit_stage_1)$table[1, 1] alpha_1_out <- summary(fit_stage_1)$table[2, 1] alpha_2_out <- summary(fit_stage_1)$table[3, 1] alpha_3_out <- summary(fit_stage_1)$table[4, 1] sigma_1_out <- fit_stage_1$scale ######### Stage 2 ######### mu <- fit_stage_1$linear.predictors Y_adj <- data_help$C * data_help$Y + (1 - data_help$C) * (mu + (sigma_1_out * dnorm((data_help$Y - mu)/sigma_1_out, mean = 0, sd = 1)/(1 - pnorm((data_help$Y - mu)/sigma_1_out, mean = 0, sd = 1)))) Y_tilde <- Y_adj - mean(Y_adj) - alpha_1_out * (data_help$K - mean(data_help$K)) fit_stage_2 <- lm(Y_tilde ~ data_help$X) alpha_4_out <- summary(fit_stage_2)$coefficients[1, 1] alpha_XY_out <- summary(fit_stage_2)$coefficients[2, 1] sigma_2_sq_out <- (n - 2)/n * summary(fit_stage_2)$sigma^2 point_estimates <- c(alpha_0_out, alpha_1_out, alpha_2_out, alpha_3_out, sigma_1_out, alpha_4_out, alpha_XY_out, sigma_2_sq_out, mean(Y_adj)) names(point_estimates) <- c("alpha_0", "alpha_1", "alpha_2", "alpha_3", "sigma_1", "alpha_4", "alpha_XY", "sigma_2_sq", "y_adj_bar") } return(point_estimates) } ## ------------------------------------------------------------------------ estimates <- get_estimates(setting = "GLM", Y = dat$Y, X = dat$X, K = dat$K, L = dat$L) estimates ## ---- echo=FALSE--------------------------------------------------------- deriv_obj <- function(setting = "GLM", logL1 = NULL, logL2 = NULL, Y = NULL, X = NULL, K = NULL, L = NULL, C = NULL, estimates = NULL) { if (is.null(setting) | is.null(logL1) | is.null(logL2) | is.null(estimates)) { stop("One or more arguments of the function are missing.") } if (is.null(Y) | is.null(X) | is.null(K) | is.null(L)) { stop("Data of one or more variables are not supplied.") } if (setting == "AFT" & is.null(C)) { stop("C has to be supplied for the AFT setting.") } n <- length(Y) if (setting == "GLM") { data_help <- data.frame(Y = Y, X = X, K = K, L = L) data_help <- data_help[complete.cases(data_help), ] U12345_i <- deriv(expr = logL1, namevec = c("alpha0", "alpha1", "alpha2", "alpha3", "sigma1sq", "alpha4", "alphaXY", "sigma2sq"), function.arg = c("y_i", "k_i", "x_i", "l_i", "alpha0", "alpha1", "alpha2", "alpha3", "sigma1sq"), func = T, hessian = T) U678_i <- deriv(expr = logL2, namevec = c("alpha0", "alpha1", "alpha2", "alpha3", "sigma1sq", "alpha4", "alphaXY", "sigma2sq"), function.arg = c("y_i", "k_i", "x_i", "y_bar", "k_bar", "alpha1", "alpha4", "alphaXY", "sigma2sq"), func = T, hessian = T) logL1_deriv <- attributes(U12345_i(y_i = data_help$Y, k_i = data_help$K, x_i = data_help$X, l_i = data_help$L, alpha0 = estimates[names(estimates) == "alpha_0"], alpha1 = estimates[names(estimates) == "alpha_1"], alpha2 = estimates[names(estimates) == "alpha_2"], alpha3 = estimates[names(estimates) == "alpha_3"], sigma1sq = estimates[names(estimates) == "sigma_1_sq"])) logL2_deriv <- attributes(U678_i(y_i = data_help$Y, k_i = data_help$K, x_i = data_help$X, y_bar = mean(data_help$Y), k_bar = mean(data_help$K), alpha1 = estimates[names(estimates) == "alpha_1"], alpha4 = estimates[names(estimates) == "alpha_4"], alphaXY = estimates[names(estimates) == "alpha_XY"], sigma2sq = estimates[names(estimates) == "sigma_2_sq"])) deriv_obj <- list(logL1_deriv = logL1_deriv, logL2_deriv = logL2_deriv) } if (setting == "AFT") { data_help <- data.frame(Y = Y, X = X, K = K, L = L, C = C) data_help <- data_help[complete.cases(data_help), ] U12345_i <- deriv(expr = logL1, namevec = c("alpha0", "alpha1", "alpha2", "alpha3", "sigma1", "alpha4", "alphaXY", "sigma2sq"), function.arg = c("y_i", "c_i", "k_i", "x_i", "l_i", "alpha0", "alpha1", "alpha2", "alpha3", "sigma1"), func = T, hessian = T) U678_i <- deriv(expr = logL2, namevec = c("alpha0", "alpha1", "alpha2", "alpha3", "sigma1", "alpha4", "alphaXY", "sigma2sq"), function.arg = c("y_i", "c_i", "k_i", "x_i", "l_i", "y_adj_bar", "k_bar", "alpha0", "alpha1", "alpha2", "alpha3", "sigma1", "alpha4", "alphaXY", "sigma2sq"), func = T, hessian = T) logL1_deriv <- attributes(U12345_i(y_i = data_help$Y, c_i = data_help$C, k_i = data_help$K, x_i = data_help$X, l_i = data_help$L, alpha0 = estimates[names(estimates) == "alpha_0"], alpha1 = estimates[names(estimates) == "alpha_1"], alpha2 = estimates[names(estimates) == "alpha_2"], alpha3 = estimates[names(estimates) == "alpha_3"], sigma1 = estimates[names(estimates) == "sigma_1"])) logL2_deriv <- attributes(U678_i(y_i = data_help$Y, c_i = data_help$C, k_i = data_help$K, x_i = data_help$X, l_i = data_help$L, y_adj_bar = estimates[names(estimates) == "y_adj_bar"], k_bar = mean(data_help$K), alpha0 = estimates[names(estimates) == "alpha_0"], alpha1 = estimates[names(estimates) == "alpha_1"], alpha2 = estimates[names(estimates) == "alpha_2"], alpha3 = estimates[names(estimates) == "alpha_3"], sigma1 = estimates[names(estimates) == "sigma_1"], alpha4 = estimates[names(estimates) == "alpha_4"], alphaXY = estimates[names(estimates) == "alpha_XY"], sigma2sq = estimates[names(estimates) == "sigma_2_sq"])) deriv_obj <- list(logL1_deriv = logL1_deriv, logL2_deriv = logL2_deriv) } return(deriv_obj) } ## ---- echo=FALSE--------------------------------------------------------- scores <- function(derivobj = NULL) { if (is.null(derivobj)) { stop("derivobj has to be supplied.") } scores_out <- cbind(derivobj[[1]]$gradient[, 1:5], derivobj[[2]]$gradient[, 6:8]) return(scores_out) } ## ---- echo=FALSE--------------------------------------------------------- hessian <- function(derivobj = NULL) { if (is.null(derivobj)) { stop("derivobj has to be supplied.") } hessian_out <- derivobj[[1]]$hessian hessian_out[, 6:8, ] <- derivobj[[2]]$hessian[, 6:8, ] return(hessian_out) } ## ------------------------------------------------------------------------ derivobj <- deriv_obj(setting = "GLM", logL1 = estfunct$logL1, logL2 = estfunct$logL2, Y = dat$Y, X = dat$X, K = dat$K, L = dat$L, estimates = estimates) names(derivobj) head(derivobj$logL1_deriv$gradient) score_matrix <- scores(derivobj) head(score_matrix) hessian_matrix <- hessian(derivobj) str(hessian_matrix) ## ---- echo=FALSE--------------------------------------------------------- sandwich_se <- function(setting = "GLM", scores = NULL, hessian = NULL) { if (is.null(scores) | is.null(hessian)) { stop("scores and hessian have to be supplied.") } n <- dim(scores)[1] ### A_n matrix ### A_n <- matrix(, nrow = 8, ncol = 8) for (A_n_i in 1:8) { for (A_n_j in 1:8) { A_n[A_n_i, A_n_j] <- sum(hessian[, A_n_i, A_n_j]) } } A_n <- -(1/n) * A_n ### B_n matrix ### B_n <- matrix(, nrow = 8, ncol = 8) for (B_n_i in 1:8) { for (B_n_j in 1:8) { B_n[B_n_i, B_n_j] <- sum(scores[, B_n_i] * scores[, B_n_j]) } } B_n <- (1/n) * B_n ### C_n matrix ### C_n <- solve(A_n) %*% B_n %*% t(solve(A_n)) ### Variance estimates of coefficients ### theta_EE_se <- (1/n) * diag(C_n) theta_EE_se <- sqrt(theta_EE_se) if (setting == "GLM") { names(theta_EE_se) <- c("alpha_0", "alpha_1", "alpha_2", "alpha_3", "sigma_1_sq", "alpha_4", "alpha_XY", "sigma_2_sq") } if (setting == "AFT") { names(theta_EE_se) <- c("alpha_0", "alpha_1", "alpha_2", "alpha_3", "sigma_1", "alpha_4", "alpha_XY", "sigma_2_sq") } return(theta_EE_se) } ## ------------------------------------------------------------------------ sandwich_se(scores = score_matrix, hessian = hessian_matrix) ## ---- echo=FALSE--------------------------------------------------------- bootstrap_se <- function(setting = "GLM", BS_rep = 1000, Y = NULL, X = NULL, K = NULL, L = NULL, C = NULL) { if (is.null(setting)) { stop("setting has to be supplied.") } if (is.null(Y) | is.null(X) | is.null(K) | is.null(L)) { stop("Data of one or more variables are not supplied.") } if (setting == "AFT" & is.null(C)) { stop("C has to be supplied for the AFT setting.") } n <- length(Y) if (setting == "GLM") { alpha_0_SE_BS_help <- alpha_1_SE_BS_help <- alpha_2_SE_BS_help <- alpha_3_SE_BS_help <- sigma_1_sq_SE_BS_help <- alpha_4_SE_BS_help <- alpha_XY_SE_BS_help <- sigma_2_sq_SE_BS_help <- NULL } if (setting == "AFT") { alpha_0_SE_BS_help <- alpha_1_SE_BS_help <- alpha_2_SE_BS_help <- alpha_3_SE_BS_help <- sigma_1_SE_BS_help <- alpha_4_SE_BS_help <- alpha_XY_SE_BS_help <- sigma_2_sq_SE_BS_help <- NULL } for (rep in 1:BS_rep) { id <- sample(1:n, n, replace = TRUE) if (setting == "GLM") { data_id <- data.frame(X = X[id], L = L[id], K = K[id], Y = Y[id]) estimates <- get_estimates(setting = setting, Y = data_id$Y, X = data_id$X, K = data_id$K, L = data_id$L) } if (setting == "AFT") { data_id <- data.frame(X = X[id], L = L[id], K = K[id], Y = Y[id], T = T[id], C = C[id]) estimates <- get_estimates(setting = setting, Y = data_id$Y, X = data_id$X, K = data_id$K, L = data_id$L, C = data_id$C) } alpha_0_SE_BS_help[rep] <- estimates[names(estimates) == "alpha_0"] alpha_1_SE_BS_help[rep] <- estimates[names(estimates) == "alpha_1"] alpha_2_SE_BS_help[rep] <- estimates[names(estimates) == "alpha_2"] alpha_3_SE_BS_help[rep] <- estimates[names(estimates) == "alpha_3"] if (setting == "GLM") { sigma_1_sq_SE_BS_help[rep] <- estimates[names(estimates) == "sigma_1_sq"] } if (setting == "AFT") { sigma_1_SE_BS_help[rep] <- estimates[names(estimates) == "sigma_1"] } alpha_4_SE_BS_help[rep] <- estimates[names(estimates) == "alpha_4"] alpha_XY_SE_BS_help[rep] <- estimates[names(estimates) == "alpha_XY"] sigma_2_sq_SE_BS_help[rep] <- estimates[names(estimates) == "sigma_2_sq"] } if (setting == "GLM") { theta_bootstrap_se <- c(sd(alpha_0_SE_BS_help,na.rm=T), sd(alpha_1_SE_BS_help,na.rm=T), sd(alpha_2_SE_BS_help,na.rm=T), sd(alpha_3_SE_BS_help,na.rm=T), sd(sigma_1_sq_SE_BS_help,na.rm=T), sd(alpha_4_SE_BS_help,na.rm=T), sd(alpha_XY_SE_BS_help,na.rm=T), sd(sigma_2_sq_SE_BS_help,na.rm=T)) names(theta_bootstrap_se) <- c("alpha_0", "alpha_1", "alpha_2", "alpha_3", "sigma_1_sq", "alpha_4", "alpha_XY", "sigma_2_sq") } if (setting == "AFT") { theta_bootstrap_se <- c(sd(alpha_0_SE_BS_help,na.rm=T), sd(alpha_1_SE_BS_help,na.rm=T), sd(alpha_2_SE_BS_help,na.rm=T), sd(alpha_3_SE_BS_help,na.rm=T), sd(sigma_1_SE_BS_help,na.rm=T), sd(alpha_4_SE_BS_help,na.rm=T), sd(alpha_XY_SE_BS_help,na.rm=T), sd(sigma_2_sq_SE_BS_help,na.rm=T)) names(theta_bootstrap_se) <- c("alpha_0", "alpha_1", "alpha_2", "alpha_3", "sigma_1", "alpha_4", "alpha_XY", "sigma_2_sq") } return(theta_bootstrap_se) } ## ---- echo=FALSE--------------------------------------------------------- naive_se <- function(setting = "GLM", Y = NULL, X = NULL, K = NULL, L = NULL, C = NULL) { if (!requireNamespace("survival", quietly = TRUE)) { stop("Pkg needed for this function to work. Please install it.", call. = FALSE) } if (is.null(setting)) { stop("setting has to be supplied.") } if (is.null(Y) | is.null(X) | is.null(K) | is.null(L)) { stop("Data of one or more variables are not supplied.") } if (setting == "AFT" & is.null(C)) { stop("C has to be supplied for the AFT setting.") } n <- length(Y) if (setting == "GLM") { data_help <- data.frame(Y = Y, X = X, K = K, L = L) data_help <- data_help[complete.cases(data_help), ] ######### Stage 1 ######### fit_stage_1 <- lm(data_help$Y ~ data_help$K + data_help$X + data_help$L) alpha_1_out <- summary(fit_stage_1)$coefficients[2, 1] alpha_0_SE_out <- summary(fit_stage_1)$coefficients[1, 2] alpha_1_SE_out <- summary(fit_stage_1)$coefficients[2, 2] alpha_2_SE_out <- summary(fit_stage_1)$coefficients[3, 2] alpha_3_SE_out <- summary(fit_stage_1)$coefficients[4, 2] ######### Stage 2 ######### Y_tilde <- data_help$Y - mean(data_help$Y) - alpha_1_out * (data_help$K - mean(data_help$K)) fit_stage_2 <- lm(Y_tilde ~ data_help$X) alpha_4_SE_out <- summary(fit_stage_2)$coefficients[1, 2] alpha_XY_SE_out <- summary(fit_stage_2)$coefficients[2, 2] } if (setting == "AFT") { data_help <- data.frame(Y = Y, X = X, K = K, L = L, C = C) data_help <- data_help[complete.cases(data_help), ] ######### Stage 1 ######### fit_stage_1 <- survival::survreg(survival::Surv(data_help$Y, data_help$C) ~ data_help$K + data_help$X + data_help$L, dist = "gaussian") alpha_1_out <- summary(fit_stage_1)$table[2, 1] sigma_1_out <- fit_stage_1$scale alpha_0_SE_out <- summary(fit_stage_1)$table[1, 2] alpha_1_SE_out <- summary(fit_stage_1)$table[2, 2] alpha_2_SE_out <- summary(fit_stage_1)$table[3, 2] alpha_3_SE_out <- summary(fit_stage_1)$table[4, 2] ######### Stage 2 ######### mu <- fit_stage_1$linear.predictors Y_adj <- data_help$C * data_help$Y + (1 - data_help$C) * (mu + (sigma_1_out * dnorm((data_help$Y - mu)/sigma_1_out, mean = 0, sd = 1)/ (1 - pnorm((data_help$Y - mu)/sigma_1_out, mean = 0, sd = 1)))) Y_tilde <- Y_adj - mean(Y_adj) - alpha_1_out * (data_help$K - mean(data_help$K)) fit_stage_2 <- lm(Y_tilde ~ data_help$X) alpha_4_SE_out <- summary(fit_stage_2)$coefficients[1, 2] alpha_XY_SE_out <- summary(fit_stage_2)$coefficients[2, 2] } SE_estimates <- c(alpha_0_SE_out, alpha_1_SE_out, alpha_2_SE_out, alpha_3_SE_out, NA, alpha_4_SE_out, alpha_XY_SE_out, NA) names(SE_estimates) <- c("alpha_0", "alpha_1", "alpha_2", "alpha_3", "sigma_1_sq", "alpha_4", "alpha_XY", "sigma_2_sq") return(SE_estimates) } ## ------------------------------------------------------------------------ bootstrap_se(setting = "GLM", BS_rep = 1000, Y = dat$Y, X = dat$X, K = dat$K, L = dat$L) naive_se(setting = "GLM", Y = dat$Y, X = dat$X, K = dat$K, L = dat$L) ## ---- echo=FALSE--------------------------------------------------------- ciee <- function(setting = "GLM", estimates = c("ee", "mult_reg", "res_reg", "sem"), ee_se = c("sandwich"), BS_rep = NULL, Y = NULL, X = NULL, K = NULL, L = NULL, C = NULL) { if (is.null(setting)) { stop("setting has to be supplied.") } if (is.null(estimates)) { stop("At least one method has to be computed.") } if ((("ee" %in% estimates) & is.null(ee_se)) | (("ee" %in% estimates) & length(ee_se) > 1)) { stop("If the estimating equations approach is chosen, one approach has to be chosen for the computation of standard errors.") } if (("bootstrap" %in% estimates) & is.null(BS_rep)) { stop("For the computation of bootstrap standard errors, the number of bootstrap samples has to be chosen.") } if (is.null(Y) | is.null(X) | is.null(K) | is.null(L)) { stop("Data of one or more variables is not supplied.") } if (setting == "AFT" & is.null(C)) { stop("C has to be supplied for the AFT setting.") } if (setting == "AFT" & ("sem" %in% estimates)) { stop("The structural equations modeling approach is only implemented for the GLM setting.") } if (setting == "AFT" & ("res_reg" %in% estimates)) { stop("The regression of residuals approach is only implemented for the GLM setting.") } if (setting == "GLM") { data_help <- data.frame(Y = Y, X = X, K = K, L = L) data_help <- data_help[complete.cases(data_help), ] if ("sem" %in% estimates) { results_sem <- sem_appl(Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L) } if ("mult_reg" %in% estimates) { results_mult_reg <- mult_reg(setting = setting, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L) } if ("res_reg" %in% estimates) { results_res_reg <- res_reg(Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L) } if ("ee" %in% estimates) { point_estimates_ee <- get_estimates(setting = setting, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L) if (ee_se == "sandwich") { # Obtain estimating functions expressions estfunct <- est_funct_expr(setting = "GLM") # Obtain matrices with all first and second derivatives derivobj <- deriv_obj(setting = setting, logL1 = estfunct$logL1, logL2 = estfunct$logL2, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L, estimates = point_estimates_ee) # Obtain score and hessian matrices results_scores <- scores(derivobj) results_hessian <- hessian(derivobj) # Obtain sandwich standard error estimates of the parameters se_estimates_ee <- sandwich_se(setting = setting, scores = results_scores, hessian = results_hessian) } if (ee_se == "bootstrap") { se_estimates_ee <- bootstrap_se(setting = setting, BS_rep = BS_rep, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L) } if (ee_se == "naive") { se_estimates_ee <- naive_se(setting = setting, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L) } wald_test_stat_ee <- point_estimates_ee[1:8]/se_estimates_ee pvalues_ee <- 2 * pnorm(-abs(wald_test_stat_ee)) results_ee <- list(point_estimates = point_estimates_ee[1:8], SE_estimates = se_estimates_ee, wald_test_stat = wald_test_stat_ee, pvalues = pvalues_ee) } } if (setting == "AFT") { data_help <- data.frame(Y = Y, X = X, K = K, L = L, C = C) data_help <- data_help[complete.cases(data_help), ] if ("mult_reg" %in% estimates) { results_mult_reg <- mult_reg(setting = setting, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L, C = data_help$C) } if ("ee" %in% estimates) { point_estimates_ee <- get_estimates(setting = setting, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L, C = data_help$C) if (ee_se == "sandwich") { # Obtain estimating functions expressions estfunct <- est_funct_expr(setting = setting) # Obtain matrices with all first and second derivatives derivobj <- deriv_obj(setting = setting, logL1 = estfunct$logL1, logL2 = estfunct$logL2, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L, C = data_help$C, estimates = point_estimates_ee) # Obtain score and hessian matrices results_scores <- scores(derivobj) results_hessian <- hessian(derivobj) # Obtain sandwich standard error estimates of the parameters se_estimates_ee <- sandwich_se(setting = setting, scores = results_scores, hessian = results_hessian) } if (ee_se == "bootstrap") { se_estimates_ee <- bootstrap_se(setting = setting, BS_rep = BS_rep, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L, C = data_help$C) } if (ee_se == "naive") { se_estimates_ee <- naive_se(setting = setting, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L, C = data_help$C) } wald_test_stat_ee <- point_estimates_ee[1:8]/se_estimates_ee pvalues_ee <- 2 * pnorm(-abs(wald_test_stat_ee)) results_ee <- list(point_estimates = point_estimates_ee[1:8], SE_estimates = se_estimates_ee, wald_test_stat = wald_test_stat_ee, pvalues = pvalues_ee) } } output <- list() if ("ee" %in% estimates) { output$results_ee <- results_ee } if ("mult_reg" %in% estimates) { output$results_mult_reg <- results_mult_reg } if ("res_reg" %in% estimates) { output$results_res_reg <- results_res_reg } if ("sem" %in% estimates) { output$results_sem <- results_sem } class(output) <- "ciee" return(output) } ## ---- echo=FALSE--------------------------------------------------------- ciee_loop <- function(setting = "GLM", estimates = c("ee", "mult_reg", "res_reg", "sem"), ee_se = c("sandwich"), BS_rep = NULL, Y = NULL, X = NULL, K = NULL, L = NULL, C = NULL) { if (is.null(setting)) { stop("setting has to be supplied.") } if (is.null(estimates)) { stop("At least one method has to be computed.") } if ((("ee" %in% estimates) & is.null(ee_se)) | (("ee" %in% estimates) & length(ee_se) > 1)) { stop("If the estimating equations approach is chosen, one approach has to be chosen for the computation of standard errors.") } if (("bootstrap" %in% estimates) & is.null(BS_rep)) { stop("For the computation of bootstrap standard errors, the number of bootstrap samples has to be chosen.") } if (is.null(Y) | is.null(X) | is.null(K) | is.null(L)) { stop("Data of one or more variables is not supplied.") } if (setting == "AFT" & is.null(C)) { stop("C has to be supplied for the AFT setting.") } if (setting == "AFT" & ("sem" %in% estimates)) { stop("The structural equations modeling approach is only implemented for the GLM setting.") } if (setting == "AFT" & ("res_reg" %in% estimates)) { stop("The regression of residuals approach is only implemented for the GLM setting.") } if ("sem" %in% estimates) { results_sem <- list(point_estimates = NULL, SE_estimates = NULL, pvalues = NULL) } if ("mult_reg" %in% estimates) { results_mult_reg <- list(point_estimates = NULL, SE_estimates = NULL, pvalues = NULL) } if ("res_reg" %in% estimates) { results_res_reg <- list(point_estimates = NULL, SE_estimates = NULL, pvalues = NULL) } if ("ee" %in% estimates) { results_ee <- list(point_estimates = NULL, SE_estimates = NULL, wald_test_stat = NULL, pvalues = NULL) } k <- dim(X)[2] for (i in 1:k) { Xi <- X[, i] if (setting == "GLM") { data_help <- data.frame(Y = Y, X = Xi, K = K, L = L) data_help <- data_help[complete.cases(data_help), ] if ("sem" %in% estimates) { sem_help <- sem_appl(Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L) results_sem$point_estimates[i] <- sem_help$point_estimates[5] results_sem$SE_estimates[i] <- sem_help$SE_estimates[5] results_sem$pvalues[i] <- sem_help$pvalues[5] names(results_sem$point_estimates)[i] <- names(results_sem$SE_estimates)[i] <- names(results_sem$pvalues)[i] <- names(X)[i] } if ("mult_reg" %in% estimates) { mult_reg_help <- mult_reg(setting = setting, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L) results_mult_reg$point_estimates[i] <- mult_reg_help$point_estimates[3] results_mult_reg$SE_estimates[i] <- mult_reg_help$SE_estimates[3] results_mult_reg$pvalues[i] <- mult_reg_help$pvalues[3] names(results_mult_reg$point_estimates)[i] <- names(results_mult_reg$SE_estimates)[i] <- names(results_mult_reg$pvalues)[i] <- names(X)[i] } if ("res_reg" %in% estimates) { res_reg_help <- res_reg(Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L) results_res_reg$point_estimates[i] <- res_reg_help$point_estimates[5] results_res_reg$SE_estimates[i] <- res_reg_help$SE_estimates[5] results_res_reg$pvalues[i] <- res_reg_help$pvalues[5] names(results_res_reg$point_estimates)[i] <- names(results_res_reg$SE_estimates)[i] <- names(results_res_reg$pvalues)[i] <- names(X)[i] } if ("ee" %in% estimates) { point_estimates_ee <- get_estimates(setting = setting, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L) if (ee_se == "sandwich") { # Obtain estimating functions expressions estfunct <- est_funct_expr(setting = "GLM") # Obtain matrices with all first and second derivatives derivobj <- deriv_obj(setting = setting, logL1 = estfunct$logL1, logL2 = estfunct$logL2, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L, estimates = point_estimates_ee) # Obtain score and hessian matrices results_scores <- scores(derivobj) results_hessian <- hessian(derivobj) # Obtain sandwich standard error estimates of the parameters se_estimates_ee <- sandwich_se(setting = setting, scores = results_scores, hessian = results_hessian) } if (ee_se == "bootstrap") { se_estimates_ee <- bootstrap_se(setting = setting, BS_rep = BS_rep, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L) } if (ee_se == "naive") { se_estimates_ee <- naive_se(setting = setting, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L) } results_ee$point_estimates[i] <- point_estimates_ee[7] results_ee$SE_estimates[i] <- se_estimates_ee[7] results_ee$wald_test_stat[i] <- point_estimates_ee[7]/ se_estimates_ee[7] results_ee$pvalues[i] <- 2 * pnorm(-abs(point_estimates_ee[7]/ se_estimates_ee[7])) names(results_ee$point_estimates)[i] <- names(results_ee$SE_estimates)[i] <- names(results_ee$wald_test_stat)[i] <- names(results_ee$pvalues)[i] <- names(X)[i] } } if (setting == "AFT") { data_help <- data.frame(Y = Y, X = Xi, K = K, L = L, C = C) data_help <- data_help[complete.cases(data_help), ] if ("mult_reg" %in% estimates) { mult_reg_help <- mult_reg(setting = setting, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L, C = data_help$C) results_mult_reg$point_estimates[i] <- mult_reg_help$point_estimates[3] results_mult_reg$SE_estimates[i] <- mult_reg_help$SE_estimates[3] results_mult_reg$pvalues[i] <- mult_reg_help$pvalues[3] names(results_mult_reg$point_estimates)[i] <- names(results_mult_reg$SE_estimates)[i] <- names(results_mult_reg$pvalues)[i] <- names(X)[i] } if ("ee" %in% estimates) { point_estimates_ee <- get_estimates(setting = setting, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L, C = data_help$C) if (ee_se == "sandwich") { # Obtain estimating functions expressions estfunct <- est_funct_expr(setting = setting) # Obtain matrices with all first and second derivatives derivobj <- deriv_obj(setting = setting, logL1 = estfunct$logL1, logL2 = estfunct$logL2, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L, C = data_help$C, estimates = point_estimates_ee) # Obtain score and hessian matrices results_scores <- scores(derivobj) results_hessian <- hessian(derivobj) # Obtain sandwich standard error estimates of the parameters se_estimates_ee <- sandwich_se(setting = setting, scores = results_scores, hessian = results_hessian) } if (ee_se == "bootstrap") { se_estimates_ee <- bootstrap_se(setting = setting, BS_rep = BS_rep, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L, C = data_help$C) } if (ee_se == "naive") { se_estimates_ee <- naive_se(setting = setting, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L, C = data_help$C) } results_ee$point_estimates[i] <- point_estimates_ee[7] results_ee$SE_estimates[i] <- se_estimates_ee[7] results_ee$wald_test_stat[i] <- point_estimates_ee[7]/ se_estimates_ee[7] results_ee$pvalues[i] <- 2 * pnorm(-abs(point_estimates_ee[7]/ se_estimates_ee[7])) names(results_ee$point_estimates)[i] <- names(results_ee$SE_estimates)[i] <- names(results_ee$wald_test_stat)[i] <- names(results_ee$pvalues)[i] <- names(X)[i] } } } output <- list() if ("ee" %in% estimates) { output$results_ee <- results_ee } if ("mult_reg" %in% estimates) { output$results_mult_reg <- results_mult_reg } if ("res_reg" %in% estimates) { output$results_res_reg <- results_res_reg } if ("sem" %in% estimates) { output$results_sem <- results_sem } class(output) <- "ciee" return(output) } ## ------------------------------------------------------------------------ results_ciee <- ciee(setting = "GLM", Y = dat$Y, X = dat$X, K = dat$K, L = dat$L, estimates = c("ee", "mult_reg", "res_reg", "sem"), ee_se = "sandwich") results_ciee maf <- 0.2 n <- 1000 dat <- generate_data(n = n, maf = maf) datX <- data.frame(X = dat$X) names(datX)[1] <- "X1" for(i in 2:10){ X <- rbinom(n, size = 2, prob = maf) datX$X <- X names(datX)[i] <- paste("X", i, sep="") } results_ciee_loop <- ciee_loop(setting = "GLM", Y = dat$Y, X = datX, K = dat$K, L = dat$L) results_ciee_loop ## ---- echo=FALSE--------------------------------------------------------- summary.ciee <- function(results = NULL) { if (is.null(results)) { stop("ciee output has to be supplied.") } res_out <- NULL if ("results_ee" %in% names(results)) { res_ee_out <- data.frame(point_estimates = results$results_ee$point_estimates, SE_estimates = results$results_ee$SE_estimates, wald_test_stat = results$results_ee$wald_test_stat, pvalues = results$results_ee$pvalues) rownames(res_ee_out) <- paste("CIEE", rownames(res_ee_out), sep = "_") print(paste("Results based on estimating equations.")) print(res_ee_out) res_out <- res_ee_out[,c(1,2,4)] } if ("results_mult_reg" %in% names(results)) { res_mr_out <- data.frame(point_estimates = results$results_mult_reg$point_estimates, SE_estimates = results$results_mult_reg$SE_estimates, pvalues = results$results_mult_reg$pvalues) rownames(res_mr_out) <- paste("MR", rownames(res_mr_out), sep = "_") print(paste("Results based on traditional multiple regression.")) print(res_mr_out) res_out <- rbind(res_out, res_mr_out) } if ("results_res_reg" %in% names(results)) { res_rr_out <- data.frame(point_estimates = results$results_res_reg$point_estimates, SE_estimates = results$results_res_reg$SE_estimates, pvalues = results$results_res_reg$pvalues) rownames(res_rr_out) <- paste("RR", rownames(res_rr_out), sep = "_") print(paste("Results based on traditional regression of residuals.")) print(res_rr_out) res_out <- rbind(res_out, res_rr_out) } if ("results_sem" %in% names(results)) { res_sem_out <- data.frame(point_estimates = results$results_sem$point_estimates, SE_estimates = results$results_sem$SE_estimates, pvalues = results$results_sem$pvalues) rownames(res_sem_out) <- paste("SEM", rownames(res_sem_out), sep = "_") print(paste("Results based on structural equation modeling.")) print(res_sem_out) res_out <- rbind(res_out, res_sem_out) } invisible(res_out) } ## ------------------------------------------------------------------------ summary(results_ciee) summary(results_ciee_loop)
/scratch/gouwar.j/cran-all/cranData/CIEE/inst/doc/ciee.R
--- title: "Estimating and Testing Direct Effects in Directed Acyclic Graphs using Estimating Equations" author: "Stefan Konigorski" date: "March 19, 2018" output: pdf_document vignette: > %\VignetteIndexEntry{Estimating and Testing Direct Effects in Directed Acyclic Graphs using Estimating Equations} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ## Overview In any association study, it is important to distinguish direct and indirect effects in order to build truly functional models. For this purpose, we consider a directed acyclic graph (DAG) setting with an exposure variable, primary and intermediate outcome variables, and confounding factors. In order to make valid statistical inference on the direct effect of the exposure on the primary outcome, it is necessary to consider all potential effects in the graph, and we propose to use the estimating equation method with robust Huber-White sandwich standard errors. Then, a large-sample Wald-type test statistic is computed for testing the absence of the direct effect. In this package, the proposed causal inference method based on estimating equations (CIEE) is implemented for both the analysis of continuous and time-to-event primary outcomes subject to censoring for the model in Figure 1. Additionally, standard multiple regression, regression of residuals, and the structural equation approach are implemented for fitting the same model. Results from simulation studies (Konigorski et al., 2018) showed that CIEE successfully removes the effect of intermediate outcomes from the primary outcome and is robust against measured and unmeasured confounding of the indirect effect through observed factors. Also, an application in a genetic association study in the same study showed that CIEE can identify genetic variants that would be missed by traditional regression methods. Both multiple regression methods and the structural equation method fail in some scenarios where their corresponding test statistics lead to inflated type I errors. An alternative approach for the analysis of continuous traits is the sequential G-estimation method (Vansteelandt et al., 2009). In this package, CIEE is implemented for the model described in the DAG in Figure 1, which includes the direct effect $\alpha_{XY}$ of an exposure X on the primary outcome Y and an indirect effect of X on Y through a secondary outcome K. The model further includes measured and unmeasured factors L and U, respectively, which potentially confound the effect of K on Y. CIEE can also be applied to different models with different error distributions. The goal is to estimate and test the direct effect $\alpha_{XY}$, while removing the indirect effect of X on Y through K, and with robustness against effects of L and U. Without restriction of generality, it is assumed that there aren't any factors affecting X and that any such factors are included as covariates in the analysis or have been dealt with using other approaches. Also, we generally assume that either $\alpha_{LY}=0$ (L is a factor influencing K) or $\alpha_{XL}=0$ (L is a measured confounder of $K \to Y$). Otherwise, the effect of L as intermediate outcome could be removed from Y in the analysis analogously to K. ![Overview of the underlying directed acyclic graph considered in this study. It is assumed that $\alpha_{LY}=0$ so that L is a measured predictive factor of K, however, CIEE is also valid if L is a measured confounder of $K \to Y$ (i.e., $\alpha_{LY} \neq 0$ and $\alpha_{XL}=0$). ](Figure1.pdf) ## Alternative approaches Two traditional methods for the aim to estimate and test $\alpha_{XY}$ are (i) to include the intermediate outcomes and factors as covariates in a multiple regression (MR) model of the primary outcome on the exposure, or (ii) to first regress the primary outcome on the intermediate outcome and factors, and then regress the extracted residuals on the exposure (regression of residuals, RR). In more detail, estimates of $\alpha_{XY}$ are obtained from fitting the following models in the quantitative outcome setting for a normally-distributed Y (GLM setting): MR: Obtain the least squares (LS) estimate of $\alpha_{XY}$ by fitting $$Y_i = \alpha_0 + \alpha_{XY} x_i + \alpha_1 k_i + \alpha_2 l_i + \varepsilon_i, \ \varepsilon_i \sim N(0,\sigma_1^2)$$. RR: First, obtain residuals $\hat{\epsilon}_{1i} = y_i - \hat{\alpha}_0 - \hat{\alpha}_1 k_i - \hat{\alpha}_2 l_i$ by fitting $$Y_i = \alpha_0 + \alpha_1 k_i + \alpha_2 l_i + \varepsilon_{1i}, \ \varepsilon_{1i} \sim N(0,\sigma_1^2 )$$ using the LS estimation. Second, obtain the LS estimate of $\alpha_{XY}$ by fitting $$\hat{\varepsilon}_{1i} = \alpha_3 + \alpha_{XY} x_i + \varepsilon_{2i}, \ \varepsilon_{2i} \sim N(0, \sigma_2^2).$$ Then, $H_0: \alpha_{XY} = 0$ versus $H_A: \alpha_{XY} \neq 0$ is tested using the default t-test in the `lm()` function in R. For the analysis of a censored time-to-event primary trait Y (accelerated failure time setting; AFT), only the MR approach is implemented. Here, the equivalent censored log-linear regression model is fitted using the `survreg()` function in the `survival` R package to obtain the maximum likelihood estimate of $\alpha_{XY}$, and a Wald-type test is performed for testing the null hypothesis $H_0: \alpha_{XY} = 0$. Both approaches are implemented in the functions `mult_reg()` and `res_reg()` and can be used as follows. For this illustration, data is first generated using the `generate_data()` function, which generates data for the quantitative outcomes Y and K, a genetic marker X (single nucleotide polymorphism, SNP, taking values 0, 1, 2) as exposure, and observed as well as unobserved confounders L, U. ```{r, echo=FALSE} generate_data <- function(setting = "GLM", n = 1000, maf = 0.2, cens = 0.3, a = NULL, b = NULL, aXK = 0.2, aXY = 0.1, aXL = 0, aKY = 0.3, aLK = 0, aLY = 0, aUY = 0, aUL = 0, mu_X = NULL, sd_X = NULL, X_orth_U = TRUE, mu_U = 0, sd_U = 1, mu_K = 0, sd_K = 1, mu_L = 0, sd_L = 1, mu_Y = 0, sd_Y = 1) { U_out <- rnorm(n, mean = mu_U, sd = sd_U) if (setting == "AFT" & (is.null(a) | is.null(b))) { stop("a and b have to be specified under the AFT setting.") } if (X_orth_U == TRUE) { X_out <- rbinom(n, size = 2, prob = maf) } if (X_orth_U == FALSE) { X_out <- pnorm(U_out, mean = mu_X, sd = sd_X) p <- 1 - maf for (j in 1:length(X_out)) { if (X_out[j] < p^2) { X_out[j] <- 0 next } if (X_out[j] >= p^2 & X_out[j] < p^2 + 2 * p * (1 - p)) { X_out[j] <- 1 next } if (X_out[j] >= p^2 + 2 * p * (1 - p)) { X_out[j] <- 2 next } } } L_out <- aUL * U_out + aXL * X_out + rnorm(n, mean = mu_L, sd = sd_L) K_out <- aXK * X_out + aLK * L_out + rnorm(n, mean = mu_K, sd = sd_K) Y_out <- aUY * U_out + aKY * K_out + aXY * X_out + aLY * L_out + rnorm(n, mean = mu_Y, sd = sd_Y) data <- data.frame(Y = Y_out, K = K_out, X = X_out, L = L_out, U = U_out) if (setting == "AFT") { T_help <- exp(Y_out) ### Create censoring indicator and censored times no censoring if (cens == 0) { T_out <- T_help C_out <- rep(1, n) # C_out==0 is censored, C_out==1 is uncensored } if (!cens == 0) { # there is censoring; cens is the percentage of censored data T_cens <- runif(n, min = a, max = b) # a, b for desired censoring rate C_out <- as.numeric(T_help < T_cens) # C==0 censored, C==1 uncensored T_out <- pmin(T_help, T_cens) Y_out <- log(T_out) } cens_out <- sum(abs(C_out - 1))/n data <- data.frame(Y = Y_out, K = K_out, X = X_out, L = L_out, U = U_out, T = T_out, C = C_out) print(paste("The empirical censoring rate obtained through the specified parameters a=", a, " and b=", b, " is ", cens_out, ".", sep = "")) if (abs(cens_out - cens) > 0.1) { warning(paste("This obtained empirical censoring rate is quite different from the desired censoring rate cens=", cens, ". Please check and adapt values for a and b.", sep = "")) } } return(data) } ``` ```{r, echo=FALSE} mult_reg <- function(setting = "GLM", Y = NULL, X = NULL, K = NULL, L = NULL, C = NULL) { if (!requireNamespace("survival", quietly = TRUE)) { stop("Pkg needed for this function to work. Please install it.", call. = FALSE) } if (is.null(setting)) { stop("setting has to be supplied.") } if (is.null(Y) | is.null(X) | is.null(K) | is.null(L)) { stop("Data of one or more variables are not supplied.") } if (setting == "AFT" & is.null(C)) { stop("C has to be supplied for the AFT setting.") } if (setting == "GLM") { fit_mult_reg <- lm(Y ~ K + X + L) point_estimates <- c(summary(fit_mult_reg)$coefficients[1, 1], summary(fit_mult_reg)$coefficients[2, 1], summary(fit_mult_reg)$coefficients[3, 1], summary(fit_mult_reg)$coefficients[4, 1]) SE_estimates <- c(summary(fit_mult_reg)$coefficients[1, 2], summary(fit_mult_reg)$coefficients[2, 2], summary(fit_mult_reg)$coefficients[3, 2], summary(fit_mult_reg)$coefficients[4, 2]) pvalues <- c(summary(fit_mult_reg)$coefficients[1, 4], summary(fit_mult_reg)$coefficients[2, 4], summary(fit_mult_reg)$coefficients[3, 4], summary(fit_mult_reg)$coefficients[4, 4]) names(point_estimates) <- names(SE_estimates) <- names(pvalues) <- c("alpha_0", "alpha_1", "alpha_XY", "alpha_2") } if (setting == "AFT") { fit_mult_reg <- survival::survreg(survival::Surv(Y, C) ~ K + X + L, dist = "gaussian") point_estimates <- c(summary(fit_mult_reg)$table[1, 1], summary(fit_mult_reg)$table[2, 1], summary(fit_mult_reg)$table[3, 1], summary(fit_mult_reg)$table[4, 1]) SE_estimates <- c(summary(fit_mult_reg)$table[1, 2], summary(fit_mult_reg)$table[2, 2], summary(fit_mult_reg)$table[3, 2], summary(fit_mult_reg)$table[4, 2]) pvalues <- c(summary(fit_mult_reg)$table[1, 4], summary(fit_mult_reg)$table[2, 4], summary(fit_mult_reg)$table[3, 4], summary(fit_mult_reg)$table[4, 4]) names(point_estimates) <- names(SE_estimates) <- names(pvalues) <- c("alpha_0", "alpha_1", "alpha_XY", "alpha_2") } return(list(point_estimates = point_estimates, SE_estimates = SE_estimates, pvalues = pvalues)) } ``` ```{r, echo=FALSE} res_reg <- function(Y = NULL, X = NULL, K = NULL, L = NULL) { if (is.null(Y) | is.null(X) | is.null(K) | is.null(L)) { stop("Data of one or more variables is not supplied.") } data_help <- data.frame(Y = Y, X = X, K = K, L = L) data_help <- data_help[complete.cases(data_help), ] fit_res_reg_1 <- lm(data_help$Y ~ data_help$K + data_help$L) res <- fit_res_reg_1$residuals fit_res_reg_2 <- lm(res ~ data_help$X) point_estimates <- c(summary(fit_res_reg_1)$coefficients[1, 1], summary(fit_res_reg_1)$coefficients[2, 1], summary(fit_res_reg_1)$coefficients[3, 1], summary(fit_res_reg_2)$coefficients[1, 1], summary(fit_res_reg_2)$coefficients[2, 1]) SE_estimates <- c(summary(fit_res_reg_1)$coefficients[1, 2], summary(fit_res_reg_1)$coefficients[2, 2], summary(fit_res_reg_1)$coefficients[3, 2], summary(fit_res_reg_2)$coefficients[1, 2], summary(fit_res_reg_2)$coefficients[2, 2]) pvalues <- c(summary(fit_res_reg_1)$coefficients[1, 4], summary(fit_res_reg_1)$coefficients[2, 4], summary(fit_res_reg_1)$coefficients[3, 4], summary(fit_res_reg_2)$coefficients[1, 4], summary(fit_res_reg_2)$coefficients[2, 4]) names(point_estimates) <- names(SE_estimates) <- names(pvalues) <- c("alpha_0", "alpha_1", "alpha_2", "alpha_3", "alpha_XY") return(list(point_estimates = point_estimates, SE_estimates = SE_estimates, pvalues = pvalues)) } ``` ```{r} dat <- generate_data(setting="GLM", n = 1000, maf = 0.2, cens = 0.3, a = NULL, b = NULL, aUL = 0, aXL = 0, aXK = 0.2, aLK = 0, aUY = 0, aKY = 0.3, aXY = 0.1, aLY = 0, mu_U = 0, sd_U = 1, X_orth_U = TRUE, mu_X = NULL, sd_X = NULL, mu_L = 0, sd_L = 1, mu_K = 0, sd_K = 1, mu_Y = 0, sd_Y = 1) head(dat) mult_reg(setting = "GLM", Y = dat$Y, X = dat$X, K = dat$K, L = dat$L) res_reg(Y = dat$Y, X = dat$X, K = dat$K, L = dat$L) ``` As another approach for modeling DAGs, the structural equation modeling method (SEM; Bollen, 1989) can be used. Among others, it is implemented in the `sem()` function of the `lavaan` package (Rosseel, 2012). For a comparison of the results, the function `sem_appl()` applies the SEM method to the DAG in Figure 1 based on the following model equations: $$L_i = \alpha_0 + \alpha_1 x_i + \varepsilon_{1i}, \ \varepsilon_{1i} \sim N(0,\sigma_1^2 ) $$ $$K_i = \alpha_2 + \alpha_3 x_i + \alpha_2 l_i + \varepsilon_{2i}, \ \varepsilon_{2i} \sim N(0,\sigma_2^2 ) $$ $$Y_i = \alpha_5 + \alpha_6 k_i + \alpha_{XY} x_i + \varepsilon_{3i}, \ \varepsilon_{3i} \sim N(0,\sigma_3^2 ) $$ ```{r, echo=FALSE} sem_appl <- function(setting = "GLM", Y = NULL, X = NULL, K = NULL, L = NULL) { if (!requireNamespace("lavaan", quietly = TRUE)) { stop("Pkg needed for this function to work. Please install it.", call. = FALSE) } if (is.null(setting)) { stop("setting has to be supplied.") } if (setting == "AFT") { stop("Only GLM setting is implemented.") } if (is.null(Y) | is.null(X) | is.null(K) | is.null(L)) { stop("Data of one or more variables are not supplied.") } data_help <- data.frame(Y = Y, X = X, K = K, L = L) data_help <- data_help[complete.cases(data_help), ] model <- " L ~ X K ~ X + L Y ~ K + X " fit <- lavaan::sem(model, data = data_help) point_estimates <- c(fit@Fit@est[1], fit@Fit@est[2], fit@Fit@est[3], fit@Fit@est[4], fit@Fit@est[5]) SE_estimates <- c(fit@Fit@se[1], fit@Fit@se[2], fit@Fit@se[3], fit@Fit@se[4], fit@Fit@se[5]) pvalues <- 2 * pnorm(-abs(point_estimates/SE_estimates)) names(point_estimates) <- names(SE_estimates) <- names(pvalues) <- c("alpha_1", "alpha_3", "alpha_4", "alpha_6", "alpha_XY") return(list(point_estimates = point_estimates, SE_estimates = SE_estimates, pvalues = pvalues)) } ``` ```{r} sem_appl(Y = dat$Y, X = dat$X, K = dat$K, L = dat$L) ``` Further proposed approaches for fitting the model in Figure 1 include the two-stage sequential G-estimation method (Vansteelandt et al., 2009). It first removes the effect of K from the primary outcome Y, and then tests the association of X with the adjusted primary outcome. In more detail, for the analyis of a quantitative outcome Y with n independent observations, in the first stage, the effect of K on Y, $\alpha_1$, is estimated and $\hat{\alpha}_1$ is obtained using the LS estimation method under the model \begin{equation} Y_i = \alpha_0 + \alpha_1 k_i + \alpha_2 x_i + \alpha_3 l_i + \varepsilon_i, \ \varepsilon_i \sim N(0,\sigma_1^2), \quad i=1,…,n \end{equation} Then, to block all indirect paths from X to Y, the adjusted outcome $\tilde{Y}$ is obtained by removing the effect of K on Y with \begin{equation} \tilde{y}_i = y_i - \bar{y} - \hat{\alpha}_1 (k_i - \bar{k}) \end{equation} where $\bar{y} = \sum_{i=1}^n y_i$ and $\bar{k} = \sum_{i=1}^n k_i$. In the second stage, the significance of the direct effect of X on Y, $\alpha_{XY}$, is tested under the model \begin{equation} \tilde{Y}_i = \alpha_4 + \alpha_{XY} x_i + \varepsilon_i, \ \varepsilon_i \sim N(0,\sigma_2^2 ) \end{equation} using the proposed test statistic in Vansteelandt and colleagues (2009). The approach is implemented in the `CGene` package, which can be obtained from [cran.r-project.org/src/contrib/Archive/CGene/](https://cran.r-project.org/src/contrib/Archive/CGene/). ## Causal inference using estimating equations (CIEE) CIEE follows the general idea of the two-stage sequential G-estimation method with the major difference that the approach is one-stage and obtains coefficient estimates of all parameters simultaneously by solving estimating equations. This also allows building on existing asymptotic properties of the estimator and obtaining robust sandwich standard error estimates considering the additional variability of the estimates from the outcome adjustment. In more detail, for the analyis of a quantitative outcome Y, we formulate unbiased estimating equations $U(\theta)=0$ for a consistent estimation of the unknown parameter vector $\theta = (\alpha_0, \alpha_1, \alpha_2, \alpha_3, \sigma_1^2, \alpha_4, \alpha_{XY}, \sigma_2^2)^T$ where $$ U(\theta) = \left( \frac{\partial l_1(\theta)}{\partial \alpha_0}, \frac{\partial l_1(\theta)}{\partial \alpha_1}, \frac{\partial l_1(\theta)}{\partial \alpha_2}, \frac{\partial l_1(\theta)}{\partial \alpha_3}, \frac{\partial l_1(\theta)}{\partial \sigma_1^2}, \frac{\partial l_1(\theta)}{\partial \alpha_4}, \frac{\partial l_1(\theta)}{\partial \alpha_{XY}}, \frac{\partial l_1(\theta)}{\partial \sigma_2^2} \right)^T $$ with $$ l_1(\theta) = \sum_{i=1}^n \left[ -log(\sigma_1) + log\left( \phi\left( \frac{y_i - \alpha_0 - \alpha_1 k_i - \alpha_2 x_i - \alpha_3 l_i}{\sigma_1} \right) \right) \right]$$ and $$ l_2(\theta) = \sum_{i=1}^n \left[ -log(\sigma_2) + log\left( \phi\left( \frac{y_i - \bar{y} - \alpha_1 (k_i - \bar{k}) - \alpha_4 - \alpha_{XY} x_i}{\sigma_2} \right) \right) \right],$$ where $\phi$ is the probability density function of the standard normal distribution. By solving the first five estimating equations based on $l_1(\theta)$, we are hence obtaining estimates of $\alpha_0, \alpha_1, \alpha_2, \alpha_3, \sigma_1^2$. Analogously, solving the last three estimating equations based on $l_2(\theta)$ yields estimates of $\alpha_4, \alpha_{XY}, \sigma_2^2$. To give an intuition on how these estimating equations are obtained, $l_1(\theta)$ is the log-likelihood function under the model in (1) and $l_2(\theta)$ is the log-likelihood function under the model in (3) given that $\alpha_1$ is known. All parameters in $\theta$ are estimated simultaneously and the additional variability obtained in the outcome adjustment in (2) is considered by using the robust Huber-White sandwich estimator of the standard error of $\hat{\theta}$. Then, the large sample Wald-type test statistic $\hat{\theta}/\widehat{SE}(\hat{\theta})$, which has an asymptotic standard normal distribution, is computed to test the absence of the exposure effect $\alpha_{XY}$. For the analysis of a censored time-to-event primary outcome Y, the estimating equations can be constructed as described above for a quantitative primary phenotype (for the same parameters except for $\sigma_1$ instead of $\sigma_1^2$), but in order to remove the effect of K from Y, the true underlying log survival times $Y_{est}$ need to be estimated for censored survival times. For uncensored survival times, $Y_{est}$ equals the observed log-survival time Y. Then, the estimating equations are constructed accordingly, the robust Huber-White sandwich estimator of the standard error is obtained and the large-sample Wald-type tests are computed. For more statistical details, see Konigorski et al. (2018). In the implementation of CIEE in this package, the `est_funct_expr()` function contains the estimating equations as an expression. ```{r, echo=FALSE} est_funct_expr <- function(setting = "GLM") { if (is.null(setting)) { stop("setting has to be supplied.") } if (setting == "GLM") { logL1 <- expression(log((1/sqrt(sigma1sq)) * dnorm((y_i - alpha0 - alpha1 * k_i - alpha2 * x_i - alpha3 * l_i)/ sqrt(sigma1sq), mean = 0, sd = 1))) logL2 <- expression(log((1/sqrt(sigma2sq)) * dnorm((y_i - y_bar - alpha1 * (k_i - k_bar) - alpha4 - alphaXY * x_i)/ sqrt(sigma2sq), mean = 0, sd = 1))) } if (setting == "AFT") { logL1 <- expression(-c_i * log(sigma1) + c_i * log(dnorm((y_i - alpha0 - alpha1 * k_i - alpha2 * x_i - alpha3 * l_i)/sigma1, mean = 0, sd = 1)) + (1 - c_i) * log(1 - pnorm((y_i - alpha0 - alpha1 * k_i - alpha2 * x_i - alpha3 * l_i)/ sigma1, mean = 0, sd = 1))) logL2 <- expression(log((1/sqrt(sigma2sq)) * dnorm(((c_i * y_i + (1 - c_i) * ((alpha0 + alpha1 * k_i + alpha2 * x_i + alpha3 * l_i) + (sigma1 * dnorm((y_i - alpha0 - alpha1 * k_i - alpha2 * x_i - alpha3 * l_i)/sigma1, mean = 0, sd = 1)/(1 - pnorm((y_i - alpha0 - alpha1 * k_i - alpha2 * x_i - alpha3 * l_i)/sigma1, mean = 0, sd = 1))))) - y_adj_bar - alpha1 * (k_i - k_bar) - alpha4 - alphaXY * x_i)/sqrt(sigma2sq), mean = 0, sd = 1))) } return(list(logL1 = logL1, logL2 = logL2)) } ``` ```{r} estfunct <- est_funct_expr(setting="GLM") estfunct est_funct_expr(setting = "AFT") ``` The function `get_estimates()` obtains estimates of the parameters in the models (1)-(3) by using the `lm()` and `survreg()` functions for computational purposes. The estimates are identical to estimates obtained by solving the estimating equations. ```{r, echo=FALSE} get_estimates <- function(setting = "GLM", Y = NULL, X = NULL, K = NULL, L = NULL, C = NULL) { if (!requireNamespace("survival", quietly = TRUE)) { stop("Pkg needed for this function to work. Please install it.", call. = FALSE) } if (is.null(setting)) { stop("setting has to be supplied.") } if (is.null(Y) | is.null(X) | is.null(K) | is.null(L)) { stop("Data of one or more variables are not supplied.") } if (setting == "AFT" & is.null(C)) { stop("C has to be supplied for the AFT setting.") } n <- length(Y) if (setting == "GLM") { data_help <- data.frame(Y = Y, X = X, K = K, L = L) data_help <- data_help[complete.cases(data_help), ] ######### Stage 1 ######### fit_stage_1 <- lm(data_help$Y ~ data_help$K + data_help$X + data_help$L) alpha_0_out <- summary(fit_stage_1)$coefficients[1, 1] alpha_1_out <- summary(fit_stage_1)$coefficients[2, 1] alpha_2_out <- summary(fit_stage_1)$coefficients[3, 1] alpha_3_out <- summary(fit_stage_1)$coefficients[4, 1] sigma_1_sq_out <- (n - 4)/n * summary(fit_stage_1)$sigma^2 ######### Stage 2 ######### Y_tilde <- data_help$Y - mean(data_help$Y) - alpha_1_out * (data_help$K - mean(data_help$K)) fit_stage_2 <- lm(Y_tilde ~ data_help$X) alpha_4_out <- summary(fit_stage_2)$coefficients[1, 1] alpha_XY_out <- summary(fit_stage_2)$coefficients[2, 1] sigma_2_sq_out <- (n - 2)/n * summary(fit_stage_2)$sigma^2 point_estimates <- c(alpha_0_out, alpha_1_out, alpha_2_out, alpha_3_out, sigma_1_sq_out, alpha_4_out, alpha_XY_out, sigma_2_sq_out) names(point_estimates) <- c("alpha_0", "alpha_1", "alpha_2", "alpha_3", "sigma_1_sq", "alpha_4", "alpha_XY", "sigma_2_sq") } if (setting == "AFT") { data_help <- data.frame(Y = Y, X = X, K = K, L = L, C = C) data_help <- data_help[complete.cases(data_help), ] ######### Stage 1 ######### fit_stage_1 <- survival::survreg(survival::Surv(data_help$Y, data_help$C) ~ data_help$K + data_help$X + data_help$L, dist = "gaussian") alpha_0_out <- summary(fit_stage_1)$table[1, 1] alpha_1_out <- summary(fit_stage_1)$table[2, 1] alpha_2_out <- summary(fit_stage_1)$table[3, 1] alpha_3_out <- summary(fit_stage_1)$table[4, 1] sigma_1_out <- fit_stage_1$scale ######### Stage 2 ######### mu <- fit_stage_1$linear.predictors Y_adj <- data_help$C * data_help$Y + (1 - data_help$C) * (mu + (sigma_1_out * dnorm((data_help$Y - mu)/sigma_1_out, mean = 0, sd = 1)/(1 - pnorm((data_help$Y - mu)/sigma_1_out, mean = 0, sd = 1)))) Y_tilde <- Y_adj - mean(Y_adj) - alpha_1_out * (data_help$K - mean(data_help$K)) fit_stage_2 <- lm(Y_tilde ~ data_help$X) alpha_4_out <- summary(fit_stage_2)$coefficients[1, 1] alpha_XY_out <- summary(fit_stage_2)$coefficients[2, 1] sigma_2_sq_out <- (n - 2)/n * summary(fit_stage_2)$sigma^2 point_estimates <- c(alpha_0_out, alpha_1_out, alpha_2_out, alpha_3_out, sigma_1_out, alpha_4_out, alpha_XY_out, sigma_2_sq_out, mean(Y_adj)) names(point_estimates) <- c("alpha_0", "alpha_1", "alpha_2", "alpha_3", "sigma_1", "alpha_4", "alpha_XY", "sigma_2_sq", "y_adj_bar") } return(point_estimates) } ``` ```{r} estimates <- get_estimates(setting = "GLM", Y = dat$Y, X = dat$X, K = dat$K, L = dat$L) estimates ``` In order to compute the robust Huber-White sandwich estimator of the parameters, in a first step, the `deriv_obj()` function computes the expression of all first and second derivatives for the 8 parameters $\alpha_0, \alpha_1, \alpha_2, \alpha_3, \sigma_1^2, \alpha_4, \alpha_{XY}, \sigma_2^2$ by using the expressions from the `est_funct_expr()` function as input. Then, the numerical values of all first and second derivatives are obtained for the observed data and parameter point estimates for all observed individuals, using the `scores()` and `hessian()` functions. ```{r, echo=FALSE} deriv_obj <- function(setting = "GLM", logL1 = NULL, logL2 = NULL, Y = NULL, X = NULL, K = NULL, L = NULL, C = NULL, estimates = NULL) { if (is.null(setting) | is.null(logL1) | is.null(logL2) | is.null(estimates)) { stop("One or more arguments of the function are missing.") } if (is.null(Y) | is.null(X) | is.null(K) | is.null(L)) { stop("Data of one or more variables are not supplied.") } if (setting == "AFT" & is.null(C)) { stop("C has to be supplied for the AFT setting.") } n <- length(Y) if (setting == "GLM") { data_help <- data.frame(Y = Y, X = X, K = K, L = L) data_help <- data_help[complete.cases(data_help), ] U12345_i <- deriv(expr = logL1, namevec = c("alpha0", "alpha1", "alpha2", "alpha3", "sigma1sq", "alpha4", "alphaXY", "sigma2sq"), function.arg = c("y_i", "k_i", "x_i", "l_i", "alpha0", "alpha1", "alpha2", "alpha3", "sigma1sq"), func = T, hessian = T) U678_i <- deriv(expr = logL2, namevec = c("alpha0", "alpha1", "alpha2", "alpha3", "sigma1sq", "alpha4", "alphaXY", "sigma2sq"), function.arg = c("y_i", "k_i", "x_i", "y_bar", "k_bar", "alpha1", "alpha4", "alphaXY", "sigma2sq"), func = T, hessian = T) logL1_deriv <- attributes(U12345_i(y_i = data_help$Y, k_i = data_help$K, x_i = data_help$X, l_i = data_help$L, alpha0 = estimates[names(estimates) == "alpha_0"], alpha1 = estimates[names(estimates) == "alpha_1"], alpha2 = estimates[names(estimates) == "alpha_2"], alpha3 = estimates[names(estimates) == "alpha_3"], sigma1sq = estimates[names(estimates) == "sigma_1_sq"])) logL2_deriv <- attributes(U678_i(y_i = data_help$Y, k_i = data_help$K, x_i = data_help$X, y_bar = mean(data_help$Y), k_bar = mean(data_help$K), alpha1 = estimates[names(estimates) == "alpha_1"], alpha4 = estimates[names(estimates) == "alpha_4"], alphaXY = estimates[names(estimates) == "alpha_XY"], sigma2sq = estimates[names(estimates) == "sigma_2_sq"])) deriv_obj <- list(logL1_deriv = logL1_deriv, logL2_deriv = logL2_deriv) } if (setting == "AFT") { data_help <- data.frame(Y = Y, X = X, K = K, L = L, C = C) data_help <- data_help[complete.cases(data_help), ] U12345_i <- deriv(expr = logL1, namevec = c("alpha0", "alpha1", "alpha2", "alpha3", "sigma1", "alpha4", "alphaXY", "sigma2sq"), function.arg = c("y_i", "c_i", "k_i", "x_i", "l_i", "alpha0", "alpha1", "alpha2", "alpha3", "sigma1"), func = T, hessian = T) U678_i <- deriv(expr = logL2, namevec = c("alpha0", "alpha1", "alpha2", "alpha3", "sigma1", "alpha4", "alphaXY", "sigma2sq"), function.arg = c("y_i", "c_i", "k_i", "x_i", "l_i", "y_adj_bar", "k_bar", "alpha0", "alpha1", "alpha2", "alpha3", "sigma1", "alpha4", "alphaXY", "sigma2sq"), func = T, hessian = T) logL1_deriv <- attributes(U12345_i(y_i = data_help$Y, c_i = data_help$C, k_i = data_help$K, x_i = data_help$X, l_i = data_help$L, alpha0 = estimates[names(estimates) == "alpha_0"], alpha1 = estimates[names(estimates) == "alpha_1"], alpha2 = estimates[names(estimates) == "alpha_2"], alpha3 = estimates[names(estimates) == "alpha_3"], sigma1 = estimates[names(estimates) == "sigma_1"])) logL2_deriv <- attributes(U678_i(y_i = data_help$Y, c_i = data_help$C, k_i = data_help$K, x_i = data_help$X, l_i = data_help$L, y_adj_bar = estimates[names(estimates) == "y_adj_bar"], k_bar = mean(data_help$K), alpha0 = estimates[names(estimates) == "alpha_0"], alpha1 = estimates[names(estimates) == "alpha_1"], alpha2 = estimates[names(estimates) == "alpha_2"], alpha3 = estimates[names(estimates) == "alpha_3"], sigma1 = estimates[names(estimates) == "sigma_1"], alpha4 = estimates[names(estimates) == "alpha_4"], alphaXY = estimates[names(estimates) == "alpha_XY"], sigma2sq = estimates[names(estimates) == "sigma_2_sq"])) deriv_obj <- list(logL1_deriv = logL1_deriv, logL2_deriv = logL2_deriv) } return(deriv_obj) } ``` ```{r, echo=FALSE} scores <- function(derivobj = NULL) { if (is.null(derivobj)) { stop("derivobj has to be supplied.") } scores_out <- cbind(derivobj[[1]]$gradient[, 1:5], derivobj[[2]]$gradient[, 6:8]) return(scores_out) } ``` ```{r, echo=FALSE} hessian <- function(derivobj = NULL) { if (is.null(derivobj)) { stop("derivobj has to be supplied.") } hessian_out <- derivobj[[1]]$hessian hessian_out[, 6:8, ] <- derivobj[[2]]$hessian[, 6:8, ] return(hessian_out) } ``` ```{r} derivobj <- deriv_obj(setting = "GLM", logL1 = estfunct$logL1, logL2 = estfunct$logL2, Y = dat$Y, X = dat$X, K = dat$K, L = dat$L, estimates = estimates) names(derivobj) head(derivobj$logL1_deriv$gradient) score_matrix <- scores(derivobj) head(score_matrix) hessian_matrix <- hessian(derivobj) str(hessian_matrix) ``` The robust Huber-White sandwich estimator of the standard error can then be obtained using the `sandwich_se()` function: ```{r, echo=FALSE} sandwich_se <- function(setting = "GLM", scores = NULL, hessian = NULL) { if (is.null(scores) | is.null(hessian)) { stop("scores and hessian have to be supplied.") } n <- dim(scores)[1] ### A_n matrix ### A_n <- matrix(, nrow = 8, ncol = 8) for (A_n_i in 1:8) { for (A_n_j in 1:8) { A_n[A_n_i, A_n_j] <- sum(hessian[, A_n_i, A_n_j]) } } A_n <- -(1/n) * A_n ### B_n matrix ### B_n <- matrix(, nrow = 8, ncol = 8) for (B_n_i in 1:8) { for (B_n_j in 1:8) { B_n[B_n_i, B_n_j] <- sum(scores[, B_n_i] * scores[, B_n_j]) } } B_n <- (1/n) * B_n ### C_n matrix ### C_n <- solve(A_n) %*% B_n %*% t(solve(A_n)) ### Variance estimates of coefficients ### theta_EE_se <- (1/n) * diag(C_n) theta_EE_se <- sqrt(theta_EE_se) if (setting == "GLM") { names(theta_EE_se) <- c("alpha_0", "alpha_1", "alpha_2", "alpha_3", "sigma_1_sq", "alpha_4", "alpha_XY", "sigma_2_sq") } if (setting == "AFT") { names(theta_EE_se) <- c("alpha_0", "alpha_1", "alpha_2", "alpha_3", "sigma_1", "alpha_4", "alpha_XY", "sigma_2_sq") } return(theta_EE_se) } ``` ```{r} sandwich_se(scores = score_matrix, hessian = hessian_matrix) ``` Alternatively, bootstrap standard error estimates can be computed using the `bootstrap_se()` function. Also, for comparison, the function `naive_se()` computes naive standard error estimates of the parameter estimates of $\alpha_0, \alpha_1, \alpha_2, \alpha_3, \alpha_4, \alpha_{XY}$ without accounting for the additional variability due to the two stages in the model in (1)-(3): ```{r, echo=FALSE} bootstrap_se <- function(setting = "GLM", BS_rep = 1000, Y = NULL, X = NULL, K = NULL, L = NULL, C = NULL) { if (is.null(setting)) { stop("setting has to be supplied.") } if (is.null(Y) | is.null(X) | is.null(K) | is.null(L)) { stop("Data of one or more variables are not supplied.") } if (setting == "AFT" & is.null(C)) { stop("C has to be supplied for the AFT setting.") } n <- length(Y) if (setting == "GLM") { alpha_0_SE_BS_help <- alpha_1_SE_BS_help <- alpha_2_SE_BS_help <- alpha_3_SE_BS_help <- sigma_1_sq_SE_BS_help <- alpha_4_SE_BS_help <- alpha_XY_SE_BS_help <- sigma_2_sq_SE_BS_help <- NULL } if (setting == "AFT") { alpha_0_SE_BS_help <- alpha_1_SE_BS_help <- alpha_2_SE_BS_help <- alpha_3_SE_BS_help <- sigma_1_SE_BS_help <- alpha_4_SE_BS_help <- alpha_XY_SE_BS_help <- sigma_2_sq_SE_BS_help <- NULL } for (rep in 1:BS_rep) { id <- sample(1:n, n, replace = TRUE) if (setting == "GLM") { data_id <- data.frame(X = X[id], L = L[id], K = K[id], Y = Y[id]) estimates <- get_estimates(setting = setting, Y = data_id$Y, X = data_id$X, K = data_id$K, L = data_id$L) } if (setting == "AFT") { data_id <- data.frame(X = X[id], L = L[id], K = K[id], Y = Y[id], T = T[id], C = C[id]) estimates <- get_estimates(setting = setting, Y = data_id$Y, X = data_id$X, K = data_id$K, L = data_id$L, C = data_id$C) } alpha_0_SE_BS_help[rep] <- estimates[names(estimates) == "alpha_0"] alpha_1_SE_BS_help[rep] <- estimates[names(estimates) == "alpha_1"] alpha_2_SE_BS_help[rep] <- estimates[names(estimates) == "alpha_2"] alpha_3_SE_BS_help[rep] <- estimates[names(estimates) == "alpha_3"] if (setting == "GLM") { sigma_1_sq_SE_BS_help[rep] <- estimates[names(estimates) == "sigma_1_sq"] } if (setting == "AFT") { sigma_1_SE_BS_help[rep] <- estimates[names(estimates) == "sigma_1"] } alpha_4_SE_BS_help[rep] <- estimates[names(estimates) == "alpha_4"] alpha_XY_SE_BS_help[rep] <- estimates[names(estimates) == "alpha_XY"] sigma_2_sq_SE_BS_help[rep] <- estimates[names(estimates) == "sigma_2_sq"] } if (setting == "GLM") { theta_bootstrap_se <- c(sd(alpha_0_SE_BS_help,na.rm=T), sd(alpha_1_SE_BS_help,na.rm=T), sd(alpha_2_SE_BS_help,na.rm=T), sd(alpha_3_SE_BS_help,na.rm=T), sd(sigma_1_sq_SE_BS_help,na.rm=T), sd(alpha_4_SE_BS_help,na.rm=T), sd(alpha_XY_SE_BS_help,na.rm=T), sd(sigma_2_sq_SE_BS_help,na.rm=T)) names(theta_bootstrap_se) <- c("alpha_0", "alpha_1", "alpha_2", "alpha_3", "sigma_1_sq", "alpha_4", "alpha_XY", "sigma_2_sq") } if (setting == "AFT") { theta_bootstrap_se <- c(sd(alpha_0_SE_BS_help,na.rm=T), sd(alpha_1_SE_BS_help,na.rm=T), sd(alpha_2_SE_BS_help,na.rm=T), sd(alpha_3_SE_BS_help,na.rm=T), sd(sigma_1_SE_BS_help,na.rm=T), sd(alpha_4_SE_BS_help,na.rm=T), sd(alpha_XY_SE_BS_help,na.rm=T), sd(sigma_2_sq_SE_BS_help,na.rm=T)) names(theta_bootstrap_se) <- c("alpha_0", "alpha_1", "alpha_2", "alpha_3", "sigma_1", "alpha_4", "alpha_XY", "sigma_2_sq") } return(theta_bootstrap_se) } ``` ```{r, echo=FALSE} naive_se <- function(setting = "GLM", Y = NULL, X = NULL, K = NULL, L = NULL, C = NULL) { if (!requireNamespace("survival", quietly = TRUE)) { stop("Pkg needed for this function to work. Please install it.", call. = FALSE) } if (is.null(setting)) { stop("setting has to be supplied.") } if (is.null(Y) | is.null(X) | is.null(K) | is.null(L)) { stop("Data of one or more variables are not supplied.") } if (setting == "AFT" & is.null(C)) { stop("C has to be supplied for the AFT setting.") } n <- length(Y) if (setting == "GLM") { data_help <- data.frame(Y = Y, X = X, K = K, L = L) data_help <- data_help[complete.cases(data_help), ] ######### Stage 1 ######### fit_stage_1 <- lm(data_help$Y ~ data_help$K + data_help$X + data_help$L) alpha_1_out <- summary(fit_stage_1)$coefficients[2, 1] alpha_0_SE_out <- summary(fit_stage_1)$coefficients[1, 2] alpha_1_SE_out <- summary(fit_stage_1)$coefficients[2, 2] alpha_2_SE_out <- summary(fit_stage_1)$coefficients[3, 2] alpha_3_SE_out <- summary(fit_stage_1)$coefficients[4, 2] ######### Stage 2 ######### Y_tilde <- data_help$Y - mean(data_help$Y) - alpha_1_out * (data_help$K - mean(data_help$K)) fit_stage_2 <- lm(Y_tilde ~ data_help$X) alpha_4_SE_out <- summary(fit_stage_2)$coefficients[1, 2] alpha_XY_SE_out <- summary(fit_stage_2)$coefficients[2, 2] } if (setting == "AFT") { data_help <- data.frame(Y = Y, X = X, K = K, L = L, C = C) data_help <- data_help[complete.cases(data_help), ] ######### Stage 1 ######### fit_stage_1 <- survival::survreg(survival::Surv(data_help$Y, data_help$C) ~ data_help$K + data_help$X + data_help$L, dist = "gaussian") alpha_1_out <- summary(fit_stage_1)$table[2, 1] sigma_1_out <- fit_stage_1$scale alpha_0_SE_out <- summary(fit_stage_1)$table[1, 2] alpha_1_SE_out <- summary(fit_stage_1)$table[2, 2] alpha_2_SE_out <- summary(fit_stage_1)$table[3, 2] alpha_3_SE_out <- summary(fit_stage_1)$table[4, 2] ######### Stage 2 ######### mu <- fit_stage_1$linear.predictors Y_adj <- data_help$C * data_help$Y + (1 - data_help$C) * (mu + (sigma_1_out * dnorm((data_help$Y - mu)/sigma_1_out, mean = 0, sd = 1)/ (1 - pnorm((data_help$Y - mu)/sigma_1_out, mean = 0, sd = 1)))) Y_tilde <- Y_adj - mean(Y_adj) - alpha_1_out * (data_help$K - mean(data_help$K)) fit_stage_2 <- lm(Y_tilde ~ data_help$X) alpha_4_SE_out <- summary(fit_stage_2)$coefficients[1, 2] alpha_XY_SE_out <- summary(fit_stage_2)$coefficients[2, 2] } SE_estimates <- c(alpha_0_SE_out, alpha_1_SE_out, alpha_2_SE_out, alpha_3_SE_out, NA, alpha_4_SE_out, alpha_XY_SE_out, NA) names(SE_estimates) <- c("alpha_0", "alpha_1", "alpha_2", "alpha_3", "sigma_1_sq", "alpha_4", "alpha_XY", "sigma_2_sq") return(SE_estimates) } ``` ```{r} bootstrap_se(setting = "GLM", BS_rep = 1000, Y = dat$Y, X = dat$X, K = dat$K, L = dat$L) naive_se(setting = "GLM", Y = dat$Y, X = dat$X, K = dat$K, L = dat$L) ``` Finally, the functions `ciee()` and `ciee_loop()` allow an easy integrated use of all above functions and a simultaneous computation of the estimating equations approach using either standard error computation, the traditional regression-based approaches, and the SEM method. `ciee()` fits the model in equations (1)-(3) (e.g. the model in Figure 1) and yields parameter estimates, standard error estimates, and p-values for all parameters. `ciee_loop()` provides an extension of `ciee()` and allows the input of multiple exposure variables (e.g. multiple SNPs) which are tested sequentially. In the output of `ciee_loop()`, only the coefficient estimates, standard error estimates, and p-values with respect to the direct effect $\alpha_{XY}$ are provided. ```{r, echo=FALSE} ciee <- function(setting = "GLM", estimates = c("ee", "mult_reg", "res_reg", "sem"), ee_se = c("sandwich"), BS_rep = NULL, Y = NULL, X = NULL, K = NULL, L = NULL, C = NULL) { if (is.null(setting)) { stop("setting has to be supplied.") } if (is.null(estimates)) { stop("At least one method has to be computed.") } if ((("ee" %in% estimates) & is.null(ee_se)) | (("ee" %in% estimates) & length(ee_se) > 1)) { stop("If the estimating equations approach is chosen, one approach has to be chosen for the computation of standard errors.") } if (("bootstrap" %in% estimates) & is.null(BS_rep)) { stop("For the computation of bootstrap standard errors, the number of bootstrap samples has to be chosen.") } if (is.null(Y) | is.null(X) | is.null(K) | is.null(L)) { stop("Data of one or more variables is not supplied.") } if (setting == "AFT" & is.null(C)) { stop("C has to be supplied for the AFT setting.") } if (setting == "AFT" & ("sem" %in% estimates)) { stop("The structural equations modeling approach is only implemented for the GLM setting.") } if (setting == "AFT" & ("res_reg" %in% estimates)) { stop("The regression of residuals approach is only implemented for the GLM setting.") } if (setting == "GLM") { data_help <- data.frame(Y = Y, X = X, K = K, L = L) data_help <- data_help[complete.cases(data_help), ] if ("sem" %in% estimates) { results_sem <- sem_appl(Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L) } if ("mult_reg" %in% estimates) { results_mult_reg <- mult_reg(setting = setting, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L) } if ("res_reg" %in% estimates) { results_res_reg <- res_reg(Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L) } if ("ee" %in% estimates) { point_estimates_ee <- get_estimates(setting = setting, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L) if (ee_se == "sandwich") { # Obtain estimating functions expressions estfunct <- est_funct_expr(setting = "GLM") # Obtain matrices with all first and second derivatives derivobj <- deriv_obj(setting = setting, logL1 = estfunct$logL1, logL2 = estfunct$logL2, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L, estimates = point_estimates_ee) # Obtain score and hessian matrices results_scores <- scores(derivobj) results_hessian <- hessian(derivobj) # Obtain sandwich standard error estimates of the parameters se_estimates_ee <- sandwich_se(setting = setting, scores = results_scores, hessian = results_hessian) } if (ee_se == "bootstrap") { se_estimates_ee <- bootstrap_se(setting = setting, BS_rep = BS_rep, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L) } if (ee_se == "naive") { se_estimates_ee <- naive_se(setting = setting, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L) } wald_test_stat_ee <- point_estimates_ee[1:8]/se_estimates_ee pvalues_ee <- 2 * pnorm(-abs(wald_test_stat_ee)) results_ee <- list(point_estimates = point_estimates_ee[1:8], SE_estimates = se_estimates_ee, wald_test_stat = wald_test_stat_ee, pvalues = pvalues_ee) } } if (setting == "AFT") { data_help <- data.frame(Y = Y, X = X, K = K, L = L, C = C) data_help <- data_help[complete.cases(data_help), ] if ("mult_reg" %in% estimates) { results_mult_reg <- mult_reg(setting = setting, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L, C = data_help$C) } if ("ee" %in% estimates) { point_estimates_ee <- get_estimates(setting = setting, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L, C = data_help$C) if (ee_se == "sandwich") { # Obtain estimating functions expressions estfunct <- est_funct_expr(setting = setting) # Obtain matrices with all first and second derivatives derivobj <- deriv_obj(setting = setting, logL1 = estfunct$logL1, logL2 = estfunct$logL2, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L, C = data_help$C, estimates = point_estimates_ee) # Obtain score and hessian matrices results_scores <- scores(derivobj) results_hessian <- hessian(derivobj) # Obtain sandwich standard error estimates of the parameters se_estimates_ee <- sandwich_se(setting = setting, scores = results_scores, hessian = results_hessian) } if (ee_se == "bootstrap") { se_estimates_ee <- bootstrap_se(setting = setting, BS_rep = BS_rep, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L, C = data_help$C) } if (ee_se == "naive") { se_estimates_ee <- naive_se(setting = setting, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L, C = data_help$C) } wald_test_stat_ee <- point_estimates_ee[1:8]/se_estimates_ee pvalues_ee <- 2 * pnorm(-abs(wald_test_stat_ee)) results_ee <- list(point_estimates = point_estimates_ee[1:8], SE_estimates = se_estimates_ee, wald_test_stat = wald_test_stat_ee, pvalues = pvalues_ee) } } output <- list() if ("ee" %in% estimates) { output$results_ee <- results_ee } if ("mult_reg" %in% estimates) { output$results_mult_reg <- results_mult_reg } if ("res_reg" %in% estimates) { output$results_res_reg <- results_res_reg } if ("sem" %in% estimates) { output$results_sem <- results_sem } class(output) <- "ciee" return(output) } ``` ```{r, echo=FALSE} ciee_loop <- function(setting = "GLM", estimates = c("ee", "mult_reg", "res_reg", "sem"), ee_se = c("sandwich"), BS_rep = NULL, Y = NULL, X = NULL, K = NULL, L = NULL, C = NULL) { if (is.null(setting)) { stop("setting has to be supplied.") } if (is.null(estimates)) { stop("At least one method has to be computed.") } if ((("ee" %in% estimates) & is.null(ee_se)) | (("ee" %in% estimates) & length(ee_se) > 1)) { stop("If the estimating equations approach is chosen, one approach has to be chosen for the computation of standard errors.") } if (("bootstrap" %in% estimates) & is.null(BS_rep)) { stop("For the computation of bootstrap standard errors, the number of bootstrap samples has to be chosen.") } if (is.null(Y) | is.null(X) | is.null(K) | is.null(L)) { stop("Data of one or more variables is not supplied.") } if (setting == "AFT" & is.null(C)) { stop("C has to be supplied for the AFT setting.") } if (setting == "AFT" & ("sem" %in% estimates)) { stop("The structural equations modeling approach is only implemented for the GLM setting.") } if (setting == "AFT" & ("res_reg" %in% estimates)) { stop("The regression of residuals approach is only implemented for the GLM setting.") } if ("sem" %in% estimates) { results_sem <- list(point_estimates = NULL, SE_estimates = NULL, pvalues = NULL) } if ("mult_reg" %in% estimates) { results_mult_reg <- list(point_estimates = NULL, SE_estimates = NULL, pvalues = NULL) } if ("res_reg" %in% estimates) { results_res_reg <- list(point_estimates = NULL, SE_estimates = NULL, pvalues = NULL) } if ("ee" %in% estimates) { results_ee <- list(point_estimates = NULL, SE_estimates = NULL, wald_test_stat = NULL, pvalues = NULL) } k <- dim(X)[2] for (i in 1:k) { Xi <- X[, i] if (setting == "GLM") { data_help <- data.frame(Y = Y, X = Xi, K = K, L = L) data_help <- data_help[complete.cases(data_help), ] if ("sem" %in% estimates) { sem_help <- sem_appl(Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L) results_sem$point_estimates[i] <- sem_help$point_estimates[5] results_sem$SE_estimates[i] <- sem_help$SE_estimates[5] results_sem$pvalues[i] <- sem_help$pvalues[5] names(results_sem$point_estimates)[i] <- names(results_sem$SE_estimates)[i] <- names(results_sem$pvalues)[i] <- names(X)[i] } if ("mult_reg" %in% estimates) { mult_reg_help <- mult_reg(setting = setting, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L) results_mult_reg$point_estimates[i] <- mult_reg_help$point_estimates[3] results_mult_reg$SE_estimates[i] <- mult_reg_help$SE_estimates[3] results_mult_reg$pvalues[i] <- mult_reg_help$pvalues[3] names(results_mult_reg$point_estimates)[i] <- names(results_mult_reg$SE_estimates)[i] <- names(results_mult_reg$pvalues)[i] <- names(X)[i] } if ("res_reg" %in% estimates) { res_reg_help <- res_reg(Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L) results_res_reg$point_estimates[i] <- res_reg_help$point_estimates[5] results_res_reg$SE_estimates[i] <- res_reg_help$SE_estimates[5] results_res_reg$pvalues[i] <- res_reg_help$pvalues[5] names(results_res_reg$point_estimates)[i] <- names(results_res_reg$SE_estimates)[i] <- names(results_res_reg$pvalues)[i] <- names(X)[i] } if ("ee" %in% estimates) { point_estimates_ee <- get_estimates(setting = setting, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L) if (ee_se == "sandwich") { # Obtain estimating functions expressions estfunct <- est_funct_expr(setting = "GLM") # Obtain matrices with all first and second derivatives derivobj <- deriv_obj(setting = setting, logL1 = estfunct$logL1, logL2 = estfunct$logL2, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L, estimates = point_estimates_ee) # Obtain score and hessian matrices results_scores <- scores(derivobj) results_hessian <- hessian(derivobj) # Obtain sandwich standard error estimates of the parameters se_estimates_ee <- sandwich_se(setting = setting, scores = results_scores, hessian = results_hessian) } if (ee_se == "bootstrap") { se_estimates_ee <- bootstrap_se(setting = setting, BS_rep = BS_rep, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L) } if (ee_se == "naive") { se_estimates_ee <- naive_se(setting = setting, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L) } results_ee$point_estimates[i] <- point_estimates_ee[7] results_ee$SE_estimates[i] <- se_estimates_ee[7] results_ee$wald_test_stat[i] <- point_estimates_ee[7]/ se_estimates_ee[7] results_ee$pvalues[i] <- 2 * pnorm(-abs(point_estimates_ee[7]/ se_estimates_ee[7])) names(results_ee$point_estimates)[i] <- names(results_ee$SE_estimates)[i] <- names(results_ee$wald_test_stat)[i] <- names(results_ee$pvalues)[i] <- names(X)[i] } } if (setting == "AFT") { data_help <- data.frame(Y = Y, X = Xi, K = K, L = L, C = C) data_help <- data_help[complete.cases(data_help), ] if ("mult_reg" %in% estimates) { mult_reg_help <- mult_reg(setting = setting, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L, C = data_help$C) results_mult_reg$point_estimates[i] <- mult_reg_help$point_estimates[3] results_mult_reg$SE_estimates[i] <- mult_reg_help$SE_estimates[3] results_mult_reg$pvalues[i] <- mult_reg_help$pvalues[3] names(results_mult_reg$point_estimates)[i] <- names(results_mult_reg$SE_estimates)[i] <- names(results_mult_reg$pvalues)[i] <- names(X)[i] } if ("ee" %in% estimates) { point_estimates_ee <- get_estimates(setting = setting, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L, C = data_help$C) if (ee_se == "sandwich") { # Obtain estimating functions expressions estfunct <- est_funct_expr(setting = setting) # Obtain matrices with all first and second derivatives derivobj <- deriv_obj(setting = setting, logL1 = estfunct$logL1, logL2 = estfunct$logL2, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L, C = data_help$C, estimates = point_estimates_ee) # Obtain score and hessian matrices results_scores <- scores(derivobj) results_hessian <- hessian(derivobj) # Obtain sandwich standard error estimates of the parameters se_estimates_ee <- sandwich_se(setting = setting, scores = results_scores, hessian = results_hessian) } if (ee_se == "bootstrap") { se_estimates_ee <- bootstrap_se(setting = setting, BS_rep = BS_rep, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L, C = data_help$C) } if (ee_se == "naive") { se_estimates_ee <- naive_se(setting = setting, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L, C = data_help$C) } results_ee$point_estimates[i] <- point_estimates_ee[7] results_ee$SE_estimates[i] <- se_estimates_ee[7] results_ee$wald_test_stat[i] <- point_estimates_ee[7]/ se_estimates_ee[7] results_ee$pvalues[i] <- 2 * pnorm(-abs(point_estimates_ee[7]/ se_estimates_ee[7])) names(results_ee$point_estimates)[i] <- names(results_ee$SE_estimates)[i] <- names(results_ee$wald_test_stat)[i] <- names(results_ee$pvalues)[i] <- names(X)[i] } } } output <- list() if ("ee" %in% estimates) { output$results_ee <- results_ee } if ("mult_reg" %in% estimates) { output$results_mult_reg <- results_mult_reg } if ("res_reg" %in% estimates) { output$results_res_reg <- results_res_reg } if ("sem" %in% estimates) { output$results_sem <- results_sem } class(output) <- "ciee" return(output) } ``` ```{r} results_ciee <- ciee(setting = "GLM", Y = dat$Y, X = dat$X, K = dat$K, L = dat$L, estimates = c("ee", "mult_reg", "res_reg", "sem"), ee_se = "sandwich") results_ciee maf <- 0.2 n <- 1000 dat <- generate_data(n = n, maf = maf) datX <- data.frame(X = dat$X) names(datX)[1] <- "X1" for(i in 2:10){ X <- rbinom(n, size = 2, prob = maf) datX$X <- X names(datX)[i] <- paste("X", i, sep="") } results_ciee_loop <- ciee_loop(setting = "GLM", Y = dat$Y, X = datX, K = dat$K, L = dat$L) results_ciee_loop ``` Both `ciee()` and `ciee_loop()` return `ciee` objects as output, and the implemented `summary.ciee()` function can be used through the generic `summary()` to provide a reader-friendly formatted output of the results. ```{r, echo=FALSE} summary.ciee <- function(results = NULL) { if (is.null(results)) { stop("ciee output has to be supplied.") } res_out <- NULL if ("results_ee" %in% names(results)) { res_ee_out <- data.frame(point_estimates = results$results_ee$point_estimates, SE_estimates = results$results_ee$SE_estimates, wald_test_stat = results$results_ee$wald_test_stat, pvalues = results$results_ee$pvalues) rownames(res_ee_out) <- paste("CIEE", rownames(res_ee_out), sep = "_") print(paste("Results based on estimating equations.")) print(res_ee_out) res_out <- res_ee_out[,c(1,2,4)] } if ("results_mult_reg" %in% names(results)) { res_mr_out <- data.frame(point_estimates = results$results_mult_reg$point_estimates, SE_estimates = results$results_mult_reg$SE_estimates, pvalues = results$results_mult_reg$pvalues) rownames(res_mr_out) <- paste("MR", rownames(res_mr_out), sep = "_") print(paste("Results based on traditional multiple regression.")) print(res_mr_out) res_out <- rbind(res_out, res_mr_out) } if ("results_res_reg" %in% names(results)) { res_rr_out <- data.frame(point_estimates = results$results_res_reg$point_estimates, SE_estimates = results$results_res_reg$SE_estimates, pvalues = results$results_res_reg$pvalues) rownames(res_rr_out) <- paste("RR", rownames(res_rr_out), sep = "_") print(paste("Results based on traditional regression of residuals.")) print(res_rr_out) res_out <- rbind(res_out, res_rr_out) } if ("results_sem" %in% names(results)) { res_sem_out <- data.frame(point_estimates = results$results_sem$point_estimates, SE_estimates = results$results_sem$SE_estimates, pvalues = results$results_sem$pvalues) rownames(res_sem_out) <- paste("SEM", rownames(res_sem_out), sep = "_") print(paste("Results based on structural equation modeling.")) print(res_sem_out) res_out <- rbind(res_out, res_sem_out) } invisible(res_out) } ``` ```{r} summary(results_ciee) summary(results_ciee_loop) ``` ## References Bollen KA (1989). Structural equations with latent variables. New York: John Wiley & Sons. Konigorski S, Wang Y, Cigsar C, Yilmaz YE (2018). Estimating and testing direct genetic effects in directed acyclic graphs using estimating equations. Genetic Epidemiology, 42: 174-186. Rosseel Y (2012). lavaan: an R package for structural equation modeling. Journal of Statistical Software, 48(2), 1–36. Vansteelandt S, Goetgeluk S, Lutz S, et al. (2009). On the adjustment for covariates in genetic association analysis: a novel, simple principle to infer direct causal effects. Genetic Epidemiology, 33, 394-405.
/scratch/gouwar.j/cran-all/cranData/CIEE/inst/doc/ciee.Rmd
--- title: "Estimating and Testing Direct Effects in Directed Acyclic Graphs using Estimating Equations" author: "Stefan Konigorski" date: "March 19, 2018" output: pdf_document vignette: > %\VignetteIndexEntry{Estimating and Testing Direct Effects in Directed Acyclic Graphs using Estimating Equations} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ## Overview In any association study, it is important to distinguish direct and indirect effects in order to build truly functional models. For this purpose, we consider a directed acyclic graph (DAG) setting with an exposure variable, primary and intermediate outcome variables, and confounding factors. In order to make valid statistical inference on the direct effect of the exposure on the primary outcome, it is necessary to consider all potential effects in the graph, and we propose to use the estimating equation method with robust Huber-White sandwich standard errors. Then, a large-sample Wald-type test statistic is computed for testing the absence of the direct effect. In this package, the proposed causal inference method based on estimating equations (CIEE) is implemented for both the analysis of continuous and time-to-event primary outcomes subject to censoring for the model in Figure 1. Additionally, standard multiple regression, regression of residuals, and the structural equation approach are implemented for fitting the same model. Results from simulation studies (Konigorski et al., 2018) showed that CIEE successfully removes the effect of intermediate outcomes from the primary outcome and is robust against measured and unmeasured confounding of the indirect effect through observed factors. Also, an application in a genetic association study in the same study showed that CIEE can identify genetic variants that would be missed by traditional regression methods. Both multiple regression methods and the structural equation method fail in some scenarios where their corresponding test statistics lead to inflated type I errors. An alternative approach for the analysis of continuous traits is the sequential G-estimation method (Vansteelandt et al., 2009). In this package, CIEE is implemented for the model described in the DAG in Figure 1, which includes the direct effect $\alpha_{XY}$ of an exposure X on the primary outcome Y and an indirect effect of X on Y through a secondary outcome K. The model further includes measured and unmeasured factors L and U, respectively, which potentially confound the effect of K on Y. CIEE can also be applied to different models with different error distributions. The goal is to estimate and test the direct effect $\alpha_{XY}$, while removing the indirect effect of X on Y through K, and with robustness against effects of L and U. Without restriction of generality, it is assumed that there aren't any factors affecting X and that any such factors are included as covariates in the analysis or have been dealt with using other approaches. Also, we generally assume that either $\alpha_{LY}=0$ (L is a factor influencing K) or $\alpha_{XL}=0$ (L is a measured confounder of $K \to Y$). Otherwise, the effect of L as intermediate outcome could be removed from Y in the analysis analogously to K. ![Overview of the underlying directed acyclic graph considered in this study. It is assumed that $\alpha_{LY}=0$ so that L is a measured predictive factor of K, however, CIEE is also valid if L is a measured confounder of $K \to Y$ (i.e., $\alpha_{LY} \neq 0$ and $\alpha_{XL}=0$). ](Figure1.pdf) ## Alternative approaches Two traditional methods for the aim to estimate and test $\alpha_{XY}$ are (i) to include the intermediate outcomes and factors as covariates in a multiple regression (MR) model of the primary outcome on the exposure, or (ii) to first regress the primary outcome on the intermediate outcome and factors, and then regress the extracted residuals on the exposure (regression of residuals, RR). In more detail, estimates of $\alpha_{XY}$ are obtained from fitting the following models in the quantitative outcome setting for a normally-distributed Y (GLM setting): MR: Obtain the least squares (LS) estimate of $\alpha_{XY}$ by fitting $$Y_i = \alpha_0 + \alpha_{XY} x_i + \alpha_1 k_i + \alpha_2 l_i + \varepsilon_i, \ \varepsilon_i \sim N(0,\sigma_1^2)$$. RR: First, obtain residuals $\hat{\epsilon}_{1i} = y_i - \hat{\alpha}_0 - \hat{\alpha}_1 k_i - \hat{\alpha}_2 l_i$ by fitting $$Y_i = \alpha_0 + \alpha_1 k_i + \alpha_2 l_i + \varepsilon_{1i}, \ \varepsilon_{1i} \sim N(0,\sigma_1^2 )$$ using the LS estimation. Second, obtain the LS estimate of $\alpha_{XY}$ by fitting $$\hat{\varepsilon}_{1i} = \alpha_3 + \alpha_{XY} x_i + \varepsilon_{2i}, \ \varepsilon_{2i} \sim N(0, \sigma_2^2).$$ Then, $H_0: \alpha_{XY} = 0$ versus $H_A: \alpha_{XY} \neq 0$ is tested using the default t-test in the `lm()` function in R. For the analysis of a censored time-to-event primary trait Y (accelerated failure time setting; AFT), only the MR approach is implemented. Here, the equivalent censored log-linear regression model is fitted using the `survreg()` function in the `survival` R package to obtain the maximum likelihood estimate of $\alpha_{XY}$, and a Wald-type test is performed for testing the null hypothesis $H_0: \alpha_{XY} = 0$. Both approaches are implemented in the functions `mult_reg()` and `res_reg()` and can be used as follows. For this illustration, data is first generated using the `generate_data()` function, which generates data for the quantitative outcomes Y and K, a genetic marker X (single nucleotide polymorphism, SNP, taking values 0, 1, 2) as exposure, and observed as well as unobserved confounders L, U. ```{r, echo=FALSE} generate_data <- function(setting = "GLM", n = 1000, maf = 0.2, cens = 0.3, a = NULL, b = NULL, aXK = 0.2, aXY = 0.1, aXL = 0, aKY = 0.3, aLK = 0, aLY = 0, aUY = 0, aUL = 0, mu_X = NULL, sd_X = NULL, X_orth_U = TRUE, mu_U = 0, sd_U = 1, mu_K = 0, sd_K = 1, mu_L = 0, sd_L = 1, mu_Y = 0, sd_Y = 1) { U_out <- rnorm(n, mean = mu_U, sd = sd_U) if (setting == "AFT" & (is.null(a) | is.null(b))) { stop("a and b have to be specified under the AFT setting.") } if (X_orth_U == TRUE) { X_out <- rbinom(n, size = 2, prob = maf) } if (X_orth_U == FALSE) { X_out <- pnorm(U_out, mean = mu_X, sd = sd_X) p <- 1 - maf for (j in 1:length(X_out)) { if (X_out[j] < p^2) { X_out[j] <- 0 next } if (X_out[j] >= p^2 & X_out[j] < p^2 + 2 * p * (1 - p)) { X_out[j] <- 1 next } if (X_out[j] >= p^2 + 2 * p * (1 - p)) { X_out[j] <- 2 next } } } L_out <- aUL * U_out + aXL * X_out + rnorm(n, mean = mu_L, sd = sd_L) K_out <- aXK * X_out + aLK * L_out + rnorm(n, mean = mu_K, sd = sd_K) Y_out <- aUY * U_out + aKY * K_out + aXY * X_out + aLY * L_out + rnorm(n, mean = mu_Y, sd = sd_Y) data <- data.frame(Y = Y_out, K = K_out, X = X_out, L = L_out, U = U_out) if (setting == "AFT") { T_help <- exp(Y_out) ### Create censoring indicator and censored times no censoring if (cens == 0) { T_out <- T_help C_out <- rep(1, n) # C_out==0 is censored, C_out==1 is uncensored } if (!cens == 0) { # there is censoring; cens is the percentage of censored data T_cens <- runif(n, min = a, max = b) # a, b for desired censoring rate C_out <- as.numeric(T_help < T_cens) # C==0 censored, C==1 uncensored T_out <- pmin(T_help, T_cens) Y_out <- log(T_out) } cens_out <- sum(abs(C_out - 1))/n data <- data.frame(Y = Y_out, K = K_out, X = X_out, L = L_out, U = U_out, T = T_out, C = C_out) print(paste("The empirical censoring rate obtained through the specified parameters a=", a, " and b=", b, " is ", cens_out, ".", sep = "")) if (abs(cens_out - cens) > 0.1) { warning(paste("This obtained empirical censoring rate is quite different from the desired censoring rate cens=", cens, ". Please check and adapt values for a and b.", sep = "")) } } return(data) } ``` ```{r, echo=FALSE} mult_reg <- function(setting = "GLM", Y = NULL, X = NULL, K = NULL, L = NULL, C = NULL) { if (!requireNamespace("survival", quietly = TRUE)) { stop("Pkg needed for this function to work. Please install it.", call. = FALSE) } if (is.null(setting)) { stop("setting has to be supplied.") } if (is.null(Y) | is.null(X) | is.null(K) | is.null(L)) { stop("Data of one or more variables are not supplied.") } if (setting == "AFT" & is.null(C)) { stop("C has to be supplied for the AFT setting.") } if (setting == "GLM") { fit_mult_reg <- lm(Y ~ K + X + L) point_estimates <- c(summary(fit_mult_reg)$coefficients[1, 1], summary(fit_mult_reg)$coefficients[2, 1], summary(fit_mult_reg)$coefficients[3, 1], summary(fit_mult_reg)$coefficients[4, 1]) SE_estimates <- c(summary(fit_mult_reg)$coefficients[1, 2], summary(fit_mult_reg)$coefficients[2, 2], summary(fit_mult_reg)$coefficients[3, 2], summary(fit_mult_reg)$coefficients[4, 2]) pvalues <- c(summary(fit_mult_reg)$coefficients[1, 4], summary(fit_mult_reg)$coefficients[2, 4], summary(fit_mult_reg)$coefficients[3, 4], summary(fit_mult_reg)$coefficients[4, 4]) names(point_estimates) <- names(SE_estimates) <- names(pvalues) <- c("alpha_0", "alpha_1", "alpha_XY", "alpha_2") } if (setting == "AFT") { fit_mult_reg <- survival::survreg(survival::Surv(Y, C) ~ K + X + L, dist = "gaussian") point_estimates <- c(summary(fit_mult_reg)$table[1, 1], summary(fit_mult_reg)$table[2, 1], summary(fit_mult_reg)$table[3, 1], summary(fit_mult_reg)$table[4, 1]) SE_estimates <- c(summary(fit_mult_reg)$table[1, 2], summary(fit_mult_reg)$table[2, 2], summary(fit_mult_reg)$table[3, 2], summary(fit_mult_reg)$table[4, 2]) pvalues <- c(summary(fit_mult_reg)$table[1, 4], summary(fit_mult_reg)$table[2, 4], summary(fit_mult_reg)$table[3, 4], summary(fit_mult_reg)$table[4, 4]) names(point_estimates) <- names(SE_estimates) <- names(pvalues) <- c("alpha_0", "alpha_1", "alpha_XY", "alpha_2") } return(list(point_estimates = point_estimates, SE_estimates = SE_estimates, pvalues = pvalues)) } ``` ```{r, echo=FALSE} res_reg <- function(Y = NULL, X = NULL, K = NULL, L = NULL) { if (is.null(Y) | is.null(X) | is.null(K) | is.null(L)) { stop("Data of one or more variables is not supplied.") } data_help <- data.frame(Y = Y, X = X, K = K, L = L) data_help <- data_help[complete.cases(data_help), ] fit_res_reg_1 <- lm(data_help$Y ~ data_help$K + data_help$L) res <- fit_res_reg_1$residuals fit_res_reg_2 <- lm(res ~ data_help$X) point_estimates <- c(summary(fit_res_reg_1)$coefficients[1, 1], summary(fit_res_reg_1)$coefficients[2, 1], summary(fit_res_reg_1)$coefficients[3, 1], summary(fit_res_reg_2)$coefficients[1, 1], summary(fit_res_reg_2)$coefficients[2, 1]) SE_estimates <- c(summary(fit_res_reg_1)$coefficients[1, 2], summary(fit_res_reg_1)$coefficients[2, 2], summary(fit_res_reg_1)$coefficients[3, 2], summary(fit_res_reg_2)$coefficients[1, 2], summary(fit_res_reg_2)$coefficients[2, 2]) pvalues <- c(summary(fit_res_reg_1)$coefficients[1, 4], summary(fit_res_reg_1)$coefficients[2, 4], summary(fit_res_reg_1)$coefficients[3, 4], summary(fit_res_reg_2)$coefficients[1, 4], summary(fit_res_reg_2)$coefficients[2, 4]) names(point_estimates) <- names(SE_estimates) <- names(pvalues) <- c("alpha_0", "alpha_1", "alpha_2", "alpha_3", "alpha_XY") return(list(point_estimates = point_estimates, SE_estimates = SE_estimates, pvalues = pvalues)) } ``` ```{r} dat <- generate_data(setting="GLM", n = 1000, maf = 0.2, cens = 0.3, a = NULL, b = NULL, aUL = 0, aXL = 0, aXK = 0.2, aLK = 0, aUY = 0, aKY = 0.3, aXY = 0.1, aLY = 0, mu_U = 0, sd_U = 1, X_orth_U = TRUE, mu_X = NULL, sd_X = NULL, mu_L = 0, sd_L = 1, mu_K = 0, sd_K = 1, mu_Y = 0, sd_Y = 1) head(dat) mult_reg(setting = "GLM", Y = dat$Y, X = dat$X, K = dat$K, L = dat$L) res_reg(Y = dat$Y, X = dat$X, K = dat$K, L = dat$L) ``` As another approach for modeling DAGs, the structural equation modeling method (SEM; Bollen, 1989) can be used. Among others, it is implemented in the `sem()` function of the `lavaan` package (Rosseel, 2012). For a comparison of the results, the function `sem_appl()` applies the SEM method to the DAG in Figure 1 based on the following model equations: $$L_i = \alpha_0 + \alpha_1 x_i + \varepsilon_{1i}, \ \varepsilon_{1i} \sim N(0,\sigma_1^2 ) $$ $$K_i = \alpha_2 + \alpha_3 x_i + \alpha_2 l_i + \varepsilon_{2i}, \ \varepsilon_{2i} \sim N(0,\sigma_2^2 ) $$ $$Y_i = \alpha_5 + \alpha_6 k_i + \alpha_{XY} x_i + \varepsilon_{3i}, \ \varepsilon_{3i} \sim N(0,\sigma_3^2 ) $$ ```{r, echo=FALSE} sem_appl <- function(setting = "GLM", Y = NULL, X = NULL, K = NULL, L = NULL) { if (!requireNamespace("lavaan", quietly = TRUE)) { stop("Pkg needed for this function to work. Please install it.", call. = FALSE) } if (is.null(setting)) { stop("setting has to be supplied.") } if (setting == "AFT") { stop("Only GLM setting is implemented.") } if (is.null(Y) | is.null(X) | is.null(K) | is.null(L)) { stop("Data of one or more variables are not supplied.") } data_help <- data.frame(Y = Y, X = X, K = K, L = L) data_help <- data_help[complete.cases(data_help), ] model <- " L ~ X K ~ X + L Y ~ K + X " fit <- lavaan::sem(model, data = data_help) point_estimates <- c(fit@Fit@est[1], fit@Fit@est[2], fit@Fit@est[3], fit@Fit@est[4], fit@Fit@est[5]) SE_estimates <- c(fit@Fit@se[1], fit@Fit@se[2], fit@Fit@se[3], fit@Fit@se[4], fit@Fit@se[5]) pvalues <- 2 * pnorm(-abs(point_estimates/SE_estimates)) names(point_estimates) <- names(SE_estimates) <- names(pvalues) <- c("alpha_1", "alpha_3", "alpha_4", "alpha_6", "alpha_XY") return(list(point_estimates = point_estimates, SE_estimates = SE_estimates, pvalues = pvalues)) } ``` ```{r} sem_appl(Y = dat$Y, X = dat$X, K = dat$K, L = dat$L) ``` Further proposed approaches for fitting the model in Figure 1 include the two-stage sequential G-estimation method (Vansteelandt et al., 2009). It first removes the effect of K from the primary outcome Y, and then tests the association of X with the adjusted primary outcome. In more detail, for the analyis of a quantitative outcome Y with n independent observations, in the first stage, the effect of K on Y, $\alpha_1$, is estimated and $\hat{\alpha}_1$ is obtained using the LS estimation method under the model \begin{equation} Y_i = \alpha_0 + \alpha_1 k_i + \alpha_2 x_i + \alpha_3 l_i + \varepsilon_i, \ \varepsilon_i \sim N(0,\sigma_1^2), \quad i=1,…,n \end{equation} Then, to block all indirect paths from X to Y, the adjusted outcome $\tilde{Y}$ is obtained by removing the effect of K on Y with \begin{equation} \tilde{y}_i = y_i - \bar{y} - \hat{\alpha}_1 (k_i - \bar{k}) \end{equation} where $\bar{y} = \sum_{i=1}^n y_i$ and $\bar{k} = \sum_{i=1}^n k_i$. In the second stage, the significance of the direct effect of X on Y, $\alpha_{XY}$, is tested under the model \begin{equation} \tilde{Y}_i = \alpha_4 + \alpha_{XY} x_i + \varepsilon_i, \ \varepsilon_i \sim N(0,\sigma_2^2 ) \end{equation} using the proposed test statistic in Vansteelandt and colleagues (2009). The approach is implemented in the `CGene` package, which can be obtained from [cran.r-project.org/src/contrib/Archive/CGene/](https://cran.r-project.org/src/contrib/Archive/CGene/). ## Causal inference using estimating equations (CIEE) CIEE follows the general idea of the two-stage sequential G-estimation method with the major difference that the approach is one-stage and obtains coefficient estimates of all parameters simultaneously by solving estimating equations. This also allows building on existing asymptotic properties of the estimator and obtaining robust sandwich standard error estimates considering the additional variability of the estimates from the outcome adjustment. In more detail, for the analyis of a quantitative outcome Y, we formulate unbiased estimating equations $U(\theta)=0$ for a consistent estimation of the unknown parameter vector $\theta = (\alpha_0, \alpha_1, \alpha_2, \alpha_3, \sigma_1^2, \alpha_4, \alpha_{XY}, \sigma_2^2)^T$ where $$ U(\theta) = \left( \frac{\partial l_1(\theta)}{\partial \alpha_0}, \frac{\partial l_1(\theta)}{\partial \alpha_1}, \frac{\partial l_1(\theta)}{\partial \alpha_2}, \frac{\partial l_1(\theta)}{\partial \alpha_3}, \frac{\partial l_1(\theta)}{\partial \sigma_1^2}, \frac{\partial l_1(\theta)}{\partial \alpha_4}, \frac{\partial l_1(\theta)}{\partial \alpha_{XY}}, \frac{\partial l_1(\theta)}{\partial \sigma_2^2} \right)^T $$ with $$ l_1(\theta) = \sum_{i=1}^n \left[ -log(\sigma_1) + log\left( \phi\left( \frac{y_i - \alpha_0 - \alpha_1 k_i - \alpha_2 x_i - \alpha_3 l_i}{\sigma_1} \right) \right) \right]$$ and $$ l_2(\theta) = \sum_{i=1}^n \left[ -log(\sigma_2) + log\left( \phi\left( \frac{y_i - \bar{y} - \alpha_1 (k_i - \bar{k}) - \alpha_4 - \alpha_{XY} x_i}{\sigma_2} \right) \right) \right],$$ where $\phi$ is the probability density function of the standard normal distribution. By solving the first five estimating equations based on $l_1(\theta)$, we are hence obtaining estimates of $\alpha_0, \alpha_1, \alpha_2, \alpha_3, \sigma_1^2$. Analogously, solving the last three estimating equations based on $l_2(\theta)$ yields estimates of $\alpha_4, \alpha_{XY}, \sigma_2^2$. To give an intuition on how these estimating equations are obtained, $l_1(\theta)$ is the log-likelihood function under the model in (1) and $l_2(\theta)$ is the log-likelihood function under the model in (3) given that $\alpha_1$ is known. All parameters in $\theta$ are estimated simultaneously and the additional variability obtained in the outcome adjustment in (2) is considered by using the robust Huber-White sandwich estimator of the standard error of $\hat{\theta}$. Then, the large sample Wald-type test statistic $\hat{\theta}/\widehat{SE}(\hat{\theta})$, which has an asymptotic standard normal distribution, is computed to test the absence of the exposure effect $\alpha_{XY}$. For the analysis of a censored time-to-event primary outcome Y, the estimating equations can be constructed as described above for a quantitative primary phenotype (for the same parameters except for $\sigma_1$ instead of $\sigma_1^2$), but in order to remove the effect of K from Y, the true underlying log survival times $Y_{est}$ need to be estimated for censored survival times. For uncensored survival times, $Y_{est}$ equals the observed log-survival time Y. Then, the estimating equations are constructed accordingly, the robust Huber-White sandwich estimator of the standard error is obtained and the large-sample Wald-type tests are computed. For more statistical details, see Konigorski et al. (2018). In the implementation of CIEE in this package, the `est_funct_expr()` function contains the estimating equations as an expression. ```{r, echo=FALSE} est_funct_expr <- function(setting = "GLM") { if (is.null(setting)) { stop("setting has to be supplied.") } if (setting == "GLM") { logL1 <- expression(log((1/sqrt(sigma1sq)) * dnorm((y_i - alpha0 - alpha1 * k_i - alpha2 * x_i - alpha3 * l_i)/ sqrt(sigma1sq), mean = 0, sd = 1))) logL2 <- expression(log((1/sqrt(sigma2sq)) * dnorm((y_i - y_bar - alpha1 * (k_i - k_bar) - alpha4 - alphaXY * x_i)/ sqrt(sigma2sq), mean = 0, sd = 1))) } if (setting == "AFT") { logL1 <- expression(-c_i * log(sigma1) + c_i * log(dnorm((y_i - alpha0 - alpha1 * k_i - alpha2 * x_i - alpha3 * l_i)/sigma1, mean = 0, sd = 1)) + (1 - c_i) * log(1 - pnorm((y_i - alpha0 - alpha1 * k_i - alpha2 * x_i - alpha3 * l_i)/ sigma1, mean = 0, sd = 1))) logL2 <- expression(log((1/sqrt(sigma2sq)) * dnorm(((c_i * y_i + (1 - c_i) * ((alpha0 + alpha1 * k_i + alpha2 * x_i + alpha3 * l_i) + (sigma1 * dnorm((y_i - alpha0 - alpha1 * k_i - alpha2 * x_i - alpha3 * l_i)/sigma1, mean = 0, sd = 1)/(1 - pnorm((y_i - alpha0 - alpha1 * k_i - alpha2 * x_i - alpha3 * l_i)/sigma1, mean = 0, sd = 1))))) - y_adj_bar - alpha1 * (k_i - k_bar) - alpha4 - alphaXY * x_i)/sqrt(sigma2sq), mean = 0, sd = 1))) } return(list(logL1 = logL1, logL2 = logL2)) } ``` ```{r} estfunct <- est_funct_expr(setting="GLM") estfunct est_funct_expr(setting = "AFT") ``` The function `get_estimates()` obtains estimates of the parameters in the models (1)-(3) by using the `lm()` and `survreg()` functions for computational purposes. The estimates are identical to estimates obtained by solving the estimating equations. ```{r, echo=FALSE} get_estimates <- function(setting = "GLM", Y = NULL, X = NULL, K = NULL, L = NULL, C = NULL) { if (!requireNamespace("survival", quietly = TRUE)) { stop("Pkg needed for this function to work. Please install it.", call. = FALSE) } if (is.null(setting)) { stop("setting has to be supplied.") } if (is.null(Y) | is.null(X) | is.null(K) | is.null(L)) { stop("Data of one or more variables are not supplied.") } if (setting == "AFT" & is.null(C)) { stop("C has to be supplied for the AFT setting.") } n <- length(Y) if (setting == "GLM") { data_help <- data.frame(Y = Y, X = X, K = K, L = L) data_help <- data_help[complete.cases(data_help), ] ######### Stage 1 ######### fit_stage_1 <- lm(data_help$Y ~ data_help$K + data_help$X + data_help$L) alpha_0_out <- summary(fit_stage_1)$coefficients[1, 1] alpha_1_out <- summary(fit_stage_1)$coefficients[2, 1] alpha_2_out <- summary(fit_stage_1)$coefficients[3, 1] alpha_3_out <- summary(fit_stage_1)$coefficients[4, 1] sigma_1_sq_out <- (n - 4)/n * summary(fit_stage_1)$sigma^2 ######### Stage 2 ######### Y_tilde <- data_help$Y - mean(data_help$Y) - alpha_1_out * (data_help$K - mean(data_help$K)) fit_stage_2 <- lm(Y_tilde ~ data_help$X) alpha_4_out <- summary(fit_stage_2)$coefficients[1, 1] alpha_XY_out <- summary(fit_stage_2)$coefficients[2, 1] sigma_2_sq_out <- (n - 2)/n * summary(fit_stage_2)$sigma^2 point_estimates <- c(alpha_0_out, alpha_1_out, alpha_2_out, alpha_3_out, sigma_1_sq_out, alpha_4_out, alpha_XY_out, sigma_2_sq_out) names(point_estimates) <- c("alpha_0", "alpha_1", "alpha_2", "alpha_3", "sigma_1_sq", "alpha_4", "alpha_XY", "sigma_2_sq") } if (setting == "AFT") { data_help <- data.frame(Y = Y, X = X, K = K, L = L, C = C) data_help <- data_help[complete.cases(data_help), ] ######### Stage 1 ######### fit_stage_1 <- survival::survreg(survival::Surv(data_help$Y, data_help$C) ~ data_help$K + data_help$X + data_help$L, dist = "gaussian") alpha_0_out <- summary(fit_stage_1)$table[1, 1] alpha_1_out <- summary(fit_stage_1)$table[2, 1] alpha_2_out <- summary(fit_stage_1)$table[3, 1] alpha_3_out <- summary(fit_stage_1)$table[4, 1] sigma_1_out <- fit_stage_1$scale ######### Stage 2 ######### mu <- fit_stage_1$linear.predictors Y_adj <- data_help$C * data_help$Y + (1 - data_help$C) * (mu + (sigma_1_out * dnorm((data_help$Y - mu)/sigma_1_out, mean = 0, sd = 1)/(1 - pnorm((data_help$Y - mu)/sigma_1_out, mean = 0, sd = 1)))) Y_tilde <- Y_adj - mean(Y_adj) - alpha_1_out * (data_help$K - mean(data_help$K)) fit_stage_2 <- lm(Y_tilde ~ data_help$X) alpha_4_out <- summary(fit_stage_2)$coefficients[1, 1] alpha_XY_out <- summary(fit_stage_2)$coefficients[2, 1] sigma_2_sq_out <- (n - 2)/n * summary(fit_stage_2)$sigma^2 point_estimates <- c(alpha_0_out, alpha_1_out, alpha_2_out, alpha_3_out, sigma_1_out, alpha_4_out, alpha_XY_out, sigma_2_sq_out, mean(Y_adj)) names(point_estimates) <- c("alpha_0", "alpha_1", "alpha_2", "alpha_3", "sigma_1", "alpha_4", "alpha_XY", "sigma_2_sq", "y_adj_bar") } return(point_estimates) } ``` ```{r} estimates <- get_estimates(setting = "GLM", Y = dat$Y, X = dat$X, K = dat$K, L = dat$L) estimates ``` In order to compute the robust Huber-White sandwich estimator of the parameters, in a first step, the `deriv_obj()` function computes the expression of all first and second derivatives for the 8 parameters $\alpha_0, \alpha_1, \alpha_2, \alpha_3, \sigma_1^2, \alpha_4, \alpha_{XY}, \sigma_2^2$ by using the expressions from the `est_funct_expr()` function as input. Then, the numerical values of all first and second derivatives are obtained for the observed data and parameter point estimates for all observed individuals, using the `scores()` and `hessian()` functions. ```{r, echo=FALSE} deriv_obj <- function(setting = "GLM", logL1 = NULL, logL2 = NULL, Y = NULL, X = NULL, K = NULL, L = NULL, C = NULL, estimates = NULL) { if (is.null(setting) | is.null(logL1) | is.null(logL2) | is.null(estimates)) { stop("One or more arguments of the function are missing.") } if (is.null(Y) | is.null(X) | is.null(K) | is.null(L)) { stop("Data of one or more variables are not supplied.") } if (setting == "AFT" & is.null(C)) { stop("C has to be supplied for the AFT setting.") } n <- length(Y) if (setting == "GLM") { data_help <- data.frame(Y = Y, X = X, K = K, L = L) data_help <- data_help[complete.cases(data_help), ] U12345_i <- deriv(expr = logL1, namevec = c("alpha0", "alpha1", "alpha2", "alpha3", "sigma1sq", "alpha4", "alphaXY", "sigma2sq"), function.arg = c("y_i", "k_i", "x_i", "l_i", "alpha0", "alpha1", "alpha2", "alpha3", "sigma1sq"), func = T, hessian = T) U678_i <- deriv(expr = logL2, namevec = c("alpha0", "alpha1", "alpha2", "alpha3", "sigma1sq", "alpha4", "alphaXY", "sigma2sq"), function.arg = c("y_i", "k_i", "x_i", "y_bar", "k_bar", "alpha1", "alpha4", "alphaXY", "sigma2sq"), func = T, hessian = T) logL1_deriv <- attributes(U12345_i(y_i = data_help$Y, k_i = data_help$K, x_i = data_help$X, l_i = data_help$L, alpha0 = estimates[names(estimates) == "alpha_0"], alpha1 = estimates[names(estimates) == "alpha_1"], alpha2 = estimates[names(estimates) == "alpha_2"], alpha3 = estimates[names(estimates) == "alpha_3"], sigma1sq = estimates[names(estimates) == "sigma_1_sq"])) logL2_deriv <- attributes(U678_i(y_i = data_help$Y, k_i = data_help$K, x_i = data_help$X, y_bar = mean(data_help$Y), k_bar = mean(data_help$K), alpha1 = estimates[names(estimates) == "alpha_1"], alpha4 = estimates[names(estimates) == "alpha_4"], alphaXY = estimates[names(estimates) == "alpha_XY"], sigma2sq = estimates[names(estimates) == "sigma_2_sq"])) deriv_obj <- list(logL1_deriv = logL1_deriv, logL2_deriv = logL2_deriv) } if (setting == "AFT") { data_help <- data.frame(Y = Y, X = X, K = K, L = L, C = C) data_help <- data_help[complete.cases(data_help), ] U12345_i <- deriv(expr = logL1, namevec = c("alpha0", "alpha1", "alpha2", "alpha3", "sigma1", "alpha4", "alphaXY", "sigma2sq"), function.arg = c("y_i", "c_i", "k_i", "x_i", "l_i", "alpha0", "alpha1", "alpha2", "alpha3", "sigma1"), func = T, hessian = T) U678_i <- deriv(expr = logL2, namevec = c("alpha0", "alpha1", "alpha2", "alpha3", "sigma1", "alpha4", "alphaXY", "sigma2sq"), function.arg = c("y_i", "c_i", "k_i", "x_i", "l_i", "y_adj_bar", "k_bar", "alpha0", "alpha1", "alpha2", "alpha3", "sigma1", "alpha4", "alphaXY", "sigma2sq"), func = T, hessian = T) logL1_deriv <- attributes(U12345_i(y_i = data_help$Y, c_i = data_help$C, k_i = data_help$K, x_i = data_help$X, l_i = data_help$L, alpha0 = estimates[names(estimates) == "alpha_0"], alpha1 = estimates[names(estimates) == "alpha_1"], alpha2 = estimates[names(estimates) == "alpha_2"], alpha3 = estimates[names(estimates) == "alpha_3"], sigma1 = estimates[names(estimates) == "sigma_1"])) logL2_deriv <- attributes(U678_i(y_i = data_help$Y, c_i = data_help$C, k_i = data_help$K, x_i = data_help$X, l_i = data_help$L, y_adj_bar = estimates[names(estimates) == "y_adj_bar"], k_bar = mean(data_help$K), alpha0 = estimates[names(estimates) == "alpha_0"], alpha1 = estimates[names(estimates) == "alpha_1"], alpha2 = estimates[names(estimates) == "alpha_2"], alpha3 = estimates[names(estimates) == "alpha_3"], sigma1 = estimates[names(estimates) == "sigma_1"], alpha4 = estimates[names(estimates) == "alpha_4"], alphaXY = estimates[names(estimates) == "alpha_XY"], sigma2sq = estimates[names(estimates) == "sigma_2_sq"])) deriv_obj <- list(logL1_deriv = logL1_deriv, logL2_deriv = logL2_deriv) } return(deriv_obj) } ``` ```{r, echo=FALSE} scores <- function(derivobj = NULL) { if (is.null(derivobj)) { stop("derivobj has to be supplied.") } scores_out <- cbind(derivobj[[1]]$gradient[, 1:5], derivobj[[2]]$gradient[, 6:8]) return(scores_out) } ``` ```{r, echo=FALSE} hessian <- function(derivobj = NULL) { if (is.null(derivobj)) { stop("derivobj has to be supplied.") } hessian_out <- derivobj[[1]]$hessian hessian_out[, 6:8, ] <- derivobj[[2]]$hessian[, 6:8, ] return(hessian_out) } ``` ```{r} derivobj <- deriv_obj(setting = "GLM", logL1 = estfunct$logL1, logL2 = estfunct$logL2, Y = dat$Y, X = dat$X, K = dat$K, L = dat$L, estimates = estimates) names(derivobj) head(derivobj$logL1_deriv$gradient) score_matrix <- scores(derivobj) head(score_matrix) hessian_matrix <- hessian(derivobj) str(hessian_matrix) ``` The robust Huber-White sandwich estimator of the standard error can then be obtained using the `sandwich_se()` function: ```{r, echo=FALSE} sandwich_se <- function(setting = "GLM", scores = NULL, hessian = NULL) { if (is.null(scores) | is.null(hessian)) { stop("scores and hessian have to be supplied.") } n <- dim(scores)[1] ### A_n matrix ### A_n <- matrix(, nrow = 8, ncol = 8) for (A_n_i in 1:8) { for (A_n_j in 1:8) { A_n[A_n_i, A_n_j] <- sum(hessian[, A_n_i, A_n_j]) } } A_n <- -(1/n) * A_n ### B_n matrix ### B_n <- matrix(, nrow = 8, ncol = 8) for (B_n_i in 1:8) { for (B_n_j in 1:8) { B_n[B_n_i, B_n_j] <- sum(scores[, B_n_i] * scores[, B_n_j]) } } B_n <- (1/n) * B_n ### C_n matrix ### C_n <- solve(A_n) %*% B_n %*% t(solve(A_n)) ### Variance estimates of coefficients ### theta_EE_se <- (1/n) * diag(C_n) theta_EE_se <- sqrt(theta_EE_se) if (setting == "GLM") { names(theta_EE_se) <- c("alpha_0", "alpha_1", "alpha_2", "alpha_3", "sigma_1_sq", "alpha_4", "alpha_XY", "sigma_2_sq") } if (setting == "AFT") { names(theta_EE_se) <- c("alpha_0", "alpha_1", "alpha_2", "alpha_3", "sigma_1", "alpha_4", "alpha_XY", "sigma_2_sq") } return(theta_EE_se) } ``` ```{r} sandwich_se(scores = score_matrix, hessian = hessian_matrix) ``` Alternatively, bootstrap standard error estimates can be computed using the `bootstrap_se()` function. Also, for comparison, the function `naive_se()` computes naive standard error estimates of the parameter estimates of $\alpha_0, \alpha_1, \alpha_2, \alpha_3, \alpha_4, \alpha_{XY}$ without accounting for the additional variability due to the two stages in the model in (1)-(3): ```{r, echo=FALSE} bootstrap_se <- function(setting = "GLM", BS_rep = 1000, Y = NULL, X = NULL, K = NULL, L = NULL, C = NULL) { if (is.null(setting)) { stop("setting has to be supplied.") } if (is.null(Y) | is.null(X) | is.null(K) | is.null(L)) { stop("Data of one or more variables are not supplied.") } if (setting == "AFT" & is.null(C)) { stop("C has to be supplied for the AFT setting.") } n <- length(Y) if (setting == "GLM") { alpha_0_SE_BS_help <- alpha_1_SE_BS_help <- alpha_2_SE_BS_help <- alpha_3_SE_BS_help <- sigma_1_sq_SE_BS_help <- alpha_4_SE_BS_help <- alpha_XY_SE_BS_help <- sigma_2_sq_SE_BS_help <- NULL } if (setting == "AFT") { alpha_0_SE_BS_help <- alpha_1_SE_BS_help <- alpha_2_SE_BS_help <- alpha_3_SE_BS_help <- sigma_1_SE_BS_help <- alpha_4_SE_BS_help <- alpha_XY_SE_BS_help <- sigma_2_sq_SE_BS_help <- NULL } for (rep in 1:BS_rep) { id <- sample(1:n, n, replace = TRUE) if (setting == "GLM") { data_id <- data.frame(X = X[id], L = L[id], K = K[id], Y = Y[id]) estimates <- get_estimates(setting = setting, Y = data_id$Y, X = data_id$X, K = data_id$K, L = data_id$L) } if (setting == "AFT") { data_id <- data.frame(X = X[id], L = L[id], K = K[id], Y = Y[id], T = T[id], C = C[id]) estimates <- get_estimates(setting = setting, Y = data_id$Y, X = data_id$X, K = data_id$K, L = data_id$L, C = data_id$C) } alpha_0_SE_BS_help[rep] <- estimates[names(estimates) == "alpha_0"] alpha_1_SE_BS_help[rep] <- estimates[names(estimates) == "alpha_1"] alpha_2_SE_BS_help[rep] <- estimates[names(estimates) == "alpha_2"] alpha_3_SE_BS_help[rep] <- estimates[names(estimates) == "alpha_3"] if (setting == "GLM") { sigma_1_sq_SE_BS_help[rep] <- estimates[names(estimates) == "sigma_1_sq"] } if (setting == "AFT") { sigma_1_SE_BS_help[rep] <- estimates[names(estimates) == "sigma_1"] } alpha_4_SE_BS_help[rep] <- estimates[names(estimates) == "alpha_4"] alpha_XY_SE_BS_help[rep] <- estimates[names(estimates) == "alpha_XY"] sigma_2_sq_SE_BS_help[rep] <- estimates[names(estimates) == "sigma_2_sq"] } if (setting == "GLM") { theta_bootstrap_se <- c(sd(alpha_0_SE_BS_help,na.rm=T), sd(alpha_1_SE_BS_help,na.rm=T), sd(alpha_2_SE_BS_help,na.rm=T), sd(alpha_3_SE_BS_help,na.rm=T), sd(sigma_1_sq_SE_BS_help,na.rm=T), sd(alpha_4_SE_BS_help,na.rm=T), sd(alpha_XY_SE_BS_help,na.rm=T), sd(sigma_2_sq_SE_BS_help,na.rm=T)) names(theta_bootstrap_se) <- c("alpha_0", "alpha_1", "alpha_2", "alpha_3", "sigma_1_sq", "alpha_4", "alpha_XY", "sigma_2_sq") } if (setting == "AFT") { theta_bootstrap_se <- c(sd(alpha_0_SE_BS_help,na.rm=T), sd(alpha_1_SE_BS_help,na.rm=T), sd(alpha_2_SE_BS_help,na.rm=T), sd(alpha_3_SE_BS_help,na.rm=T), sd(sigma_1_SE_BS_help,na.rm=T), sd(alpha_4_SE_BS_help,na.rm=T), sd(alpha_XY_SE_BS_help,na.rm=T), sd(sigma_2_sq_SE_BS_help,na.rm=T)) names(theta_bootstrap_se) <- c("alpha_0", "alpha_1", "alpha_2", "alpha_3", "sigma_1", "alpha_4", "alpha_XY", "sigma_2_sq") } return(theta_bootstrap_se) } ``` ```{r, echo=FALSE} naive_se <- function(setting = "GLM", Y = NULL, X = NULL, K = NULL, L = NULL, C = NULL) { if (!requireNamespace("survival", quietly = TRUE)) { stop("Pkg needed for this function to work. Please install it.", call. = FALSE) } if (is.null(setting)) { stop("setting has to be supplied.") } if (is.null(Y) | is.null(X) | is.null(K) | is.null(L)) { stop("Data of one or more variables are not supplied.") } if (setting == "AFT" & is.null(C)) { stop("C has to be supplied for the AFT setting.") } n <- length(Y) if (setting == "GLM") { data_help <- data.frame(Y = Y, X = X, K = K, L = L) data_help <- data_help[complete.cases(data_help), ] ######### Stage 1 ######### fit_stage_1 <- lm(data_help$Y ~ data_help$K + data_help$X + data_help$L) alpha_1_out <- summary(fit_stage_1)$coefficients[2, 1] alpha_0_SE_out <- summary(fit_stage_1)$coefficients[1, 2] alpha_1_SE_out <- summary(fit_stage_1)$coefficients[2, 2] alpha_2_SE_out <- summary(fit_stage_1)$coefficients[3, 2] alpha_3_SE_out <- summary(fit_stage_1)$coefficients[4, 2] ######### Stage 2 ######### Y_tilde <- data_help$Y - mean(data_help$Y) - alpha_1_out * (data_help$K - mean(data_help$K)) fit_stage_2 <- lm(Y_tilde ~ data_help$X) alpha_4_SE_out <- summary(fit_stage_2)$coefficients[1, 2] alpha_XY_SE_out <- summary(fit_stage_2)$coefficients[2, 2] } if (setting == "AFT") { data_help <- data.frame(Y = Y, X = X, K = K, L = L, C = C) data_help <- data_help[complete.cases(data_help), ] ######### Stage 1 ######### fit_stage_1 <- survival::survreg(survival::Surv(data_help$Y, data_help$C) ~ data_help$K + data_help$X + data_help$L, dist = "gaussian") alpha_1_out <- summary(fit_stage_1)$table[2, 1] sigma_1_out <- fit_stage_1$scale alpha_0_SE_out <- summary(fit_stage_1)$table[1, 2] alpha_1_SE_out <- summary(fit_stage_1)$table[2, 2] alpha_2_SE_out <- summary(fit_stage_1)$table[3, 2] alpha_3_SE_out <- summary(fit_stage_1)$table[4, 2] ######### Stage 2 ######### mu <- fit_stage_1$linear.predictors Y_adj <- data_help$C * data_help$Y + (1 - data_help$C) * (mu + (sigma_1_out * dnorm((data_help$Y - mu)/sigma_1_out, mean = 0, sd = 1)/ (1 - pnorm((data_help$Y - mu)/sigma_1_out, mean = 0, sd = 1)))) Y_tilde <- Y_adj - mean(Y_adj) - alpha_1_out * (data_help$K - mean(data_help$K)) fit_stage_2 <- lm(Y_tilde ~ data_help$X) alpha_4_SE_out <- summary(fit_stage_2)$coefficients[1, 2] alpha_XY_SE_out <- summary(fit_stage_2)$coefficients[2, 2] } SE_estimates <- c(alpha_0_SE_out, alpha_1_SE_out, alpha_2_SE_out, alpha_3_SE_out, NA, alpha_4_SE_out, alpha_XY_SE_out, NA) names(SE_estimates) <- c("alpha_0", "alpha_1", "alpha_2", "alpha_3", "sigma_1_sq", "alpha_4", "alpha_XY", "sigma_2_sq") return(SE_estimates) } ``` ```{r} bootstrap_se(setting = "GLM", BS_rep = 1000, Y = dat$Y, X = dat$X, K = dat$K, L = dat$L) naive_se(setting = "GLM", Y = dat$Y, X = dat$X, K = dat$K, L = dat$L) ``` Finally, the functions `ciee()` and `ciee_loop()` allow an easy integrated use of all above functions and a simultaneous computation of the estimating equations approach using either standard error computation, the traditional regression-based approaches, and the SEM method. `ciee()` fits the model in equations (1)-(3) (e.g. the model in Figure 1) and yields parameter estimates, standard error estimates, and p-values for all parameters. `ciee_loop()` provides an extension of `ciee()` and allows the input of multiple exposure variables (e.g. multiple SNPs) which are tested sequentially. In the output of `ciee_loop()`, only the coefficient estimates, standard error estimates, and p-values with respect to the direct effect $\alpha_{XY}$ are provided. ```{r, echo=FALSE} ciee <- function(setting = "GLM", estimates = c("ee", "mult_reg", "res_reg", "sem"), ee_se = c("sandwich"), BS_rep = NULL, Y = NULL, X = NULL, K = NULL, L = NULL, C = NULL) { if (is.null(setting)) { stop("setting has to be supplied.") } if (is.null(estimates)) { stop("At least one method has to be computed.") } if ((("ee" %in% estimates) & is.null(ee_se)) | (("ee" %in% estimates) & length(ee_se) > 1)) { stop("If the estimating equations approach is chosen, one approach has to be chosen for the computation of standard errors.") } if (("bootstrap" %in% estimates) & is.null(BS_rep)) { stop("For the computation of bootstrap standard errors, the number of bootstrap samples has to be chosen.") } if (is.null(Y) | is.null(X) | is.null(K) | is.null(L)) { stop("Data of one or more variables is not supplied.") } if (setting == "AFT" & is.null(C)) { stop("C has to be supplied for the AFT setting.") } if (setting == "AFT" & ("sem" %in% estimates)) { stop("The structural equations modeling approach is only implemented for the GLM setting.") } if (setting == "AFT" & ("res_reg" %in% estimates)) { stop("The regression of residuals approach is only implemented for the GLM setting.") } if (setting == "GLM") { data_help <- data.frame(Y = Y, X = X, K = K, L = L) data_help <- data_help[complete.cases(data_help), ] if ("sem" %in% estimates) { results_sem <- sem_appl(Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L) } if ("mult_reg" %in% estimates) { results_mult_reg <- mult_reg(setting = setting, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L) } if ("res_reg" %in% estimates) { results_res_reg <- res_reg(Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L) } if ("ee" %in% estimates) { point_estimates_ee <- get_estimates(setting = setting, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L) if (ee_se == "sandwich") { # Obtain estimating functions expressions estfunct <- est_funct_expr(setting = "GLM") # Obtain matrices with all first and second derivatives derivobj <- deriv_obj(setting = setting, logL1 = estfunct$logL1, logL2 = estfunct$logL2, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L, estimates = point_estimates_ee) # Obtain score and hessian matrices results_scores <- scores(derivobj) results_hessian <- hessian(derivobj) # Obtain sandwich standard error estimates of the parameters se_estimates_ee <- sandwich_se(setting = setting, scores = results_scores, hessian = results_hessian) } if (ee_se == "bootstrap") { se_estimates_ee <- bootstrap_se(setting = setting, BS_rep = BS_rep, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L) } if (ee_se == "naive") { se_estimates_ee <- naive_se(setting = setting, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L) } wald_test_stat_ee <- point_estimates_ee[1:8]/se_estimates_ee pvalues_ee <- 2 * pnorm(-abs(wald_test_stat_ee)) results_ee <- list(point_estimates = point_estimates_ee[1:8], SE_estimates = se_estimates_ee, wald_test_stat = wald_test_stat_ee, pvalues = pvalues_ee) } } if (setting == "AFT") { data_help <- data.frame(Y = Y, X = X, K = K, L = L, C = C) data_help <- data_help[complete.cases(data_help), ] if ("mult_reg" %in% estimates) { results_mult_reg <- mult_reg(setting = setting, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L, C = data_help$C) } if ("ee" %in% estimates) { point_estimates_ee <- get_estimates(setting = setting, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L, C = data_help$C) if (ee_se == "sandwich") { # Obtain estimating functions expressions estfunct <- est_funct_expr(setting = setting) # Obtain matrices with all first and second derivatives derivobj <- deriv_obj(setting = setting, logL1 = estfunct$logL1, logL2 = estfunct$logL2, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L, C = data_help$C, estimates = point_estimates_ee) # Obtain score and hessian matrices results_scores <- scores(derivobj) results_hessian <- hessian(derivobj) # Obtain sandwich standard error estimates of the parameters se_estimates_ee <- sandwich_se(setting = setting, scores = results_scores, hessian = results_hessian) } if (ee_se == "bootstrap") { se_estimates_ee <- bootstrap_se(setting = setting, BS_rep = BS_rep, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L, C = data_help$C) } if (ee_se == "naive") { se_estimates_ee <- naive_se(setting = setting, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L, C = data_help$C) } wald_test_stat_ee <- point_estimates_ee[1:8]/se_estimates_ee pvalues_ee <- 2 * pnorm(-abs(wald_test_stat_ee)) results_ee <- list(point_estimates = point_estimates_ee[1:8], SE_estimates = se_estimates_ee, wald_test_stat = wald_test_stat_ee, pvalues = pvalues_ee) } } output <- list() if ("ee" %in% estimates) { output$results_ee <- results_ee } if ("mult_reg" %in% estimates) { output$results_mult_reg <- results_mult_reg } if ("res_reg" %in% estimates) { output$results_res_reg <- results_res_reg } if ("sem" %in% estimates) { output$results_sem <- results_sem } class(output) <- "ciee" return(output) } ``` ```{r, echo=FALSE} ciee_loop <- function(setting = "GLM", estimates = c("ee", "mult_reg", "res_reg", "sem"), ee_se = c("sandwich"), BS_rep = NULL, Y = NULL, X = NULL, K = NULL, L = NULL, C = NULL) { if (is.null(setting)) { stop("setting has to be supplied.") } if (is.null(estimates)) { stop("At least one method has to be computed.") } if ((("ee" %in% estimates) & is.null(ee_se)) | (("ee" %in% estimates) & length(ee_se) > 1)) { stop("If the estimating equations approach is chosen, one approach has to be chosen for the computation of standard errors.") } if (("bootstrap" %in% estimates) & is.null(BS_rep)) { stop("For the computation of bootstrap standard errors, the number of bootstrap samples has to be chosen.") } if (is.null(Y) | is.null(X) | is.null(K) | is.null(L)) { stop("Data of one or more variables is not supplied.") } if (setting == "AFT" & is.null(C)) { stop("C has to be supplied for the AFT setting.") } if (setting == "AFT" & ("sem" %in% estimates)) { stop("The structural equations modeling approach is only implemented for the GLM setting.") } if (setting == "AFT" & ("res_reg" %in% estimates)) { stop("The regression of residuals approach is only implemented for the GLM setting.") } if ("sem" %in% estimates) { results_sem <- list(point_estimates = NULL, SE_estimates = NULL, pvalues = NULL) } if ("mult_reg" %in% estimates) { results_mult_reg <- list(point_estimates = NULL, SE_estimates = NULL, pvalues = NULL) } if ("res_reg" %in% estimates) { results_res_reg <- list(point_estimates = NULL, SE_estimates = NULL, pvalues = NULL) } if ("ee" %in% estimates) { results_ee <- list(point_estimates = NULL, SE_estimates = NULL, wald_test_stat = NULL, pvalues = NULL) } k <- dim(X)[2] for (i in 1:k) { Xi <- X[, i] if (setting == "GLM") { data_help <- data.frame(Y = Y, X = Xi, K = K, L = L) data_help <- data_help[complete.cases(data_help), ] if ("sem" %in% estimates) { sem_help <- sem_appl(Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L) results_sem$point_estimates[i] <- sem_help$point_estimates[5] results_sem$SE_estimates[i] <- sem_help$SE_estimates[5] results_sem$pvalues[i] <- sem_help$pvalues[5] names(results_sem$point_estimates)[i] <- names(results_sem$SE_estimates)[i] <- names(results_sem$pvalues)[i] <- names(X)[i] } if ("mult_reg" %in% estimates) { mult_reg_help <- mult_reg(setting = setting, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L) results_mult_reg$point_estimates[i] <- mult_reg_help$point_estimates[3] results_mult_reg$SE_estimates[i] <- mult_reg_help$SE_estimates[3] results_mult_reg$pvalues[i] <- mult_reg_help$pvalues[3] names(results_mult_reg$point_estimates)[i] <- names(results_mult_reg$SE_estimates)[i] <- names(results_mult_reg$pvalues)[i] <- names(X)[i] } if ("res_reg" %in% estimates) { res_reg_help <- res_reg(Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L) results_res_reg$point_estimates[i] <- res_reg_help$point_estimates[5] results_res_reg$SE_estimates[i] <- res_reg_help$SE_estimates[5] results_res_reg$pvalues[i] <- res_reg_help$pvalues[5] names(results_res_reg$point_estimates)[i] <- names(results_res_reg$SE_estimates)[i] <- names(results_res_reg$pvalues)[i] <- names(X)[i] } if ("ee" %in% estimates) { point_estimates_ee <- get_estimates(setting = setting, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L) if (ee_se == "sandwich") { # Obtain estimating functions expressions estfunct <- est_funct_expr(setting = "GLM") # Obtain matrices with all first and second derivatives derivobj <- deriv_obj(setting = setting, logL1 = estfunct$logL1, logL2 = estfunct$logL2, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L, estimates = point_estimates_ee) # Obtain score and hessian matrices results_scores <- scores(derivobj) results_hessian <- hessian(derivobj) # Obtain sandwich standard error estimates of the parameters se_estimates_ee <- sandwich_se(setting = setting, scores = results_scores, hessian = results_hessian) } if (ee_se == "bootstrap") { se_estimates_ee <- bootstrap_se(setting = setting, BS_rep = BS_rep, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L) } if (ee_se == "naive") { se_estimates_ee <- naive_se(setting = setting, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L) } results_ee$point_estimates[i] <- point_estimates_ee[7] results_ee$SE_estimates[i] <- se_estimates_ee[7] results_ee$wald_test_stat[i] <- point_estimates_ee[7]/ se_estimates_ee[7] results_ee$pvalues[i] <- 2 * pnorm(-abs(point_estimates_ee[7]/ se_estimates_ee[7])) names(results_ee$point_estimates)[i] <- names(results_ee$SE_estimates)[i] <- names(results_ee$wald_test_stat)[i] <- names(results_ee$pvalues)[i] <- names(X)[i] } } if (setting == "AFT") { data_help <- data.frame(Y = Y, X = Xi, K = K, L = L, C = C) data_help <- data_help[complete.cases(data_help), ] if ("mult_reg" %in% estimates) { mult_reg_help <- mult_reg(setting = setting, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L, C = data_help$C) results_mult_reg$point_estimates[i] <- mult_reg_help$point_estimates[3] results_mult_reg$SE_estimates[i] <- mult_reg_help$SE_estimates[3] results_mult_reg$pvalues[i] <- mult_reg_help$pvalues[3] names(results_mult_reg$point_estimates)[i] <- names(results_mult_reg$SE_estimates)[i] <- names(results_mult_reg$pvalues)[i] <- names(X)[i] } if ("ee" %in% estimates) { point_estimates_ee <- get_estimates(setting = setting, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L, C = data_help$C) if (ee_se == "sandwich") { # Obtain estimating functions expressions estfunct <- est_funct_expr(setting = setting) # Obtain matrices with all first and second derivatives derivobj <- deriv_obj(setting = setting, logL1 = estfunct$logL1, logL2 = estfunct$logL2, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L, C = data_help$C, estimates = point_estimates_ee) # Obtain score and hessian matrices results_scores <- scores(derivobj) results_hessian <- hessian(derivobj) # Obtain sandwich standard error estimates of the parameters se_estimates_ee <- sandwich_se(setting = setting, scores = results_scores, hessian = results_hessian) } if (ee_se == "bootstrap") { se_estimates_ee <- bootstrap_se(setting = setting, BS_rep = BS_rep, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L, C = data_help$C) } if (ee_se == "naive") { se_estimates_ee <- naive_se(setting = setting, Y = data_help$Y, X = data_help$X, K = data_help$K, L = data_help$L, C = data_help$C) } results_ee$point_estimates[i] <- point_estimates_ee[7] results_ee$SE_estimates[i] <- se_estimates_ee[7] results_ee$wald_test_stat[i] <- point_estimates_ee[7]/ se_estimates_ee[7] results_ee$pvalues[i] <- 2 * pnorm(-abs(point_estimates_ee[7]/ se_estimates_ee[7])) names(results_ee$point_estimates)[i] <- names(results_ee$SE_estimates)[i] <- names(results_ee$wald_test_stat)[i] <- names(results_ee$pvalues)[i] <- names(X)[i] } } } output <- list() if ("ee" %in% estimates) { output$results_ee <- results_ee } if ("mult_reg" %in% estimates) { output$results_mult_reg <- results_mult_reg } if ("res_reg" %in% estimates) { output$results_res_reg <- results_res_reg } if ("sem" %in% estimates) { output$results_sem <- results_sem } class(output) <- "ciee" return(output) } ``` ```{r} results_ciee <- ciee(setting = "GLM", Y = dat$Y, X = dat$X, K = dat$K, L = dat$L, estimates = c("ee", "mult_reg", "res_reg", "sem"), ee_se = "sandwich") results_ciee maf <- 0.2 n <- 1000 dat <- generate_data(n = n, maf = maf) datX <- data.frame(X = dat$X) names(datX)[1] <- "X1" for(i in 2:10){ X <- rbinom(n, size = 2, prob = maf) datX$X <- X names(datX)[i] <- paste("X", i, sep="") } results_ciee_loop <- ciee_loop(setting = "GLM", Y = dat$Y, X = datX, K = dat$K, L = dat$L) results_ciee_loop ``` Both `ciee()` and `ciee_loop()` return `ciee` objects as output, and the implemented `summary.ciee()` function can be used through the generic `summary()` to provide a reader-friendly formatted output of the results. ```{r, echo=FALSE} summary.ciee <- function(results = NULL) { if (is.null(results)) { stop("ciee output has to be supplied.") } res_out <- NULL if ("results_ee" %in% names(results)) { res_ee_out <- data.frame(point_estimates = results$results_ee$point_estimates, SE_estimates = results$results_ee$SE_estimates, wald_test_stat = results$results_ee$wald_test_stat, pvalues = results$results_ee$pvalues) rownames(res_ee_out) <- paste("CIEE", rownames(res_ee_out), sep = "_") print(paste("Results based on estimating equations.")) print(res_ee_out) res_out <- res_ee_out[,c(1,2,4)] } if ("results_mult_reg" %in% names(results)) { res_mr_out <- data.frame(point_estimates = results$results_mult_reg$point_estimates, SE_estimates = results$results_mult_reg$SE_estimates, pvalues = results$results_mult_reg$pvalues) rownames(res_mr_out) <- paste("MR", rownames(res_mr_out), sep = "_") print(paste("Results based on traditional multiple regression.")) print(res_mr_out) res_out <- rbind(res_out, res_mr_out) } if ("results_res_reg" %in% names(results)) { res_rr_out <- data.frame(point_estimates = results$results_res_reg$point_estimates, SE_estimates = results$results_res_reg$SE_estimates, pvalues = results$results_res_reg$pvalues) rownames(res_rr_out) <- paste("RR", rownames(res_rr_out), sep = "_") print(paste("Results based on traditional regression of residuals.")) print(res_rr_out) res_out <- rbind(res_out, res_rr_out) } if ("results_sem" %in% names(results)) { res_sem_out <- data.frame(point_estimates = results$results_sem$point_estimates, SE_estimates = results$results_sem$SE_estimates, pvalues = results$results_sem$pvalues) rownames(res_sem_out) <- paste("SEM", rownames(res_sem_out), sep = "_") print(paste("Results based on structural equation modeling.")) print(res_sem_out) res_out <- rbind(res_out, res_sem_out) } invisible(res_out) } ``` ```{r} summary(results_ciee) summary(results_ciee_loop) ``` ## References Bollen KA (1989). Structural equations with latent variables. New York: John Wiley & Sons. Konigorski S, Wang Y, Cigsar C, Yilmaz YE (2018). Estimating and testing direct genetic effects in directed acyclic graphs using estimating equations. Genetic Epidemiology, 42: 174-186. Rosseel Y (2012). lavaan: an R package for structural equation modeling. Journal of Statistical Software, 48(2), 1–36. Vansteelandt S, Goetgeluk S, Lutz S, et al. (2009). On the adjustment for covariates in genetic association analysis: a novel, simple principle to infer direct causal effects. Genetic Epidemiology, 33, 394-405.
/scratch/gouwar.j/cran-all/cranData/CIEE/vignettes/ciee.Rmd
#' Compositional Impact of Migration #' #' produce statistical indicators of the impact of migration on the socio-demographic #' composition of an area. Three measures can be used: ratios, percentages and #' the Duncan index of dissimilarity. The input data files are assumed to be in an #' origin-destination matrix format, with each cell representing a flow count #' between an origin and a destination area. Columns are expected to represent origins, #' and rows are expected to represent destinations. The first row and column are assumed to #' contain labels for each area. See Rodríguez-Vignoli and Rowe (2018) #' for technical details. #' #' @param ... 2 or more data frames, each containing an origin-destination migration matrix by #' population attribute (i.e. age, sex, education, ethnicity, etc.). #' Columns are expected to represent origins, #' and rows are expected to represent destionations. The first row and column are assumed to #' contain labels for each area. #' #' @param calculation a character, indicating the migration impact indicator selected to measure the socio-demographic #' composition of an area. Users can type one of three options: #' "ratio", "percentage" or "duncan". #' #' @param numerator a number, indicating the index number of the data frame to be used as #' the numerator for the calculation. Type 1 to use the first data frame included in the function. #' Type 2 to use the second data frame included in the function, and so on. #' #' @param denominator a number, indicating the index number of the data frame to be used as #' the denominator for the calculation. Type 1 to use the first data frame included in the function. #' Type 2 to use the second data frame included in the function, and so on. #' Note the numerator data frame must differ from the denominator data frame. #' #' @param DuncanAll, a logical argument. If calculation = "Duncan", this logical argument must be specified. #' The Duncan index measures the dissimilarity in the spatial #' distribution of a chosen group (first data frame in the function) against a reference category #' as specified by the "DuncanAll" argument. #' If TRUE, the reference category is the sum of all data frames, #' except for the first data frame included in the function (i.e. chosen group). #' If FALSE, a specific data frame must be specified to be the reference group. See Duncan and Duncan (1955) #' for details on the Duncan index, and Rodríguez-Vignoli and Rowe (2017a, b) for an empirical application #' of the CIM using the Duncan index. #' #' @param rest, a logical argument. If calculation = "Duncan", this argument must be specified. #' It enables a special calculation of the CIM, for a particular area (e.g. the Greater London Metropolitan Area), and #' the rest of spatial units comprising a country. To correctly compute the CMI, these spatial units #' need to be amalgamated and included as a single column/row in the matrix - labelled "Rest of the country" #' (e.g. Rest of the UK). If TRUE, the column/row of the "Rest of the country" is considered for the calculation #' and is excluded from the denominator of the duncan index. #' If FALSE, the "Rest of the country" column/row is included in the denominator, producing the wrong results. #' #' @return an object containing: #' #' @return for the "ratio" and "percentage" calculation options: #' @return num_results: a data frame containing nine area-level indicators: the Factual Value (FV), Counterfactual Value (CFV), #' Compositional Impact of Migration (CIM), Compositional Impact of Migration Percentage Change (CIM_PC), #' Diagonal Cell Indicator (DIAG), Compositional Impact of Migration for Inflows (CIM_I), #' Compositional Impact of Migration for Outflows (CIM_O), CIM_I as a percentage of CMI (CIM_I_PC), and #' CIM_O as a percentage of CMI (CIM_O_PC) #' #' @return for the "duncan" calculation option: #' #' @return duncan_results: a data frame, containing #' the Factual Value of the Area-Specific Share (ASFVShare_cg), and the Counterfactual Value of the Area-Specific Share (ASCFVShare_cg) for the chosen group; #' the Factual Value of the Area-Specific Share (ASFVShare_ref) and the Counterfactual Value of the Area-Specific Share (ASCFVShare_ref) for the reference group; #' the Area-Specific Share Factual Value Difference between the ASFVShare_cg and ASFVShare_ref (ASShareFV_diff); #' and the Area-Specific Share Counterfactual Value Difference between the ASCFVShare_cg and ASCFVShare_ref (ASShareCFV_diff). #' The chosen group corresponds to the first data frame in the function. See above the argument "DuncanAll" #' to specify the reference category. #' #' @return duncan_index: a numeric value, indicating the Duncan Index of dissimilarity for the chosen group. #' #' @examples #' ## Read in the two data.frames included in the package #' m <- male #' f <- female #' #' ## Run the function using "ratio" calculation #' CIM.ratio <- CIM(m, f, calculation = "ratio", numerator = 1, denominator = 2) #' ## Print the resulted data.frame #' CIM.ratio #' #' ## Run the function using "percentage" calculation #' CIM.percentage <- CIM(m, f, calculation = "percentage", numerator = 1, denominator = 2) #' ## See the resulted data.frame #' CIM.percentage #' #' ## For the Duncan index, we compute impact of internal migration on the spatial pattern of #' ## residential age segregation of people age 65 and over in the #' ## local authority districts of Greater London using 2011 census data. #' ## Chosen group: people aged 65 and over. #' ## Reference category: the rest of age groups. #' ## For this example, this group is people aged pop1-14, 15-29, 30-14 and 45-64). #' CIM.duncan <- CIM(pop65over, pop1_14, pop15_29, pop30_44, pop45_64, #' calculation = "duncan", numerator = 1, DuncanAll= TRUE) #' CIM.duncan$duncan_results #' CIM.duncan$duncan_index #' #' #' @references #' #' Duncan, O.D. and Duncan, B., 1955. A methodological analysis of segregation indexes. #' American sociological review, 20(2), pp.210-217. #' #' Rodríguez-Vignoli, J.R. and Rowe, F., 2017a. ¿Contribuye la migración interna a #' reducir la segregación residencial?: el caso de Santiago de Chile 1977-2002. #' Revista Latinoamericana de Población, (21), pp.7-46. #' #' Rodríguez-Vignoli, J.R. and Rowe, F., 2017b. The Changing Impacts of Internal Migration #' on Residential Socio-Economic Segregation in the Greater Santiago. 28th International #' Population Conference of the International Union for the Scientific Study of Population (IUSSP), #' Cape Town, South Africa. #' #' Rodríguez-Vignoli, J. and Rowe, F., 2018. How is internal migration reshaping #' metropolitan populations in Latin America? A new method and new evidence. #' Population studies, 72(2), pp.253-273. doi.org/10.1080/00324728.2017.1416155 #' #' #' @importFrom utils head #' #' @export CIM <- function(..., calculation, numerator, denominator, DuncanAll= TRUE, rest = TRUE) { # Put all the data.frames in a list args <- list(...) # Create an empty list which will hold the new calculated data.frames b <- list() # Create a counter count_tables <- 1 for (a in args) { a <- cbind(a, totalRow= rowSums(a)) a <- rbind(a, totalCol = colSums(a)) b[[count_tables]] <- a count_tables = count_tables+1 } if(calculation == "ratio"){ # Calculate the ratio between the specified numerator and denominator c <- b[[numerator]]/b[[denominator]] *100 # Transpose the last row c <- cbind(c, t(c[nrow(c),])) # Rename the last two columns colnames(c)[ncol(c)-1] <- "FV" colnames(c)[ncol(c)] <- "CFV" # Calculate the CIM index (FV-CFV) c$CIM <- c$FV - c$CFV # Calculate the CIM inflows index (FV-MII[ii]) for (i in 1:nrow(c)) { c$CIM_I[i] <- c$FV[i] - c[i,i] } # Calculate the CIM outflows index (MII[ii]- CFV) for (i in 1:nrow(c)) { c$CIM_O[i] <- c[i,i] - c$CFV[i] } # Extract the diagonal of the dataframe # Extract the diagonal of the dataframe for (i in 1:nrow(c)) { c$DIAG[i] <- c[i,i] } # Calculate Percentage change CIM index ([FV-CFV] / CFV) c$CIM_PC <- c$CIM / c$CFV *100 # Calculate percentage of CMI_I over CMI c$CIM_I_PC <- c$CIM_I / c$CIM *100 # Calculate percentage of CMI_O over CMI c$CIM_O_PC <- c$CIM_O / c$CIM *100 # replace NA values with zeroes c[is.na(c)] <- 0 # Return the columns specified as the result of this option of the function res <- list(num_results = c[c("FV", "CFV", "CIM", "CIM_PC","DIAG", "CIM_I", "CIM_O", "CIM_I_PC", "CIM_O_PC")]) return(res) } else if (calculation == "percentage") { # Sum all the data.frames m_sum <- Reduce('+', b) # Calculate the percentage of the specified numerator c <- b[[numerator]]/m_sum *100 # Transpose the last row c <- cbind(c, t(c[nrow(c),])) # Rename the last two columns colnames(c)[ncol(c)-1] <- "FV" colnames(c)[ncol(c)] <- "CFV" # Calculate the CIM index (FV-CFV) c$CIM <- c$FV - c$CFV # Calculate the CIM inflows index (FV-MII[ii]) for (i in 1:nrow(c)) { c$CIM_I[i] <- c$FV[i] - c[i,i] } # Calculate the CIM outflows index (MII[ii]- CFV) for (i in 1:nrow(c)) { c$CIM_O[i] <- c[i,i] - c$CFV[i] } # Calculate Percentage change CIM index ([FV-CFV] / CFV) c$CIM_PC <- c$CIM / c$CFV *100 # Return the columns specified as the result of this option of the function res <- list(num_results = c[c("FV", "CFV", "CIM", "CIM_I", "CIM_O", "CIM_PC")]) return(res) } else if (calculation == "duncan"){ if (DuncanAll){ # Sum all the data.frames except the specified numerator sum_matr <- Reduce('+', b[-c(numerator)]) # Transpose the last row sum_matr <- cbind(sum_matr, t(sum_matr[nrow(sum_matr),])) c <- b[[numerator]] # Transpose the last row c <- cbind(c, t(c[nrow(c),])) if (rest) { # Calculate Factual Value and Counterfactual Value for numerator # Ignore the last row c$ASFVShare_cg <- c$totalRow / sum(head(c$totalRow, -2)) c$ASCFVShare_cg <- c$totalCol / sum(head(c$totalCol, -2)) # Calculate Factual Value and Counterfactual Value for the rest of the data.frames # Ignore the last row sum_matr$ASFVShare_ref <- sum_matr$totalRow / sum(head(sum_matr$totalRow, -2)) sum_matr$ASCFVShare_ref <- sum_matr$totalCol / sum(head(sum_matr$totalCol, -2)) # Calculate Duncan FVs and CFVs for each row c$ASShareFV_diff <- abs(c$ASFVShare_cg - sum_matr$ASFVShare_ref) c$ASShareCFV_diff <- abs(c$ASCFVShare_cg - sum_matr$ASCFVShare_ref) # Sum Duncan FVs and CFVs sumDuncanFV <- sum(head(c$ASShareFV_diff, -2)) sumDuncanCFV <- sum(head(c$ASShareCFV_diff, -2)) # Duncan Index DuncanIndex <- (sumDuncanFV/2) - (sumDuncanCFV/2) # remove the rest of the country row which is always the second row from the bottom of the dataframe c <- c[-c(nrow(c)-1),] sum_matr <- sum_matr[-c(nrow(sum_matr)-1),] # Return the columns specified as the result of this option of the function res <- list(duncan_results = cbind(c[c("ASFVShare_cg", "ASCFVShare_cg")], sum_matr[c("ASFVShare_ref", "ASCFVShare_ref")], c[c("ASShareFV_diff", "ASShareCFV_diff")]), duncan_index = DuncanIndex) return(res) } # Calculate Factual Value and Counterfactual Value for numerator # Ignore the last row c$ASFVShare_cg <- c$totalRow / sum(c$totalRow[1:nrow(c)-1]) c$ASCFVShare_cg <- c$totalCol / sum(c$totalCol[1:nrow(c)-1]) # Calculate Factual Value and Counterfactual Value for the rest of the data.frames # Ignore the last row sum_matr$ASFVShare_ref <- sum_matr$totalRow / sum(sum_matr$totalRow[1:nrow(sum_matr)-1]) sum_matr$ASCFVShare_ref <- sum_matr$totalCol / sum(sum_matr$totalCol[1:nrow(sum_matr)-1]) # Calculate Duncan FVs and CFVs for each row c$ASShareFV_diff <- abs(c$ASFVShare_cg - sum_matr$ASFVShare_ref) c$ASShareCFV_diff <- abs(c$ASCFVShare_cg - sum_matr$ASCFVShare_ref) # Sum Duncan FVs and CFVs sumDuncanFV <- sum(c$ASShareFV_diff) sumDuncanCFV <- sum(c$ASShareCFV_diff) # Duncan Index DuncanIndex <- (sumDuncanFV/2) - (sumDuncanCFV/2) # remove the rest of the country row which is always the second row from the bottom of the dataframe c <- c[-c(nrow(c)-1),] sum_matr <- sum_matr[-c(nrow(sum_matr)-1),] # Return the columns specified as the result of this option of the function res <- list(duncan_results = cbind(c[c("ASFVShare_cg", "ASCFVShare_cg")], sum_matr[c("ASFVShare_ref", "ASCFVShare_ref")], c[c("ASShareFV_diff", "ASShareCFV_diff")]), duncan_index = DuncanIndex) return(res) } if (rest){ ratios <- list() i <- 1 for (a in b) { a <- cbind(a, t(a[nrow(a),])) # ignore the last row a$ASFVShare <- a$totalRow / sum(head(a$totalRow, -2)) a$ASCFVShare <- a$totalCol / sum(head(a$totalCol, -2)) ratios[[i]] <- a i <- i+1 } c <- ratios[[numerator]] d <- ratios[[denominator]] # Calculate Duncan FVs and CFVs for each row c$ASShareFV_diff <- abs(c$ASFVShare - d$ASFVShare) c$ASShareCFV_diff <- abs(c$ASCFVShare - d$ASCFVShare) # Sum Duncan FVs and CFVs sumDuncanFV <- sum(head(c$ASShareFV_diff, -2)) sumDuncanCFV <- sum(head(c$ASShareCFV_diff, -2)) # Duncan Index DuncanIndex <- (sumDuncanFV/2) - (sumDuncanCFV/2) # rename columns to reflect which is the chisen group and which is the reference names(c)[names(c) == "ASFVShare"] <- "ASFVShare_cg" names(c)[names(c) == "ASCFVShare"] <- "ASCFVShare_cg" names(d)[names(d) == "ASFVShare"] <- "ASFVShare_ref" names(d)[names(d) == "ASCFVShare"] <- "ASCFVShare_ref" # remove the rest of the country row which is always the second row from the bottom of the dataframe c <- c[-c(nrow(c)-1),] d <- d[-c(nrow(d)-1),] # Return the columns specified as the result of this option of the function res <- list(duncan_results = cbind(c[c("ASFVShare_cg", "ASCFVShare_cg")], d[c("ASFVShare_ref", "ASCFVShare_ref")], c[c("ASShareFV_diff", "ASShareCFV_diff")]), duncan_index = DuncanIndex) return(res) } ratios <- list() i <- 1 for (a in b) { a <- cbind(a, t(a[nrow(a),])) # ignore the last row a$ASFVShare <- a$totalRow / sum(a$totalRow[1:nrow(a)-1]) a$ASCFVShare <- a$totalCol / sum(a$totalCol[1:nrow(a)-1]) ratios[[i]] <- a i <- i+1 } c <- ratios[[numerator]] d <- ratios[[denominator]] # Calculate Duncan FVs and CFVs for each row c$ASShareFV_diff <- abs(c$ASFVShare - d$ASFVShare) c$ASShareCFV_diff <- abs(c$ASCFVShare - d$ASCFVShare) # Sum Duncan FVs and CFVs sumDuncanFV <- sum(c$ASShareFV_diff) sumDuncanCFV <- sum(c$ASShareCFV_diff) # Duncan Index DuncanIndex <- (sumDuncanFV/2) - (sumDuncanCFV/2) # rename columns to reflect which is the chisen group and which is the reference names(c)[names(c) == "ASFVShare"] <- "ASFVShare_cg" names(c)[names(c) == "ASCFVShare"] <- "ASCFVShare_cg" names(d)[names(d) == "ASFVShare"] <- "ASFVShare_ref" names(d)[names(d) == "ASCFVShare"] <- "ASCFVShare_ref" # remove the rest of the country row which is always the second row from the bottom of the dataframe c <- c[-c(nrow(c)-1),] d <- d[-c(nrow(d)-1),] # Return the columns specified as the result of this option of the function res <- list(duncan_results = cbind(c[c("ASFVShare_cg", "ASCFVShare_cg")], d[c("ASFVShare_ref", "ASCFVShare_ref")], c[c("ASShareFV_diff", "ASShareCFV_diff")]), duncan_index = DuncanIndex) return(res) } }
/scratch/gouwar.j/cran-all/cranData/CIM/R/R_function.R
#' OD matrix, male, 2008-2013. #' #' 4x4 origin-destination migration data matrix, male, 2008-2013, Chile. #' #' @format A data frame of 4 rows by 4 columns containing a 3x3 #' origin-destination migration data matrix for males, including counts for #' the non-migrant population in the diagonal. The first row and column #' correspond to the area names. Rows correspond to destinations and columns represent #' origins. #' \describe{ #' \item{Greater.Santiago}{Population, male} #' \item{Rest.of.the.Metropolitan.region}{Population, male} #' \item{Rest.of.the.country}{Population, male} #' } #' @source \url{https://www.tandfonline.com/doi/suppl/10.1080/00324728.2017.1416155?scroll=top} "male" #' OD matrix, female, 2008-2013. #' #' 4x4 origin-destination migration data matrix, female, 2008-2013, Chile. #' #' @format A data frame of 4 rows by 4 columns containing a 3x3 #' origin-destination migration data matrix for females, including counts for #' the non-migrant population in the diagonal. The first row and column #' correspond to the area names. Rows correspond to destinations and columns represent #' origins. #' \describe{ #' \item{Greater.Santiago}{Population, female} #' \item{Rest.of.the.Metropolitan.region}{Population, female} #' \item{Rest.of.the.country}{Population, female} #' } #' @source \url{https://www.tandfonline.com/doi/suppl/10.1080/00324728.2017.1416155?scroll=top} "female" #' OD matrix, people aged 1-14, 2010-2011. #' #' 34x34 origin-destination migration data matrix, population aged 1-14, 2010-2011, UK. #' #' @format A data frame of 34 rows by 34 columns containing a 33x33 #' origin-destination migration data matrix for people aged 1-14, including counts for #' the non-migrant population in the diagonal. The first row and column #' correspond to the area names. Rows correspond to destinations and columns represent #' origins. #' \describe{ #' \item{Barking and Dagenham}{Population, aged 1 to 14} #' \item{Barnet}{Population, aged 1 to 14} #' \item{Bexley}{Population, aged 1 to 14} #' \item{Brent}{Population, aged 1 to 14} #' \item{Bromley}{Population, aged 1 to 14} #' \item{Camden}{Population, aged 1 to 14} #' \item{Croydon}{Population, aged 1 to 14} #' \item{Ealing}{Population, aged 1 to 14} #' \item{Enfield}{Population, aged 1 to 14} #' \item{Greenwich}{Population, aged 1 to 14} #' \item{Hackney}{Population, aged 1 to 14} #' \item{Hammersmith and Fulham}{Population, aged 1 to 14} #' \item{Haringey}{Population, aged 1 to 14} #' \item{Harrow}{Population, aged 1 to 14} #' \item{Havering}{Population, aged 1 to 14} #' \item{Hillingdon}{Population, aged 1 to 14} #' \item{Hounslow}{Population, aged 1 to 14} #' \item{Islington}{Population, aged 1 to 14} #' \item{Kensington and Chelsea}{Population, aged 1 to 14} #' \item{Kingston upon Thames}{Population, aged 1 to 14} #' \item{Lambeth}{Population, aged 1 to 14} #' \item{Lewisham}{Population, aged 1 to 14} #' \item{Merton}{Population, aged 1 to 14} #' \item{Newham}{Population, aged 1 to 14} #' \item{Redbridge}{Population, aged 1 to 14} #' \item{Richmond upon Thames}{Population, aged 1 to 14} #' \item{Southwark}{Population, aged 1 to 14} #' \item{Sutton}{Population, aged 1 to 14} #' \item{Tower Hamlets}{Population, aged 1 to 14} #' \item{Waltham Forest}{Population, aged 1 to 14} #' \item{Wandsworth}{Population, aged 1 to 14} #' \item{City of London-Westminster}{Population, aged 1 to 14} #' \item{Rest of the UK}{Population, aged 1 to 14} #' } #' @source {2011 Census for England and Wales} "pop1_14" #' OD matrix, people aged 15-29, 2010-2011. #' #' 34x34 origin-destination migration data matrix, population aged 15-29, 2010-2011, UK. #' #' @format A data frame of 34 rows by 34 columns containing a 33x33 #' origin-destination migration data matrix for people aged 15-29, including counts for #' the non-migrant population in the diagonal. The first row and column #' correspond to the area names. Rows correspond to destinations and columns represent #' origins. #' \describe{ #' \item{Barking and Dagenham}{Population, aged 15 to 29} #' \item{Barnet}{Population, aged 15 to 29} #' \item{Bexley}{Population, aged 15 to 29} #' \item{Brent}{Population, aged 15 to 29} #' \item{Bromley}{Population, aged 15 to 29} #' \item{Camden}{Population, aged 15 to 29} #' \item{Croydon}{Population, aged 15 to 29} #' \item{Ealing}{Population, aged 15 to 29} #' \item{Enfield}{Population, aged 15 to 29} #' \item{Greenwich}{Population, aged 15 to 29} #' \item{Hackney}{Population, aged 15 to 29} #' \item{Hammersmith and Fulham}{Population, aged 15 to 29} #' \item{Haringey}{Population, aged 15 to 29} #' \item{Harrow}{Population, aged 15 to 29} #' \item{Havering}{Population, aged 15 to 29} #' \item{Hillingdon}{Population, aged 15 to 29} #' \item{Hounslow}{Population, aged 15 to 29} #' \item{Islington}{Population, aged 15 to 29} #' \item{Kensington and Chelsea}{Population, aged 15 to 29} #' \item{Kingston upon Thames}{Population, aged 15 to 29} #' \item{Lambeth}{Population, aged 15 to 29} #' \item{Lewisham}{Population, aged 15 to 29} #' \item{Merton}{Population, aged 15 to 29} #' \item{Newham}{Population, aged 15 to 29} #' \item{Redbridge}{Population, aged 15 to 29} #' \item{Richmond upon Thames}{Population, aged 15 to 29} #' \item{Southwark}{Population, aged 15 to 29} #' \item{Sutton}{Population, aged 15 to 29} #' \item{Tower Hamlets}{Population, aged 15 to 29} #' \item{Waltham Forest}{Population, aged 15 to 29} #' \item{Wandsworth}{Population, aged 15 to 29} #' \item{City of London-Westminster}{Population, aged 15 to 29} #' \item{Rest of the UK}{Population, aged 15 to 29} #' } #' @source {2011 Census for England and Wales} "pop15_29" #' OD matrix, people aged 30-34, 2010-2011. #' #' 34x34 origin-destination migration data matrix, population aged 30-34, 2010-2011, UK. #' #' @format A data frame of 34 rows by 34 columns containing a 33x33 #' origin-destination migration data matrix for people aged 30-34, including counts for #' the non-migrant population in the diagonal. The first row and column #' correspond to the area names. Rows correspond to destinations and columns represent #' origins. #' \describe{ #' \item{Barking and Dagenham}{Population, aged 30 to 44} #' \item{Barnet}{Population, aged 30 to 44} #' \item{Bexley}{Population, aged 30 to 44} #' \item{Brent}{Population, aged 30 to 44} #' \item{Bromley}{Population, aged 30 to 44} #' \item{Camden}{Population, aged 30 to 44} #' \item{Croydon}{Population, aged 30 to 44} #' \item{Ealing}{Population, aged 30 to 44} #' \item{Enfield}{Population, aged 30 to 44} #' \item{Greenwich}{Population, aged 30 to 44} #' \item{Hackney}{Population, aged 30 to 44} #' \item{Hammersmith and Fulham}{Population, aged 30 to 44} #' \item{Haringey}{Population, aged 30 to 44} #' \item{Harrow}{Population, aged 30 to 44} #' \item{Havering}{Population, aged 30 to 44} #' \item{Hillingdon}{Population, aged 30 to 44} #' \item{Hounslow}{Population, aged 30 to 44} #' \item{Islington}{Population, aged 30 to 44} #' \item{Kensington and Chelsea}{Population, aged 30 to 44} #' \item{Kingston upon Thames}{Population, aged 30 to 44} #' \item{Lambeth}{Population, aged 30 to 44} #' \item{Lewisham}{Population, aged 30 to 44} #' \item{Merton}{Population, aged 30 to 44} #' \item{Newham}{Population, aged 30 to 44} #' \item{Redbridge}{Population, aged 30 to 44} #' \item{Richmond upon Thames}{Population, aged 30 to 44} #' \item{Southwark}{Population, aged 30 to 44} #' \item{Sutton}{Population, aged 30 to 44} #' \item{Tower Hamlets}{Population, aged 30 to 44} #' \item{Waltham Forest}{Population, aged 30 to 44} #' \item{Wandsworth}{Population, aged 30 to 44} #' \item{City of London-Westminster}{Population, aged 30 to 44} #' \item{Rest of the UK}{Population, aged 30 to 44} #' } #' @source {2011 Census for England and Wales} "pop30_44" #' OD matrix, people aged 45-64, 2010-2011. #' #' 34x34 origin-destination migration data matrix, population aged 45-64, 2010-2011, UK. #' #' @format A data frame of 34 rows by 34 columns containing a 33x33 #' origin-destination migration data matrix for people aged 45-64, including counts for #' the non-migrant population in the diagonal. The first row and column #' correspond to the area names. Rows correspond to destinations and columns represent #' origins. #' \describe{ #' \item{Barking and Dagenham}{Population, aged 45 to 64} #' \item{Barnet}{Population, aged 45 to 64} #' \item{Bexley}{Population, aged 45 to 64} #' \item{Brent}{Population, aged 45 to 64} #' \item{Bromley}{Population, aged 45 to 64} #' \item{Camden}{Population, aged 45 to 64} #' \item{Croydon}{Population, aged 45 to 64} #' \item{Ealing}{Population, aged 45 to 64} #' \item{Enfield}{Population, aged 45 to 64} #' \item{Greenwich}{Population, aged 45 to 64} #' \item{Hackney}{Population, aged 45 to 64} #' \item{Hammersmith and Fulham}{Population, aged 45 to 64} #' \item{Haringey}{Population, aged 45 to 64} #' \item{Harrow}{Population, aged 45 to 64} #' \item{Havering}{Population, aged 45 to 64} #' \item{Hillingdon}{Population, aged 45 to 64} #' \item{Hounslow}{Population, aged 45 to 64} #' \item{Islington}{Population, aged 45 to 64} #' \item{Kensington and Chelsea}{Population, aged 45 to 64} #' \item{Kingston upon Thames}{Population, aged 45 to 64} #' \item{Lambeth}{Population, aged 45 to 64} #' \item{Lewisham}{Population, aged 45 to 64} #' \item{Merton}{Population, aged 45 to 64} #' \item{Newham}{Population, aged 45 to 64} #' \item{Redbridge}{Population, aged 45 to 64} #' \item{Richmond upon Thames}{Population, aged 45 to 64} #' \item{Southwark}{Population, aged 45 to 64} #' \item{Sutton}{Population, aged 45 to 64} #' \item{Tower Hamlets}{Population, aged 45 to 64} #' \item{Waltham Forest}{Population, aged 45 to 64} #' \item{Wandsworth}{Population, aged 45 to 64} #' \item{City of London-Westminster}{Population, aged 45 to 64} #' \item{Rest of the UK}{Population, aged 45 to 64} #' } #' @source {2011 Census for England and Wales} "pop45_64" #' OD matrix, people aged 65+, 2010-2011. #' #' 34x34 origin-destination migration data matrix, population aged 65+, 2010-2011, UK.. #' #' @format A data frame of 34 rows by 34 columns containing a 33x33 #' origin-destination migration data matrix for people aged 65+, including counts for #' the non-migrant population in the diagonal. The first row and column #' correspond to the area names. Rows correspond to destinations and columns represent #' origins. #' \describe{ #' \item{Barking and Dagenham}{Population, aged 65 plus} #' \item{Barnet}{Population, aged 65 plus} #' \item{Bexley}{Population, aged 65 plus} #' \item{Brent}{Population, aged 65 plus} #' \item{Bromley}{Population, aged 65 plus} #' \item{Camden}{Population, aged 65 plus} #' \item{Croydon}{Population, aged 65 plus} #' \item{Ealing}{Population, aged 65 plus} #' \item{Enfield}{Population, aged 65 plus} #' \item{Greenwich}{Population, aged 65 plus} #' \item{Hackney}{Population, aged 65 plus} #' \item{Hammersmith and Fulham}{Population, aged 65 plus} #' \item{Haringey}{Population, aged 65 plus} #' \item{Harrow}{Population, aged 65 plus} #' \item{Havering}{Population, aged 65 plus} #' \item{Hillingdon}{Population, aged 65 plus} #' \item{Hounslow}{Population, aged 65 plus} #' \item{Islington}{Population, aged 65 plus} #' \item{Kensington and Chelsea}{Population, aged 65 plus} #' \item{Kingston upon Thames}{Population, aged 65 plus} #' \item{Lambeth}{Population, aged 65 plus} #' \item{Lewisham}{Population, aged 65 plus} #' \item{Merton}{Population, aged 65 plus} #' \item{Newham}{Population, aged 65 plus} #' \item{Redbridge}{Population, aged 65 plus} #' \item{Richmond upon Thames}{Population, aged 65 plus} #' \item{Southwark}{Population, aged 65 plus} #' \item{Sutton}{Population, aged 65 plus} #' \item{Tower Hamlets}{Population, aged 65 plus} #' \item{Waltham Forest}{Population, aged 65 plus} #' \item{Wandsworth}{Population, aged 65 plus} #' \item{City of London-Westminster}{Population, aged 65 plus} #' \item{Rest of the UK}{Population, aged 65 plus} #' } #' @source {2011 Census, England and Wales} "pop65over"
/scratch/gouwar.j/cran-all/cranData/CIM/R/data.R
#' Causal inference with multiple treatments using observational data #' #' The function \code{ce_estimate} implements the 6 #' different methods for causal inference with #' multiple treatments using observational data. #' #' @param y A numeric vector (0, 1) representing a binary outcome. #' @param x A dataframe, including all the covariates but not treatments. #' @param w A numeric vector representing the treatment groups. #' @param method A character string. Users can selected from the #' following methods including \code{"RA"}, \code{"VM"}, \code{"BART"}, #' \code{"TMLE"}, \code{"IPTW-Multinomial"}, \code{"IPTW-GBM"}, #' \code{"IPTW-SL"}, \code{"RAMS-Multinomial"}, \code{"RAMS-GBM"}, #' \code{"RAMS-SL"}. #' @param formula A \code{\link[stats]{formula}} object representing #' the variables used for the analysis. #' The default is to use all terms specified in \code{x}. #' @param discard A logical indicating whether to use the discarding rules #' for the BART based methods. The default is \code{FALSE}. #' @param estimand A character string representing the type of causal estimand. #' Only \code{"ATT"} or \code{"ATE"} is allowed. #' When the \code{estimand = "ATT"}, users also need to specify #' the reference treatment group by setting the \code{reference_trt} argument. #' @param trim_perc A 2-vector numeric value indicating the percentile #' at which the inverse probability of treatment weights should be trimmed. #' The default is \code{NULL}. #' @param sl_library A character vector of prediction algorithms. #' A list of functions included in the SuperLearner package #' can be found with \code{\link[SuperLearner:listWrappers]{listWrappers}}. #' @param reference_trt A numeric value indicating reference #' treatment group for ATT effect. #' @param boot A logical indicating whether or not to use nonparametric #' bootstrap to calculate the 95\% confidence intervals of the causal #' effect estimates. The default is \code{FALSE}. #' @param verbose_boot A logical value indicating whether to #' print the progress of nonparametric bootstrap. #' The default is \code{TRUE}. #' @param nboots A numeric value representing the number of bootstrap samples. #' @param ndpost A numeric value indicating the number of posterior draws #' for the Bayesian methods (\code{"BART"} and \code{"RA"}). #' @param caliper A numeric value denoting the caliper which should be used #' when matching (\code{method = "VM"}) on the logit of GPS within each cluster #' formed by K-means clustering. #' The caliper is in standardized units. For example, \code{caliper = 0.25} #' means that all matches greater than 0.25 standard deviations of the #' logit of GPS are dropped. The default value is 0.25. #' @param n_cluster A numeric value denoting the number of clusters to form #' using K means clustering on the logit of GPS when \code{method = "VM"}. #' The default value is 5. #' @param ... Other parameters that can be passed through to functions. #' #' @return A summary of the effect estimates can be obtained #' with \code{summary} function. For VM, the output contains the number #' of matched individuals. For BART and \code{discard = TRUE}, #' the output contains number of discarded individuals. For IPTW related #' method and \code{boot = FALSE}, the weight distributions can be #' visualized using \code{plot} function. For BART and RA, the output #' contains a list of the posterior samples of causal estimands. #' @import SuperLearner #' @importFrom stringr str_sub #' @references #' #' Hu, L., Gu, C., Lopez, M., Ji, J., & Wisnivesky, J. (2020). #' Estimation of causal effects of multiple treatments in #' observational studies with a binary outcome. #' \emph{Statistical Methods in Medical Research}, \strong{29}(11), 3218–3234. #' #' Hu, L., Gu, C. #' Estimation of causal effects of multiple treatments in healthcare #' database studies with rare outcomes. #' \emph{Health Service Outcomes Research Method} \strong{21}, 287–308 (2021). #' #' Sparapani R, Spanbauer C, McCulloch R #' Nonparametric Machine Learning and Efficient Computation #' with Bayesian Additive Regression Trees: The BART R Package. #' \emph{Journal of Statistical Software}, \strong{97}(1), 1-66. #' #' Hadley Wickham, Romain François, Lionel Henry and Kirill Müller (2021). #' \emph{dplyr: A Grammar of Data Manipulation}. #' R package version 1.0.7. #' URL: \url{https://CRAN.R-project.org/package=dplyr} #' #' Venables, W. N. & Ripley, B. D. (2002) #' \emph{Modern Applied Statistics with S}. #' Fourth Edition. Springer, New York. ISBN 0-387-95457-0 #' #' Matthew Cefalu, Greg Ridgeway, Dan McCaffrey, Andrew Morral, #' Beth Ann Griffin and Lane Burgette (2021). #' \emph{twang: Toolkit for Weighting and Analysis of Nonequivalent Groups}. #' R package version 2.5. #' URL:\url{https://CRAN.R-project.org/package=twang} #' #' Noah Greifer (2021). #' \emph{WeightIt: Weighting for Covariate Balance in Observational Studies}. #' R package version 0.12.0. #' URL:\url{https://CRAN.R-project.org/package=WeightIt} #' #' Hadley Wickham (2019). #' \emph{stringr: Simple, Consistent Wrappers for Common String Operations}. #' R package version 1.4.0. #' URL:\url{https://CRAN.R-project.org/package=stringr} #' #' Andrew Gelman and Yu-Sung Su (2020). #' \emph{arm: Data Analysis Using Regression and #' Multilevel/Hierarchical Models}. #' R package version 1.11-2. #' URL:\url{https://CRAN.R-project.org/package=arm} #' #' Wood, S.N. (2011) #' Fast stable restricted maximum likelihood and marginal likelihood #' estimation of semiparametric generalized linear models. #' \emph{Journal of the Royal Statistical Society (B)} \strong{73}(1):3-36 #' #' Eric Polley, Erin LeDell, Chris Kennedy and Mark van der Laan (2021). #' \emph{SuperLearner: Super Learner Prediction}. #' R package version 2.0-28. #' URL:\url{https://CRAN.R-project.org/package=SuperLearner} #' #' Susan Gruber, Mark J. van der Laan (2012). #' tmle: An R Package for Targeted Maximum Likelihood Estimation. #' \emph{Journal of Statistical Software}, #' \strong{51}(13), 1-35. #' #' Jasjeet S. Sekhon (2011). #' Multivariate and Propensity Score Matching Software with #' Automated Balance Optimization: The Matching Package for R. #' \emph{Journal of Statistical Software}, \strong{42}(7), 1-52 #' #' H. Wickham. #' \emph{ggplot2: Elegant Graphics for Data Analysis}. #' Springer-Verlag New York, 2016. #' #' Claus O. Wilke (2020). #' \emph{cowplot: Streamlined Plot Theme and Plot Annotations for 'ggplot2'}. #' R package version 1.1.1. #' URL:\url{https://CRAN.R-project.org/package=cowplot} #' #' Elio Campitelli (2021). #' \emph{metR: Tools for Easier Analysis of Meteorological Fields}. #' R package version 0.11.0. #' URL:\url{https://github.com/eliocamp/metR} #' #' Hadley Wickham (2021). #' \emph{tidyr: Tidy Messy Data}. R package version 1.1.4. #' \emph{https://CRAN.R-project.org/package=tidyr} #' #' Microsoft Corporation and Steve Weston (2020). #' \emph{doParallel: Foreach Parallel Adaptor for the 'parallel' Package}. #' R package version 1.0.16. #' URL:\url{https://CRAN.R-project.org/package=doParallel} #' #' Microsoft and Steve Weston (2020). #' \emph{foreach: Provides Foreach Looping Construct. R package version 1.5.1}. #' URL:\url{https://CRAN.R-project.org/package=foreach} #' @export #' #' @examples #' lp_w_all <- #' c( #' ".4*x1 + .1*x2 - .1*x4 + .1*x5", # w = 1 #' ".2 * x1 + .2 * x2 - .2 * x4 - .3 * x5" #' ) # w = 2 #' nlp_w_all <- #' c( #' "-.5*x1*x4 - .1*x2*x5", # w = 1 #' "-.3*x1*x4 + .2*x2*x5" #' ) # w = 2 #' lp_y_all <- rep(".2*x1 + .3*x2 - .1*x3 - .1*x4 - .2*x5", 3) #' nlp_y_all <- rep(".7*x1*x1 - .1*x2*x3", 3) #' X_all <- c( #' "rnorm(0, 0.5)", # x1 #' "rbeta(2, .4)", # x2 #' "runif(0, 0.5)", # x3 #' "rweibull(1,2)", # x4 #' "rbinom(1, .4)" # x5 #' ) #' #' set.seed(111111) #' data <- data_sim( #' sample_size = 300, #' n_trt = 3, #' x = X_all, #' lp_y = lp_y_all, #' nlp_y = nlp_y_all, #' align = FALSE, #' lp_w = lp_w_all, #' nlp_w = nlp_w_all, #' tau = c(-1.5, 0, 1.5), #' delta = c(0.5, 0.5), #' psi = 1 #' ) #' ce_estimate( #' y = data$y, x = data$covariates, w = data$w, #' ndpost = 100, method = "RA", estimand = "ATE" #' ) ce_estimate <- function(y, x, w, method, formula = NULL, discard = FALSE, estimand, trim_perc = NULL, sl_library, reference_trt, boot = FALSE, nboots, verbose_boot = TRUE, ndpost = 1000, caliper = 0.25, n_cluster = 5, ...) { if (!(estimand %in% c("ATE", "ATT"))) stop("Estimand only supported for \"ATT\" or \"ATE\"", call. = FALSE) if (!( method %in% c( "RA", "VM", "BART", "TMLE", "IPTW-Multinomial", "IPTW-GBM", "IPTW-SL", "RAMS-Multinomial", "RAMS-GBM", "RAMS-SL" ) )) stop( "Currently method is only supported for \"RA\", \"VM\", \"BART\", \"TMLE\", \"IPTW-Multinomial\", \"IPTW-GBM\", \"IPTW-SL\", \"RAMS-Multinomial\", \"RAMS-GBM\", \"RAMS-SL\". Please double check the entered method argument.", call. = FALSE ) if (estimand == "ATT" && !(reference_trt %in% unique(w))) stop(paste0( "Please set the reference_trt from ", paste0(sort(unique(w)), collapse = ", "), "." ), call. = FALSE) if (sum(c( length(w) == length(y), length(w) == nrow(x), length(y) == nrow(x) )) != 3) stop( paste0( "The length of y, the length of w and the nrow for x should be equal. Please double check the input." ), call. = FALSE ) if (!is.null(formula)) { x <- as.data.frame(stats::model.matrix(object = formula, cbind(y, x))) x <- x[, !(names(x) == "(Intercept)")] } if (method == "RA" && estimand == "ATE") { result <- ce_estimate_ra_ate( y = y, x = x, w = w, ndpost = ndpost ) } else if (method == "RA" && estimand == "ATT") { result <- ce_estimate_ra_att( y = y, x = x, w = w, ndpost = ndpost, reference_trt = reference_trt ) } else if (method == "VM" && estimand == "ATT" && boot == FALSE) { result <- ce_estimate_vm_att( y = y, x = x, w = w, reference_trt = reference_trt, caliper = caliper, n_cluster = n_cluster ) } else if (method == "VM" && estimand == "ATT" && boot == TRUE) { stop("Bootstrap confidence intervals are not appropriate for VM based on Lopez and Gutman (2017). The current version of CIMTx does not support the standard error calculation for VM.") } else if (method == "BART" && estimand == "ATE") { result <- ce_estimate_bart_ate( y = y, x = x, w = w, ndpost = ndpost, discard = discard, ... ) } else if (method == "BART" && estimand == "ATT") { result <- ce_estimate_bart_att( y = y, x = x, w = w, ndpost = ndpost, reference_trt = reference_trt, discard = discard, ... ) } else if (method == "TMLE" && estimand == "ATE" && boot == FALSE) { result <- ce_estimate_tmle_ate( y = y, x = x, w = w, sl_library = sl_library, ... ) } else if (method == "TMLE" && estimand == "ATE" && boot == TRUE) { result <- ce_estimate_tmle_ate_boot( y = y, x = x, w = w, sl_library = sl_library, nboots = nboots, verbose_boot = verbose_boot, ... ) } else if (method %in% c("RAMS-Multinomial", "RAMS-GBM", "RAMS-SL") && estimand == "ATE" && boot == FALSE) { result <- ce_estimate_rams_ate( y = y, x = x, w = w, method = method, verbose_boot = verbose_boot, ... ) } else if (method %in% c("RAMS-Multinomial", "RAMS-GBM", "RAMS-SL") && estimand == "ATE" && boot == TRUE) { result <- ce_estimate_rams_ate_boot( y = y, x = x, w = w, method = method, nboots = nboots, verbose_boot = verbose_boot, ... ) } else if (method %in% c("RAMS-Multinomial", "RAMS-GBM", "RAMS-SL") && estimand == "ATT" && boot == FALSE) { result <- ce_estimate_rams_att( y = y, x = x, w = w, method = method, reference_trt = reference_trt, ... ) } else if (method %in% c("RAMS-Multinomial", "RAMS-GBM", "RAMS-SL") && estimand == "ATT" && boot == TRUE) { result <- ce_estimate_rams_att_boot( y = y, x = x, w = w, method = method, nboots = nboots, reference_trt = reference_trt, verbose_boot = verbose_boot, ... ) } else if (method %in% c("IPTW-Multinomial", "IPTW-GBM", "IPTW-SL") && estimand == "ATE" && boot == FALSE) { result <- ce_estimate_iptw_ate( y = y, x = x, w = w, method = method, ... ) } else if (method %in% c("IPTW-Multinomial", "IPTW-GBM", "IPTW-SL") && estimand == "ATE" && boot == TRUE) { result <- ce_estimate_iptw_ate_boot( y = y, x = x, w = w, method = method, nboots = nboots, verbose_boot = verbose_boot, ... ) } else if (method %in% c("IPTW-Multinomial", "IPTW-GBM", "IPTW-SL") && estimand == "ATT" && boot == FALSE) { result <- ce_estimate_iptw_att( y = y, x = x, w = w, method = method, reference_trt = reference_trt, ... ) } else if (method %in% c("IPTW-Multinomial", "IPTW-GBM", "IPTW-SL") && estimand == "ATT" && boot == TRUE) { result <- ce_estimate_iptw_att_boot( y = y, x = x, w = w, method = method, reference_trt = reference_trt, nboots = nboots, verbose_boot = verbose_boot, ... ) } return(result) }
/scratch/gouwar.j/cran-all/cranData/CIMTx/R/ce_estimate.R
#' Causal inference with multiple treatments using BART for ATE effects #' #' The function \code{ce_estimate_bart_ate} implements #' BART to estimate ATE effect with #' multiple treatments using observational data. #' #' @param y A numeric vector (0, 1) representing a binary outcome. #' @param x A dataframe, including all the covariates but not treatments. #' @param w A numeric vector representing the treatment groups. #' @param discard A logical indicating whether to use the discarding rules. #' The default is \code{FALSE}. #' @param ndpost A numeric value indicating the number of posterior draws. #' @param ... Other parameters that can be passed through to functions. #' @return A summary of the effect estimates can be obtained #' with \code{summary} function. The output also #' contains a list of the posterior samples of causal estimands. When #' \code{discard = TRUE}, the output contains number of discarded #' individuals. #' @importFrom BART pbart #' @importFrom dplyr mutate select filter #' @references #' Sparapani R, Spanbauer C, McCulloch R #' Nonparametric Machine Learning and #' Efficient Computation with Bayesian Additive Regression Trees: #' The BART R Package. #' \emph{Journal of Statistical Software}, \strong{97}(1), 1-66. #' #' Hadley Wickham, Romain François, Lionel Henry and Kirill Müller (2021). #' \emph{dplyr: A Grammar of Data Manipulation}. R package version 1.0.7. #' URL: \url{https://CRAN.R-project.org/package=dplyr} ce_estimate_bart_ate <- function(y, x, w, discard = FALSE, ndpost = 1000, ...) { # Get the number of treatment groups n_trt <- length(unique(w)) # Get the sample size for each treatment group for (i in 1:n_trt) { assign(paste0("n", i), sum(w == i)) } xwdata <- cbind(w, x) # Fit BART model bart_mod <- BART::pbart(x.train = xwdata, y.train = y, ndpost = ndpost, ...) # Predict potential outcomes for each treatment group w for (i in 1:n_trt) { assign(paste0("xp", i), xwdata) for (j in 1:(n_trt)) { assign(paste0("xp", j), as.data.frame(eval(parse(text = paste0("xp", i)))) %>% dplyr::mutate(w = j)) assign(paste0("xp", i, j), as.data.frame(eval(parse(text = paste0("xp", i)))) %>% dplyr::filter(w == i) %>% dplyr::mutate(w = j)) assign(paste0("bart_pred", i, j), stats::predict(bart_mod, newdata = eval(parse(text = paste0("xp", i, j))))) assign(paste0("bart_pred", j), stats::predict(bart_mod, newdata = eval(parse(text = paste0("xp", j))))) assign(paste0("pred_prop", i, j), eval(parse(text = paste0("bart_pred", i, j)))[["prob.test"]]) assign(paste0("pred_prop", j), eval(parse(text = paste0("bart_pred", j)))[["prob.test"]]) } } # Implement the discarding rules if (discard == FALSE) { for (i in 1:n_trt) { for (j in 1:(n_trt)) { assign(paste0("pred_prop", i, j), eval(parse(text = paste0("bart_pred", i, j)))[["prob.test"]]) } } discard_all <- 0 } else if (discard == TRUE) { for (i in 1:n_trt) { for (j in 1:(n_trt)) { assign(paste0("post.ind.sd", i, j), apply(eval(parse(text = paste0("pred_prop", i, j))), 2, stats::sd)) } assign(paste0("threshold", i), max(eval(parse(text = paste0("post.ind.sd", i, i))))) } # Individuals with a large variability in the predicted potential outcomes # among each of the treatment groups are discarded for (i in 1:n_trt) { n_trt_no_i <- unique(w)[unique(w) != i] assign(paste0("eligible", i), TRUE) assign(paste0("criteria", i), TRUE) for (j in seq_len(n_trt_no_i)) { assign(paste0("criteria", i, n_trt_no_i[j]), eval(parse(text = paste0("post.ind.sd", i, n_trt_no_i[j]))) <= eval(parse(text = paste0("threshold", i)))) assign(paste0("eligible", i), eval(parse(text = paste0("criteria", i, n_trt_no_i[j]))) & eval(parse(text = paste0("criteria", i)))) } # Record the number of discarded individuals in each treatment group assign(paste0("n_", i, "_discard"), sum(eval(parse(text = paste0("eligible", i))) == FALSE)) } discard_all <- NULL for (i in 1:n_trt) { discard_all <- c(discard_all, eval(parse(text = paste0("n_", i, "_discard")))) } # Only use the undiscarded individuals for the final causal estimands for (i in 1:n_trt) { for (j in 1:(n_trt)) { assign(paste0("pred_prop", i, j), eval(parse(text = paste0("pred_prop", i, j))) %>% as.data.frame() %>% dplyr::select(which(eval(parse(text = paste0("eligible", i))))) %>% as.matrix()) } } } # Set up the final matrix to save the RD, RR and OR for (i in 1:(n_trt - 1)) { for (j in (i + 1):n_trt) { assign(paste0("RD", i, j, "_est"), NULL) assign(paste0("RR", i, j, "_est"), NULL) assign(paste0("OR", i, j, "_est"), NULL) } } for (i in 1:n_trt) { assign(paste0("y", i, "_pred"), NULL) assign(paste0("y", i, "_pred"), matrix(stats::rbinom( dim(eval(parse(text = ( paste0("pred_prop", i) ))))[1] * dim(eval(parse(text = ( paste0("pred_prop", i) ))))[2], 1, eval(parse(text = ( paste0("pred_prop", i) ))) ), nrow = ndpost)) } # Calculate the final RD, RR and OR using # the predictive posterior distributions from BART model for (i in 1:(n_trt - 1)) { for (j in (i + 1):n_trt) { assign(paste0("RD", i, j, "_est"), list(rowMeans(eval(parse(text = ( paste0("y", i, "_pred") )))) - rowMeans(eval(parse(text = ( paste0("y", j, "_pred") )))))) assign(paste0("RR", i, j, "_est"), list(rowMeans(eval(parse(text = ( paste0("y", i, "_pred") )))) / rowMeans(eval(parse(text = ( paste0("y", j, "_pred") )))))) assign(paste0("OR", i, j, "_est"), list(rowMeans((eval(parse( text = (paste0("y", i, "_pred")) ))) / (1 - rowMeans(eval( parse(text = (paste0( "y", i, "_pred" ))) )))) / rowMeans((eval(parse( text = (paste0("y", j, "_pred")) ))) / (1 - rowMeans(eval( parse(text = (paste0( "y", j, "_pred" ))) )))))) } } result <- NULL for (i in 1:(n_trt - 1)) { for (j in (i + 1):n_trt) { assign(paste0("RD", i, j, "_est"), stats::setNames(eval(parse(text = (paste0("RD", i, j, "_est")))), paste0("ATE_RD", i, j))) assign(paste0("RR", i, j, "_est"), stats::setNames(eval(parse(text = (paste0("RR", i, j, "_est")))), paste0("ATE_RR", i, j))) assign(paste0("OR", i, j, "_est"), stats::setNames(eval(parse(text = (paste0("OR", i, j, "_est")))), paste0("ATE_OR", i, j))) result <- c(result, (eval(parse(text = (paste0("RD", i, j, "_est"))))), (eval(parse(text = (paste0("RR", i, j, "_est"))))), (eval(parse(text = (paste0("OR", i, j, "_est")))))) } } result <- c(result, list(n_discard = discard_all), list(method = parent.frame()$method)) class(result) <- "CIMTx_ATE_posterior" return(result) }
/scratch/gouwar.j/cran-all/cranData/CIMTx/R/ce_estimate_bart_ate.R
#' Causal inference with multiple treatments using BART for ATT effects #' #' The function \code{ce_estimate_bart_att} implements #' BART to estimate ATT effect with #' multiple treatments using observational data. #' #' @param y A numeric vector (0, 1) representing a binary outcome. #' @param x A dataframe, including all the covariates but not treatments. #' @param w A numeric vector representing the treatment groups. #' @param discard A logical indicating whether to use the discarding rules. #' The default is \code{FALSE}. #' @param ndpost A numeric value indicating the number of posterior draws. #' @param reference_trt A numeric value indicating reference treatment group #' for ATT effect. #' @param ... Other parameters that can be passed through to functions. #' #' @return A summary of the effect estimates can be obtained #' with \code{summary} function. The output also #' contains a list of the posterior samples of causal estimands. When #' \code{discard = TRUE}, the output contains number of discarded #' individuals. #' @importFrom BART pbart #' @importFrom dplyr mutate select filter #' @references #' #' Sparapani R, Spanbauer C, McCulloch R #' Nonparametric Machine Learning and Efficient Computation with #' Bayesian Additive Regression Trees: The BART R Package. #' \emph{Journal of Statistical Software}, \strong{97}(1), 1-66. #' #' Hadley Wickham, Romain François, Lionel Henry and Kirill Müller (2021). #' \emph{dplyr: A Grammar of Data Manipulation}. R package version 1.0.7. #' URL: \url{https://CRAN.R-project.org/package=dplyr} ce_estimate_bart_att <- function(y, x, w, discard = FALSE, ndpost = 1000, reference_trt, ...) { # Get the number of treatment groups n_trt <- length(unique(w)) trt_ind <- seq_len(n_trt) trt_ind_no_ref <- trt_ind[trt_ind != reference_trt] # Get the sample size for each treatment group for (i in seq_len(n_trt)) { assign(paste0("n", i), sum(w == i)) } xwdata <- cbind(w, x) # Fit BART model bart_mod <- BART::pbart(x.train = xwdata, y.train = y, ndpost = ndpost, ...) assign(paste0("xp", reference_trt), xwdata[w == reference_trt, ]) for (i in trt_ind[trt_ind != reference_trt]) { assign(paste0("xp", i), xwdata[w == reference_trt, ]) assign(paste0("xp", i), as.data.frame(eval(parse(text = paste0("xp", i)))) %>% dplyr::mutate(w = i)) } # Predict potential outcomes among those in reference_trt group for (j in seq_len(n_trt)) { assign(paste0("bart_pred", reference_trt, j), BART::pwbart(eval(parse(text = paste0("xp", j))), bart_mod$treedraws, mu = mean(y))) assign(paste0("pred_prop", reference_trt, j), stats::pnorm(eval(parse(text = paste0("bart_pred", reference_trt, j))))) } # Implement the discarding rules if (discard == FALSE) { for (j in seq_len(n_trt)) { assign(paste0("pred_prop", reference_trt, j), stats::pnorm(eval(parse(text = paste0("bart_pred", reference_trt, j))))) } n_discard_att <- 0 } else if (discard == TRUE) { for (j in seq_len(n_trt)) { assign(paste0("post.ind.sd", j), apply(eval(parse(text = paste0("pred_prop", reference_trt, j))), 2, stats::sd)) } threshold <- max(eval(parse(text = paste0("post.ind.sd", reference_trt)))) for (j in seq_len(length(trt_ind_no_ref))) { assign(paste0("eligible", trt_ind_no_ref[j]), (eval(parse(text = paste0("post.ind.sd", trt_ind_no_ref[j]))) <= threshold)) } # Individuals with a large variability in the predicted potential outcomes # in the reference group are discarded eligible <- rep(TRUE, dim(eval(parse(text = paste0("pred_prop", reference_trt, 1))))[2]) for (j in seq_len(length(trt_ind_no_ref))) { eligible <- (eval(parse(text = paste0("eligible", trt_ind_no_ref[j]))) & eligible) } # Record the number of discarded individuals # Only use the undiscarded individuals for the final causal estimands n_discard_att <- sum(eligible == FALSE) for (j in seq_len(n_trt)) { assign(paste0("pred_prop", reference_trt, j), (eval(parse(text = paste0("pred_prop", reference_trt, j))) %>% as.data.frame() %>% dplyr::select(which(eligible)) %>% as.matrix())) } } # Set up the final matrix to save the RD, RR and OR for (j in seq_len(length(trt_ind_no_ref))) { assign(paste0("RD", reference_trt, trt_ind_no_ref[j], "_est"), NULL) assign(paste0("RR", reference_trt, trt_ind_no_ref[j], "_est"), NULL) assign(paste0("OR", reference_trt, trt_ind_no_ref[j], "_est"), NULL) } for (i in seq_len(n_trt)) { assign(paste0("y", i, "_pred"), NULL) assign(paste0("y", i, "_pred"), matrix(stats::rbinom( dim(eval(parse(text = ( paste0("pred_prop", reference_trt, i) ))))[1] * dim(eval(parse(text = ( paste0("pred_prop", reference_trt, i) ))))[2], 1, eval(parse(text = ( paste0("pred_prop", reference_trt, i) ))) ), nrow = ndpost)) } # Calculate the final RD, RR and OR using the # predictive posterior distributions from BART model for (j in seq_len(length(trt_ind_no_ref))) { assign(paste0("RD", reference_trt, trt_ind_no_ref[j], "_est"), list(rowMeans(eval(parse(text = ( paste0("y", reference_trt, "_pred") )))) - rowMeans(eval(parse(text = ( paste0("y", trt_ind_no_ref[j], "_pred") )))))) assign(paste0("RR", reference_trt, trt_ind_no_ref[j], "_est"), list(rowMeans(eval(parse(text = ( paste0("y", reference_trt, "_pred") )))) / rowMeans(eval(parse(text = ( paste0("y", trt_ind_no_ref[j], "_pred") )))))) assign(paste0("OR", reference_trt, trt_ind_no_ref[j], "_est"), list(rowMeans((eval(parse( text = (paste0("y", reference_trt, "_pred")) ))) / (1 - rowMeans(eval( parse(text = (paste0( "y", reference_trt, "_pred" ))) )))) / rowMeans((eval(parse( text = (paste0("y", trt_ind_no_ref[j], "_pred")) ))) / (1 - rowMeans(eval( parse(text = (paste0( "y", trt_ind_no_ref[j], "_pred" ))) )))))) } result <- NULL for (i in seq_len(n_trt - 1)) { for (j in seq_len(length(trt_ind_no_ref))) { assign(paste0("RD", reference_trt, trt_ind_no_ref[j], "_est"), stats::setNames(eval( parse(text = (paste0("RD", reference_trt, trt_ind_no_ref[j], "_est")))), paste0("ATT_RD", reference_trt, trt_ind_no_ref[j]))) assign(paste0("RR", reference_trt, trt_ind_no_ref[j], "_est"), stats::setNames(eval( parse(text = (paste0("RR", reference_trt, trt_ind_no_ref[j], "_est")))), paste0("ATT_RR", reference_trt, trt_ind_no_ref[j]))) assign(paste0("OR", reference_trt, trt_ind_no_ref[j], "_est"), stats::setNames(eval( parse(text = (paste0("OR", reference_trt, trt_ind_no_ref[j], "_est")))), paste0("ATT_OR", reference_trt, trt_ind_no_ref[j]))) result <- c(result, (eval(parse(text = (paste0("RD", reference_trt, trt_ind_no_ref[j], "_est"))))), (eval(parse(text = (paste0("RR", reference_trt, trt_ind_no_ref[j], "_est"))))), (eval(parse(text = (paste0("OR", reference_trt, trt_ind_no_ref[j], "_est")))))) } } result <- c(result, list(n_discard = n_discard_att), list(method = parent.frame()$method)) class(result) <- "CIMTx_ATT_posterior" return(result) }
/scratch/gouwar.j/cran-all/cranData/CIMTx/R/ce_estimate_bart_att.R
#' Causal inference with multiple treatments using IPTW for ATE effects #' #' The function \code{ce_estimate_iptw_ate} implements #' IPTW to estimate ATE effect with #' multiple treatments using observational data. #' #' @param y A numeric vector (0, 1) representing a binary outcome. #' @param w A numeric vector representing the treatment groups. #' @param x A dataframe, including all the covariates but not treatments. #' @param method A character string. Users can selected from the #' following methods including \code{"IPTW-Multinomial"}, #' \code{"IPTW-GBM"}, \code{"IPTW-SL"}. #' @param ... Other parameters that can be passed through to functions. #' #' @return A summary of the effect estimates can be obtained #' with \code{summary} function. The weight distributions can be #' visualized using \code{plot} function. #' @importFrom nnet multinom #' @importFrom WeightIt weightit #' @references #' #' Venables, W. N. & Ripley, B. D. (2002) #' \emph{Modern Applied Statistics with S}. #' Fourth Edition. Springer, New York. ISBN 0-387-95457-0 #' #' Matthew Cefalu, Greg Ridgeway, Dan McCaffrey, #' Andrew Morral, Beth Ann Griffin and Lane Burgette (2021). #' \emph{twang: Toolkit for Weighting and Analysis of Nonequivalent Groups}. #' R package version 2.5. URL:\url{https://CRAN.R-project.org/package=twang} #' #' Noah Greifer (2021). #' \emph{WeightIt: Weighting for Covariate Balance in Observational Studies}. #' R package version 0.12.0. #' URL:\url{https://CRAN.R-project.org/package=WeightIt} ce_estimate_iptw_ate <- function(y, w, x, method, ...) { xwdata <- as.data.frame(cbind(x, w = w)) n_trt <- length(unique(w)) trim_perc <- parent.frame()$trim_perc if (method == "IPTW-Multinomial" && is.null(trim_perc)) { # Fit a multinomial logistic regression model # with treatment indicator as the outcome psmod2 <- nnet::multinom(w ~ ., data = xwdata, trace = FALSE) pred_ps <- stats::fitted(psmod2) # Get the weights for (i in 1:n_trt) { assign(paste0("ate_wt_", i), 1 / pred_ps[, i]) } # Record the weights weight_glm <- NULL for (i in 1:n_trt) { weight_glm <- c(weight_glm, eval(parse(text = paste0("ate_wt_", i)))[w == i]) } # Calculate the weighted means for (i in 1:n_trt) { assign(paste0("mu_", i, "_hat_iptw"), sum(y[w == i] * weight_glm[w == i]) / sum(weight_glm[w == i])) } # Obtain the causal effects based on RD, OR and RR result_list_multinomial <- NULL for (i in 1:(n_trt - 1)) { result_once <- NULL for (j in (i + 1):n_trt) { assign(paste0("RD", i, j), eval(parse(text = paste0( "mu_", i, "_hat_iptw" ))) - eval(parse(text = paste0( "mu_", j, "_hat_iptw" )))) assign(paste0("RR", i, j), eval(parse(text = paste0( "mu_", i, "_hat_iptw" ))) / eval(parse(text = paste0( "mu_", j, "_hat_iptw" )))) assign(paste0("OR", i, j), (eval(parse( text = paste0("mu_", i, "_hat_iptw") )) / (1 - eval( parse(text = paste0("mu_", i, "_hat_iptw")) ))) / (eval(parse( text = paste0("mu_", j, "_hat_iptw") )) / (1 - eval( parse(text = paste0("mu_", j, "_hat_iptw")) )))) result_once <- rbind(eval(parse(text = paste0("RD", i, j))), eval(parse(text = paste0("RR", i, j))), eval(parse(text = paste0("OR", i, j)))) colnames(result_once) <- "EST" rownames(result_once) <- c("RD", "RR", "OR") result_once_list <- list(result_once) names(result_once_list) <- paste0("ATE", i, j) result_list_multinomial <- c(result_list_multinomial, result_once_list) } } result_list_multinomial <- c( result_list_multinomial, list(weight = weight_glm), list(method = method), list(estimand = "ATE") ) class(result_list_multinomial) <- "CIMTx_IPTW" return(result_list_multinomial) } else if (method == "IPTW-Multinomial" && !is.null(trim_perc)) { # Fit a multinomial logistic regression model # with treatment indicator as the outcome psmod2 <- nnet::multinom(w ~ ., data = xwdata, trace = FALSE) pred_ps <- stats::fitted(psmod2) # Get the weights for (i in 1:n_trt) { assign(paste0("ate_wt_", i), 1 / pred_ps[, i]) } # Record the weights weight_glm <- NULL for (i in 1:n_trt) { weight_glm <- c(weight_glm, eval(parse(text = paste0("ate_wt_", i)))[w == i]) } # Trim the weights weight_glm_trim <- trunc_fun(weight_glm, trim_perc) # Calculate the weighted means for (i in 1:n_trt) { assign( paste0("mu_", i, "_hat_iptw_trim"), sum(y[w == i] * weight_glm_trim[w == i]) / sum(weight_glm_trim[w == i]) ) } # Obtain the causal effects based on RD, OR and RR result_list_multinomial_trim <- NULL for (i in 1:(n_trt - 1)) { result_once <- NULL for (j in (i + 1):n_trt) { assign(paste0("RD", i, j), eval(parse( text = paste0("mu_", i, "_hat_iptw_trim") )) - eval(parse( text = paste0("mu_", j, "_hat_iptw_trim") ))) assign(paste0("RR", i, j), eval(parse( text = paste0("mu_", i, "_hat_iptw_trim") )) / eval(parse( text = paste0("mu_", j, "_hat_iptw_trim") ))) assign(paste0("OR", i, j), (eval(parse( text = paste0("mu_", i, "_hat_iptw_trim") )) / (1 - eval( parse(text = paste0("mu_", i, "_hat_iptw_trim")) ))) / (eval(parse( text = paste0("mu_", j, "_hat_iptw_trim") )) / (1 - eval( parse(text = paste0("mu_", j, "_hat_iptw_trim")) )))) result_once <- rbind(eval(parse(text = paste0("RD", i, j))), eval(parse(text = paste0("RR", i, j))), eval(parse(text = paste0("OR", i, j)))) colnames(result_once) <- "EST" rownames(result_once) <- c("RD", "RR", "OR") result_once_list <- list(result_once) names(result_once_list) <- paste0("ATE", i, j) result_list_multinomial_trim <- c(result_list_multinomial_trim, result_once_list) } } result_list_multinomial_trim <- c( result_list_multinomial_trim, list(weight = weight_glm_trim), list(method = paste0(method, "-Trim")), list(estimand = "ATE") ) class(result_list_multinomial_trim) <- "CIMTx_IPTW" return(result_list_multinomial_trim) } else if (method == "IPTW-GBM" && is.null(trim_perc)) { # Fit a GBM model with treatment indicator as the outcome temp <- noquote(names(x)) str_formula <- sprintf("w~%s", paste(temp, sep = "", collapse = "+")) psmod <- twang::mnps( stats::as.formula(str_formula), data = xwdata %>% mutate(w = as.factor(w)), estimand = "ATE", ) # Get the weights es.max.ATE <- NULL for (i in 1:n_trt) { assign(paste0("ps", i), psmod$psList[[i]]$ps %>% pull(es.max.ATE)) } wt_hat <- twang::get.weights(psmod, estimand = "ATE") # Calculate the weighted means for (i in 1:n_trt) { assign(paste0("mu_", i, "_hatgbm"), sum(y[w == i] * wt_hat[w == i]) / sum(wt_hat[w == i])) } # Obtain the causal effects based on RD, OR and RR result_list_gbm <- NULL for (i in 1:(n_trt - 1)) { result_once <- NULL for (j in (i + 1):n_trt) { assign(paste0("RD", i, j), eval(parse(text = paste0( "mu_", i, "_hatgbm" ))) - eval(parse(text = paste0( "mu_", j, "_hatgbm" )))) assign(paste0("RR", i, j), eval(parse(text = paste0( "mu_", i, "_hatgbm" ))) / eval(parse(text = paste0( "mu_", j, "_hatgbm" )))) assign(paste0("OR", i, j), (eval(parse( text = paste0("mu_", i, "_hatgbm") )) / (1 - eval( parse(text = paste0("mu_", i, "_hatgbm")) ))) / (eval(parse( text = paste0("mu_", j, "_hatgbm") )) / (1 - eval( parse(text = paste0("mu_", j, "_hatgbm")) )))) result_once <- rbind(eval(parse(text = paste0("RD", i, j))), eval(parse(text = paste0("RR", i, j))), eval(parse(text = paste0("OR", i, j)))) colnames(result_once) <- "EST" rownames(result_once) <- c("RD", "RR", "OR") result_once_list <- list(result_once) names(result_once_list) <- paste0("ATE", i, j) result_list_gbm <- c(result_list_gbm, result_once_list) } } result_list_gbm <- c( result_list_gbm, list(weight = wt_hat), list(method = method), list(estimand = "ATE") ) class(result_list_gbm) <- "CIMTx_IPTW" return(result_list_gbm) } else if (method == "IPTW-GBM" && !is.null(trim_perc)) { # Get the weights temp <- noquote(names(x)) str_formula <- sprintf("w~%s", paste(temp, sep = "", collapse = "+")) psmod <- twang::mnps( stats::as.formula(str_formula), data = xwdata %>% mutate(w = as.factor(w)), estimand = "ATE", ... ) for (i in 1:n_trt) { assign(paste0("ps", i), psmod$psList[[i]]$ps %>% pull(es.max.ATE)) } wt_hat <- twang::get.weights(psmod, estimand = "ATE") # Trim the weights wt_hat_trunc <- trunc_fun(wt_hat, trim_perc) # Calculate the weighted means for (i in 1:n_trt) { assign(paste0("mu_", i, "_hatgbm_trim"), sum(y[w == i] * wt_hat_trunc[w == i]) / sum(wt_hat_trunc[w == i])) } # Obtain the causal effects based on RD, OR and RR result_list_gbm_trim <- NULL for (i in 1:(n_trt - 1)) { result_once <- NULL for (j in (i + 1):n_trt) { assign(paste0("RD", i, j), eval(parse(text = paste0( "mu_", i, "_hatgbm_trim" ))) - eval(parse(text = paste0( "mu_", j, "_hatgbm_trim" )))) assign(paste0("RR", i, j), eval(parse(text = paste0( "mu_", i, "_hatgbm_trim" ))) / eval(parse(text = paste0( "mu_", j, "_hatgbm_trim" )))) assign(paste0("OR", i, j), (eval(parse( text = paste0("mu_", i, "_hatgbm_trim") )) / (1 - eval( parse(text = paste0("mu_", i, "_hatgbm_trim")) ))) / (eval(parse( text = paste0("mu_", j, "_hatgbm_trim") )) / (1 - eval( parse(text = paste0("mu_", j, "_hatgbm_trim")) )))) result_once <- rbind(eval(parse(text = paste0("RD", i, j))), eval(parse(text = paste0("RR", i, j))), eval(parse(text = paste0("OR", i, j)))) colnames(result_once) <- "EST" rownames(result_once) <- c("RD", "RR", "OR") result_once_list <- list(result_once) names(result_once_list) <- paste0("ATE", i, j) result_list_gbm_trim <- c(result_list_gbm_trim, result_once_list) } } result_list_gbm_trim <- c( result_list_gbm_trim, list(weight = wt_hat_trunc), list(method = paste0(method, "-Trim")), list(estimand = "ATE") ) class(result_list_gbm_trim) <- "CIMTx_IPTW" return(result_list_gbm_trim) } else if (method == "IPTW-SL" && is.null(trim_perc)) { sl_library <- parent.frame()$sl_library if (any((sl_library %in% getNamespaceExports("SuperLearner")[ grepl(pattern = "^[S]L", getNamespaceExports("SuperLearner"))]) == F)) stop( "sl_library argument unrecgonized; please use listWrappers() in SuperLearner to find the list of supported values", call. = FALSE ) # Get the weights weightit_superlearner <- WeightIt::weightit( w ~ ., data = xwdata, method = "super", estimand = "ATE", SL.library = sl_library, ... ) weight_superlearner <- weightit_superlearner$weights # Calculate the weighted means for (i in 1:n_trt) { assign( paste0("mu_", i, "_hat_superlearner"), sum(y[w == i] * weight_superlearner[w == i]) / sum(weight_superlearner[w == i]) ) } # Obtain the causal effects based on RD, OR and RR result_list_superlearner <- NULL for (i in 1:(n_trt - 1)) { result_once <- NULL for (j in (i + 1):n_trt) { assign(paste0("RD", i, j), eval(parse( text = paste0("mu_", i, "_hat_superlearner") )) - eval(parse( text = paste0("mu_", j, "_hat_superlearner") ))) assign(paste0("RR", i, j), eval(parse( text = paste0("mu_", i, "_hat_superlearner") )) / eval(parse( text = paste0("mu_", j, "_hat_superlearner") ))) assign(paste0("OR", i, j), (eval(parse( text = paste0("mu_", i, "_hat_superlearner") )) / (1 - eval( parse(text = paste0("mu_", i, "_hat_superlearner")) ))) / (eval(parse( text = paste0("mu_", j, "_hat_superlearner") )) / (1 - eval( parse(text = paste0("mu_", j, "_hat_superlearner")) )))) result_once <- rbind(eval(parse(text = paste0("RD", i, j))), eval(parse(text = paste0("RR", i, j))), eval(parse(text = paste0("OR", i, j)))) colnames(result_once) <- "EST" rownames(result_once) <- c("RD", "RR", "OR") result_once_list <- list(result_once) names(result_once_list) <- paste0("ATE", i, j) result_list_superlearner <- c(result_list_superlearner, result_once_list) } } result_list_superlearner <- c( result_list_superlearner, list(weight = weight_superlearner), list(method = method), list(estimand = "ATE") ) class(result_list_superlearner) <- "CIMTx_IPTW" return(result_list_superlearner) } else if (method == "IPTW-SL" && !is.null(trim_perc)) { sl_library <- parent.frame()$sl_library if (any((sl_library %in% getNamespaceExports("SuperLearner")[ grepl(pattern = "^[S]L", getNamespaceExports("SuperLearner"))]) == F)) stop( "sl_library argument unrecgonized; please use listWrappers() in SuperLearner to find the list of supported values", call. = FALSE ) # Get the weights weightit_superlearner <- WeightIt::weightit( w ~ ., data = xwdata, method = "super", estimand = "ATE", SL.library = sl_library, ... ) # Trim the weights weight_superlearner_trim <- trunc_fun(weightit_superlearner$weights, trim_perc) # Calculate the weighted means for (i in 1:n_trt) { assign( paste0("mu_", i, "_hat_superlearner_trim"), sum(y[w == i] * weight_superlearner_trim[w == i]) / sum(weight_superlearner_trim[w == i]) ) } # Obtain the causal effects based on RD, OR and RR result_list_superlearner_trim <- NULL for (i in 1:(n_trt - 1)) { result_once <- NULL for (j in (i + 1):n_trt) { assign(paste0("RD", i, j), eval(parse( text = paste0("mu_", i, "_hat_superlearner_trim") )) - eval(parse( text = paste0("mu_", j, "_hat_superlearner_trim") ))) assign(paste0("RR", i, j), eval(parse( text = paste0("mu_", i, "_hat_superlearner_trim") )) / eval(parse( text = paste0("mu_", j, "_hat_superlearner_trim") ))) assign(paste0("OR", i, j), (eval(parse( text = paste0("mu_", i, "_hat_superlearner_trim") )) / (1 - eval( parse(text = paste0( "mu_", i, "_hat_superlearner_trim" )) ))) / (eval(parse( text = paste0("mu_", j, "_hat_superlearner_trim") )) / (1 - eval( parse(text = paste0( "mu_", j, "_hat_superlearner_trim" )) )))) result_once <- rbind(eval(parse(text = paste0("RD", i, j))), eval(parse(text = paste0("RR", i, j))), eval(parse(text = paste0("OR", i, j)))) colnames(result_once) <- "EST" rownames(result_once) <- c("RD", "RR", "OR") result_once_list <- list(result_once) names(result_once_list) <- paste0("ATE", i, j) result_list_superlearner_trim <- c(result_list_superlearner_trim, result_once_list) } } result_list_superlearner_trim <- c( result_list_superlearner_trim, list(weight = weight_superlearner_trim), list(method = paste0(method, "-Trim")), list(estimand = "ATE") ) class(result_list_superlearner_trim) <- "CIMTx_IPTW" return(result_list_superlearner_trim) } }
/scratch/gouwar.j/cran-all/cranData/CIMTx/R/ce_estimate_iptw_ate.R
#' Causal inference with multiple treatments using IPTW for ATE effects #' (bootstrapping for CI) #' #' The function \code{ce_estimate_iptw_ate_boot} implements #' IPTW with bootstrapping to estimate ATE effect with #' multiple treatments using observational data. #' #' @param y A numeric vector (0, 1) representing a binary outcome. #' @param x A dataframe, including all the covariates but not treatments. #' @param w A numeric vector representing the treatment groups. #' @param method A character string. Users can selected from the following #' methods including \code{"IPTW-Multinomial"}, \code{"IPTW-GBM"}, #' \code{"IPTW-SL"}. #' @param nboots A numeric value representing the number of bootstrap samples. #' @param verbose_boot A logical value indicating whether to print #' the progress of nonparametric bootstrap. #' @param ... Other parameters that can be passed through to functions. #' #' @return A summary of the effect estimates can be obtained #' with \code{summary} function. #' @importFrom stringr str_sub #' @references #' Hadley Wickham (2019). #' \emph{stringr: Simple, Consistent Wrappers for Common String Operations}. #' R package version 1.4.0. #' URL:\url{https://CRAN.R-project.org/package=stringr} ce_estimate_iptw_ate_boot <- function(y, x, w, method, nboots, verbose_boot, ...) { sl_library <- parent.frame()$sl_library # Get the number of treatment group n_trt <- length(unique(w)) for (i in 1:n_trt) { assign(paste0("iptw_multitrt_ate_result_", i, "_all"), NULL) } names_result <- NULL # Start bootstrapping for (j in 1:nboots) { bootstrap_id <- sample(length(y), replace = T) y_boot <- y[bootstrap_id] w_boot <- w[bootstrap_id] x_boot <- x[bootstrap_id, ] iptw_multitrt_ate_result <- ce_estimate_iptw_ate( y = y_boot, x = x_boot, w = w_boot, method = method, ... ) names_result <- names(iptw_multitrt_ate_result) for (i in 1:n_trt) { assign( paste0("iptw_multitrt_ate_result_", i, "_all"), cbind(eval(parse( text = paste0("iptw_multitrt_ate_result_", i, "_all") )), iptw_multitrt_ate_result[[i]]) ) } if (verbose_boot == TRUE) { print(paste0("Finish bootstrapping ", j)) } } # Save the results of bootstrapping result <- NULL for (i in 1:n_trt) { assign(paste0("RD_", i), list(as.double(eval( parse(text = paste0( "iptw_multitrt_ate_result_", i, "_all" )) )[1, ]))) assign(paste0("RR_", i), list(as.double(eval( parse(text = paste0( "iptw_multitrt_ate_result_", i, "_all" )) )[2, ]))) assign(paste0("OR_", i), list(as.double(eval( parse(text = paste0( "iptw_multitrt_ate_result_", i, "_all" )) )[3, ]))) assign(paste0("RD_", i), stats::setNames(eval(parse(text = ( paste0("RD_", i) ))), paste0( "ATE_RD", stringr::str_sub(names_result[i], 4, 5) ))) assign(paste0("RR_", i), stats::setNames(eval(parse(text = ( paste0("RR_", i) ))), paste0( "ATE_RR", stringr::str_sub(names_result[i], 4, 5) ))) assign(paste0("OR_", i), stats::setNames(eval(parse(text = ( paste0("OR_", i) ))), paste0( "ATE_OR", stringr::str_sub(names_result[i], 4, 5) ))) result <- c(result, (eval(parse(text = ( paste0("RD_", i) )))), (eval(parse(text = ( paste0("RR_", i) )))), (eval(parse(text = ( paste0("OR_", i) ))))) } result <- c(result, list(method = parent.frame()$method)) class(result) <- "CIMTx_ATE_posterior" return(result) }
/scratch/gouwar.j/cran-all/cranData/CIMTx/R/ce_estimate_iptw_ate_boot.R
#' Causal inference with multiple treatments using IPTW for ATT effects #' #' The function \code{ce_estimate_iptw_att} implements #' IPTW to estimate ATT effect with #' multiple treatments using observational data. #' #' @param y A numeric vector (0, 1) representing a binary outcome. #' @param x A dataframe, including all the covariates but not treatments. #' @param w A numeric vector representing the treatment groups. #' @param method A character string. Users can selected from the #' following methods including \code{"IPTW-Multinomial"}, #' \code{"IPTW-GBM"}, \code{"IPTW-SL"}. #' @param reference_trt A numeric value indicating reference treatment group #' for ATT effect. #' @param ... Other parameters that can be passed through to functions. #' #' @return A summary of the effect estimates can be obtained #' with \code{summary} function. The weight distributions can be #' visualized using \code{plot} function. #' @importFrom nnet multinom #' @importFrom WeightIt weightit #' @references #' #' Venables, W. N. & Ripley, B. D. (2002) #' \emph{Modern Applied Statistics with S}. #' Fourth Edition. Springer, New York. ISBN 0-387-95457-0 #' #' Matthew Cefalu, Greg Ridgeway, Dan McCaffrey, #' Andrew Morral, Beth Ann Griffin and Lane Burgette (2021). #' \emph{twang: Toolkit for Weighting and Analysis of Nonequivalent Groups}. #' R package version 2.5. URL:\url{https://CRAN.R-project.org/package=twang} #' #' Noah Greifer (2021). #' \emph{WeightIt: Weighting for Covariate Balance in Observational Studies}. #' R package version 0.12.0. #' URL:\url{https://CRAN.R-project.org/package=WeightIt} ce_estimate_iptw_att <- function(y, x, w, method, reference_trt, ...) { xwdata <- as.data.frame(cbind(x, w = w)) n_trt <- length(unique(w)) trt_indicator <- 1:n_trt trt_indicator_no_reference <- trt_indicator[trt_indicator != reference_trt] trim_perc <- parent.frame()$trim_perc if (method == "IPTW-SL" && is.null(trim_perc)) { sl_library <- parent.frame()$sl_library if (any((sl_library %in% getNamespaceExports("SuperLearner")[ grepl(pattern = "^[S]L", getNamespaceExports("SuperLearner"))]) == F)) stop( "sl_library argument unrecgonized; please use listWrappers() in SuperLearner to find the list of supported values", call. = FALSE ) # Fit a SL model with treatment indicator as the outcome weightit_superlearner <- WeightIt::weightit( w ~ ., data = xwdata %>% mutate(w = as.factor(w)), focal = reference_trt, method = "super", estimand = "ATT", SL.library = sl_library, ... ) # Extract the weights weight_superlearner <- weightit_superlearner$weights assign(paste0("mu_", reference_trt, "_hat_iptw_superlearner"), mean(y[w == reference_trt])) # Calculate the weighted means for (i in seq_len(length(trt_indicator_no_reference))) { assign( paste0( "mu_", trt_indicator_no_reference[i], "_hat_iptw_superlearner" ), sum(y[w == trt_indicator_no_reference[i]] * weight_superlearner[w == trt_indicator_no_reference[i]]) / sum(weight_superlearner[w == trt_indicator_no_reference[i]]) ) } # Obtain the causal effects based on RD, OR and RR result_list_superlearner <- NULL for (j in seq_len(length(trt_indicator_no_reference))) { assign( paste0("RD", reference_trt, trt_indicator_no_reference[j]), eval(parse(text = ( paste0("mu_", reference_trt, "_hat_iptw_superlearner") ))) - eval(parse(text = ( paste0( "mu_", trt_indicator_no_reference[j], "_hat_iptw_superlearner" ) ))) ) assign( paste0("RR", reference_trt, trt_indicator_no_reference[j]), eval(parse(text = ( paste0("mu_", reference_trt, "_hat_iptw_superlearner") ))) / eval(parse(text = ( paste0( "mu_", trt_indicator_no_reference[j], "_hat_iptw_superlearner" ) ))) ) assign( paste0("OR", reference_trt, trt_indicator_no_reference[j]), (eval(parse( text = (paste0( "mu_", reference_trt, "_hat_iptw_superlearner" )) )) / (1 - eval( parse(text = ( paste0("mu_", reference_trt, "_hat_iptw_superlearner") )) ))) / (eval(parse( text = ( paste0( "mu_", trt_indicator_no_reference[j], "_hat_iptw_superlearner" ) ) )) / (1 - eval( parse(text = ( paste0( "mu_", trt_indicator_no_reference[j], "_hat_iptw_superlearner" ) )) ))) ) result_once <- rbind(eval(parse( text = paste0("RD", reference_trt, trt_indicator_no_reference[j]) )), eval(parse( text = paste0("RR", reference_trt, trt_indicator_no_reference[j]) )), eval(parse( text = paste0("OR", reference_trt, trt_indicator_no_reference[j]) ))) colnames(result_once) <- "EST" rownames(result_once) <- c("RD", "RR", "OR") result_once_list <- list(result_once) names(result_once_list) <- paste0("ATT", reference_trt, trt_indicator_no_reference[j]) result_list_superlearner <- c(result_list_superlearner, result_once_list) } result_list_superlearner <- c( result_list_superlearner, list(weight = weight_superlearner), list(method = method), list(estimand = "ATT") ) class(result_list_superlearner) <- "CIMTx_IPTW" return(result_list_superlearner) } if (method == "IPTW-Multinomial" && is.null(trim_perc)) { # Fit a multinomial logistic regression model with # treatment indicator as the outcome psmod2 <- nnet::multinom(w ~ ., data = xwdata, trace = FALSE) pred_ps <- stats::fitted(psmod2) # Get the weights for (j in seq_len(length(trt_indicator_no_reference))) { assign( paste0("att_wt_", reference_trt, trt_indicator_no_reference[j]), pred_ps[, reference_trt] / pred_ps[, trt_indicator_no_reference[j]] ) } # Record the weights weight_glm <- NULL for (i in seq_len(length(trt_indicator_no_reference))) { weight_glm <- c(weight_glm, eval(parse( text = paste0("att_wt_", reference_trt, trt_indicator_no_reference[i]) ))[w == trt_indicator_no_reference[i]]) } assign(paste0("mu_", reference_trt, "_hat_iptw"), mean(y[w == reference_trt])) # Calculate the weighted means for (i in seq_len(length(trt_indicator_no_reference))) { assign( paste0("mu_", trt_indicator_no_reference[i], "_hat_iptw"), sum(y[w == trt_indicator_no_reference[i]] * eval(parse( text = paste0("att_wt_", reference_trt, trt_indicator_no_reference[i]) ))[w == trt_indicator_no_reference[i]]) / sum(eval(parse( text = paste0("att_wt_", reference_trt, trt_indicator_no_reference[i]) ))[w == trt_indicator_no_reference[i]]) ) } # Obtain the causal effects based on RD, OR and RR result_list_multinomial <- NULL for (j in seq_len(length(trt_indicator_no_reference))) { assign( paste0("RD", reference_trt, trt_indicator_no_reference[j]), eval(parse(text = ( paste0("mu_", reference_trt, "_hat_iptw") ))) - eval(parse(text = ( paste0("mu_", trt_indicator_no_reference[j], "_hat_iptw") ))) ) assign( paste0("RR", reference_trt, trt_indicator_no_reference[j]), eval(parse(text = ( paste0("mu_", reference_trt, "_hat_iptw") ))) / eval(parse(text = ( paste0("mu_", trt_indicator_no_reference[j], "_hat_iptw") ))) ) assign( paste0("OR", reference_trt, trt_indicator_no_reference[j]), (eval(parse( text = (paste0("mu_", reference_trt, "_hat_iptw")) )) / (1 - eval( parse(text = ( paste0("mu_", reference_trt, "_hat_iptw") )) ))) / (eval(parse( text = ( paste0("mu_", trt_indicator_no_reference[j], "_hat_iptw") ) )) / (1 - eval( parse(text = ( paste0("mu_", trt_indicator_no_reference[j], "_hat_iptw") )) ))) ) result_once <- rbind(eval(parse( text = paste0("RD", reference_trt, trt_indicator_no_reference[j]) )), eval(parse( text = paste0("RR", reference_trt, trt_indicator_no_reference[j]) )), eval(parse( text = paste0("OR", reference_trt, trt_indicator_no_reference[j]) ))) colnames(result_once) <- "EST" rownames(result_once) <- c("RD", "RR", "OR") result_once_list <- list(result_once) names(result_once_list) <- paste0("ATT", reference_trt, trt_indicator_no_reference[j]) result_list_multinomial <- c(result_list_multinomial, result_once_list) } result_list_multinomial <- c( result_list_multinomial, list(weight = weight_glm), list(method = method), list(estimand = "ATT") ) class(result_list_multinomial) <- "CIMTx_IPTW" return(result_list_multinomial) } if (method == "IPTW-GBM" && is.null(trim_perc)) { # Fit a GBM model with treatment indicator as the outcome temp <- noquote(names(x)) str_formula <- sprintf("w~%s", paste(temp, sep = "", collapse = "+")) psmod <- twang::mnps( stats::as.formula(str_formula), data = xwdata %>% mutate(w = as.factor(w)), estimand = "ATT", treatATT = reference_trt, ... ) # Get the weights wt_hat <- twang::get.weights(psmod, estimand = "ATT") assign(paste0("mu_", reference_trt, "_hat_iptw_gbm"), mean(y[w == reference_trt])) # Calculate the weighted means for (i in seq_len(length(trt_indicator_no_reference))) { assign( paste0("mu_", trt_indicator_no_reference[i], "_hat_iptw_gbm"), sum(y[w == trt_indicator_no_reference[i]] * wt_hat[w == trt_indicator_no_reference[i]]) / sum(wt_hat[w == trt_indicator_no_reference[i]]) ) } # Obtain the causal effects based on RD, OR and RR result_list_gbm <- NULL for (j in seq_len(length(trt_indicator_no_reference))) { assign( paste0("RD", reference_trt, trt_indicator_no_reference[j]), eval(parse(text = ( paste0("mu_", reference_trt, "_hat_iptw_gbm") ))) - eval(parse(text = ( paste0("mu_", trt_indicator_no_reference[j], "_hat_iptw_gbm") ))) ) assign( paste0("RR", reference_trt, trt_indicator_no_reference[j]), eval(parse(text = ( paste0("mu_", reference_trt, "_hat_iptw_gbm") ))) / eval(parse(text = ( paste0("mu_", trt_indicator_no_reference[j], "_hat_iptw_gbm") ))) ) assign( paste0("OR", reference_trt, trt_indicator_no_reference[j]), (eval(parse( text = (paste0( "mu_", reference_trt, "_hat_iptw_gbm" )) )) / (1 - eval( parse(text = ( paste0("mu_", reference_trt, "_hat_iptw_gbm") )) ))) / (eval(parse( text = ( paste0("mu_", trt_indicator_no_reference[j], "_hat_iptw_gbm") ) )) / (1 - eval( parse(text = ( paste0("mu_", trt_indicator_no_reference[j], "_hat_iptw_gbm") )) ))) ) result_once <- rbind(eval(parse( text = paste0("RD", reference_trt, trt_indicator_no_reference[j]) )), eval(parse( text = paste0("RR", reference_trt, trt_indicator_no_reference[j]) )), eval(parse( text = paste0("OR", reference_trt, trt_indicator_no_reference[j]) ))) colnames(result_once) <- "EST" rownames(result_once) <- c("RD", "RR", "OR") result_once_list <- list(result_once) names(result_once_list) <- paste0("ATT", reference_trt, trt_indicator_no_reference[j]) result_list_gbm <- c(result_list_gbm, result_once_list) } result_list_gbm <- c( result_list_gbm, list(weight = wt_hat), list(method = method), list(estimand = "ATT") ) class(result_list_gbm) <- "CIMTx_IPTW" return(result_list_gbm) } if (method == "IPTW-Multinomial" && !is.null(trim_perc)) { # Fit a multinomial logistic regression model with # treatment indicator as the outcome psmod2 <- nnet::multinom(w ~ ., data = xwdata, trace = FALSE) pred_ps <- stats::fitted(psmod2) for (j in seq_len(length(trt_indicator_no_reference))) { assign( paste0("att_wt_", reference_trt, trt_indicator_no_reference[j]), pred_ps[, reference_trt] / pred_ps[, trt_indicator_no_reference[j]] ) } # Get the trimmed weights for (i in seq_len(length(trt_indicator_no_reference))) { assign( paste0( "att_wt_", reference_trt, trt_indicator_no_reference[i], "_trunc" ), trunc_fun(eval(parse( text = paste0("att_wt_", reference_trt, trt_indicator_no_reference[i]) )), trim_perc) ) } weight_glm <- NULL for (i in seq_len(length(trt_indicator_no_reference))) { weight_glm <- c(weight_glm, eval(parse( text = paste0( "att_wt_", reference_trt, trt_indicator_no_reference[i], "_trunc" ) ))[w == trt_indicator_no_reference[i]]) } assign(paste0("mu_", reference_trt, "_hat_iptw_trim"), mean(y[w == reference_trt])) # Calculate the weighted means for (i in seq_len(length(trt_indicator_no_reference))) { assign( paste0("mu_", trt_indicator_no_reference[i], "_hat_iptw_trim"), sum(y[w == trt_indicator_no_reference[i]] * eval(parse( text = paste0( "att_wt_", reference_trt, trt_indicator_no_reference[i], "_trunc" ) ))[w == trt_indicator_no_reference[i]]) / sum(eval(parse( text = paste0( "att_wt_", reference_trt, trt_indicator_no_reference[i], "_trunc" ) ))[w == trt_indicator_no_reference[i]]) ) } # Obtain the causal effects based on RD, OR and RR result_list_multinomial_trim <- NULL for (j in seq_len(length(trt_indicator_no_reference))) { assign( paste0("RD", reference_trt, trt_indicator_no_reference[j]), eval(parse(text = ( paste0("mu_", reference_trt, "_hat_iptw_trim") ))) - eval(parse(text = ( paste0("mu_", trt_indicator_no_reference[j], "_hat_iptw_trim") ))) ) assign( paste0("RR", reference_trt, trt_indicator_no_reference[j]), eval(parse(text = ( paste0("mu_", reference_trt, "_hat_iptw_trim") ))) / eval(parse(text = ( paste0("mu_", trt_indicator_no_reference[j], "_hat_iptw_trim") ))) ) assign( paste0("OR", reference_trt, trt_indicator_no_reference[j]), (eval(parse( text = (paste0( "mu_", reference_trt, "_hat_iptw_trim" )) )) / (1 - eval( parse(text = ( paste0("mu_", reference_trt, "_hat_iptw_trim") )) ))) / (eval(parse( text = ( paste0("mu_", trt_indicator_no_reference[j], "_hat_iptw_trim") ) )) / (1 - eval( parse(text = ( paste0("mu_", trt_indicator_no_reference[j], "_hat_iptw_trim") )) ))) ) result_once <- rbind(eval(parse( text = paste0("RD", reference_trt, trt_indicator_no_reference[j]) )), eval(parse( text = paste0("RR", reference_trt, trt_indicator_no_reference[j]) )), eval(parse( text = paste0("OR", reference_trt, trt_indicator_no_reference[j]) ))) colnames(result_once) <- "EST" rownames(result_once) <- c("RD", "RR", "OR") result_once_list <- list(result_once) names(result_once_list) <- paste0("ATT", reference_trt, trt_indicator_no_reference[j]) result_list_multinomial_trim <- c(result_list_multinomial_trim, result_once_list) } result_list_multinomial_trim <- c( result_list_multinomial_trim, list(weight = weight_glm), list(method = paste0(method, "-Trim")), list(estimand = "ATT") ) class(result_list_multinomial_trim) <- "CIMTx_IPTW" return(result_list_multinomial_trim) } if (method == "IPTW-GBM" && !is.null(trim_perc)) { # Fit a GBM model with treatment indicator as the outcome temp <- noquote(names(x)) str_formula <- sprintf("w~%s", paste(temp, sep = "", collapse = "+")) psmod <- twang::mnps( stats::as.formula(str_formula), data = xwdata %>% mutate(w = as.factor(w)), estimand = "ATT", treatATT = reference_trt, ... ) wt_hat <- twang::get.weights(psmod, estimand = "ATT") # Get the trimmed weights for (i in seq_len(length(trt_indicator_no_reference))) { wt_hat[w == i] <- trunc_fun(wt_hat[w == i], trim_perc) } assign(paste0("mu_", reference_trt, "_hat_iptw_gbm_trim"), mean(y[w == reference_trt])) # Calculate the weighted means for (i in seq_len(length(trt_indicator_no_reference))) { assign( paste0( "mu_", trt_indicator_no_reference[i], "_hat_iptw_gbm_trim" ), sum(y[w == trt_indicator_no_reference[i]] * wt_hat[w == trt_indicator_no_reference[i]]) / sum(wt_hat[w == trt_indicator_no_reference[i]]) ) } # Obtain the causal effects based on RD, OR and RR result_list_gbm_trim <- NULL for (j in seq_len(length(trt_indicator_no_reference))) { assign( paste0("RD", reference_trt, trt_indicator_no_reference[j]), eval(parse(text = ( paste0("mu_", reference_trt, "_hat_iptw_gbm_trim") ))) - eval(parse(text = ( paste0( "mu_", trt_indicator_no_reference[j], "_hat_iptw_gbm_trim" ) ))) ) assign( paste0("RR", reference_trt, trt_indicator_no_reference[j]), eval(parse(text = ( paste0("mu_", reference_trt, "_hat_iptw_gbm_trim") ))) / eval(parse(text = ( paste0( "mu_", trt_indicator_no_reference[j], "_hat_iptw_gbm_trim" ) ))) ) assign( paste0("OR", reference_trt, trt_indicator_no_reference[j]), (eval(parse( text = (paste0( "mu_", reference_trt, "_hat_iptw_gbm_trim" )) )) / (1 - eval( parse(text = ( paste0("mu_", reference_trt, "_hat_iptw_gbm_trim") )) ))) / (eval(parse( text = ( paste0( "mu_", trt_indicator_no_reference[j], "_hat_iptw_gbm_trim" ) ) )) / (1 - eval( parse(text = ( paste0( "mu_", trt_indicator_no_reference[j], "_hat_iptw_gbm_trim" ) )) ))) ) result_once <- rbind(eval(parse( text = paste0("RD", reference_trt, trt_indicator_no_reference[j]) )), eval(parse( text = paste0("RR", reference_trt, trt_indicator_no_reference[j]) )), eval(parse( text = paste0("OR", reference_trt, trt_indicator_no_reference[j]) ))) colnames(result_once) <- "EST" rownames(result_once) <- c("RD", "RR", "OR") result_once_list <- list(result_once) names(result_once_list) <- paste0("ATT", reference_trt, trt_indicator_no_reference[j]) result_list_gbm_trim <- c(result_list_gbm_trim, result_once_list) } result_list_gbm_trim <- c( result_list_gbm_trim, list(weight = wt_hat), list(method = paste0(method, "-Trim")), list(estimand = "ATT") ) class(result_list_gbm_trim) <- "CIMTx_IPTW" return(result_list_gbm_trim) } if (method == "IPTW-SL" && !is.null(trim_perc)) { # Fit a SL model with treatment indicator as the outcome sl_library <- parent.frame()$sl_library if (any((sl_library %in% getNamespaceExports("SuperLearner")[ grepl(pattern = "^[S]L", getNamespaceExports("SuperLearner"))]) == F)) stop( "sl_library argument unrecgonized; please use listWrappers() in SuperLearner to find the list of supported values", call. = FALSE ) # Extract the weights weightit_superlearner <- WeightIt::weightit( w ~ ., data = xwdata %>% mutate(w = as.factor(w)), focal = reference_trt, method = "super", estimand = "ATT", SL.library = sl_library, ... ) weight_superlearner <- weightit_superlearner$weights # Trim the weights weight_superlearner_trunc <- trunc_fun(weight_superlearner, trim_perc) for (i in seq_len(length(trt_indicator_no_reference))) { weight_superlearner_trunc[w == i] <- trunc_fun(weight_superlearner_trunc[w == i], trim_perc) } assign(paste0("mu_", reference_trt, "_hat_iptw_superlearner_trim"), mean(y[w == reference_trt])) # Calculate the weighted means for (i in seq_len(length(trt_indicator_no_reference))) { assign( paste0( "mu_", trt_indicator_no_reference[i], "_hat_iptw_superlearner_trim" ), sum(y[w == trt_indicator_no_reference[i]] * weight_superlearner_trunc[w == trt_indicator_no_reference[i]]) / sum(weight_superlearner_trunc[w == trt_indicator_no_reference[i]]) ) } # Obtain the causal effects based on RD, OR and RR result_list_superlearner_trim <- NULL for (j in seq_len(length(trt_indicator_no_reference))) { assign( paste0("RD", reference_trt, trt_indicator_no_reference[j]), eval(parse(text = ( paste0("mu_", reference_trt, "_hat_iptw_superlearner_trim") ))) - eval(parse(text = ( paste0( "mu_", trt_indicator_no_reference[j], "_hat_iptw_superlearner_trim" ) ))) ) assign( paste0("RR", reference_trt, trt_indicator_no_reference[j]), eval(parse(text = ( paste0("mu_", reference_trt, "_hat_iptw_superlearner_trim") ))) / eval(parse(text = ( paste0( "mu_", trt_indicator_no_reference[j], "_hat_iptw_superlearner_trim" ) ))) ) assign( paste0("OR", reference_trt, trt_indicator_no_reference[j]), (eval(parse( text = ( paste0("mu_", reference_trt, "_hat_iptw_superlearner_trim") ) )) / (1 - eval( parse(text = ( paste0("mu_", reference_trt, "_hat_iptw_superlearner_trim") )) ))) / (eval(parse( text = ( paste0( "mu_", trt_indicator_no_reference[j], "_hat_iptw_superlearner_trim" ) ) )) / (1 - eval( parse(text = ( paste0( "mu_", trt_indicator_no_reference[j], "_hat_iptw_superlearner_trim" ) )) ))) ) result_once <- rbind(eval(parse( text = paste0("RD", reference_trt, trt_indicator_no_reference[j]) )), eval(parse( text = paste0("RR", reference_trt, trt_indicator_no_reference[j]) )), eval(parse( text = paste0("OR", reference_trt, trt_indicator_no_reference[j]) ))) colnames(result_once) <- "EST" rownames(result_once) <- c("RD", "RR", "OR") result_once_list <- list(result_once) names(result_once_list) <- paste0("ATT", reference_trt, trt_indicator_no_reference[j]) result_list_superlearner_trim <- c(result_list_superlearner_trim, result_once_list) } result_list_superlearner_trim <- c( result_list_superlearner_trim, list(weight = weight_superlearner_trunc), list(method = paste0(method, "-Trim")), list(estimand = "ATT") ) class(result_list_superlearner_trim) <- "CIMTx_nonIPTW_once" return(result_list_superlearner_trim) } }
/scratch/gouwar.j/cran-all/cranData/CIMTx/R/ce_estimate_iptw_att.R
#' Causal inference with multiple treatments using IPTW for ATT effects #' (bootstrapping for CI) #' #' The function \code{ce_estimate_iptw_att_boot} implements #' IPTW with bootstrapping to estimate ATT effect with #' multiple treatments using observational data. #' #' @param y A numeric vector (0, 1) representing a binary outcome. #' @param x A dataframe, including all the covariates but not treatments. #' @param w A numeric vector representing the treatment groups. #' @param reference_trt A numeric value indicating reference treatment group #' for ATT effect. #' @param method A character string. Users can selected from the #' following methods including \code{"IPTW-Multinomial"}, #' \code{"IPTW-GBM"}, \code{"IPTW-SL"}. #' @param nboots A numeric value representing the number of bootstrap samples. #' @param verbose_boot A logical value indicating whether to print #' the progress of nonparametric bootstrap. The default is \code{TRUE}. #' @param ... Other parameters that can be passed through to functions. #' #' @return A summary of the effect estimates can be obtained #' with \code{summary} function. #' @importFrom stringr str_sub #' @references #' Hadley Wickham (2019). #' \emph{stringr: Simple, Consistent Wrappers for Common String Operations}. #' R package version 1.4.0. #' URL:\url{https://CRAN.R-project.org/package=stringr} ce_estimate_iptw_att_boot <- function(y, x, w, reference_trt, method, nboots, verbose_boot, ...) { sl_library <- parent.frame()$sl_library # Get the number of treatment group n_trt <- length(unique(w)) for (i in 1:(n_trt - 1)) { assign(paste0("iptw_multitrt_att_result_", i, "_all"), NULL) } names_result <- NULL # Start bootstrapping for (j in 1:nboots) { bootstrap_id <- sample(length(y), replace = T) y_boot <- y[bootstrap_id] trt_boot <- w[bootstrap_id] x_boot <- x[bootstrap_id, ] iptw_multitrt_att_result <- ce_estimate_iptw_att( y = y_boot, x = x_boot, w = trt_boot, reference_trt, method = method, ... ) names_result <- names(iptw_multitrt_att_result) for (i in 1:(n_trt - 1)) { assign( paste0("iptw_multitrt_att_result_", i, "_all"), cbind(eval(parse( text = paste0("iptw_multitrt_att_result_", i, "_all") )), iptw_multitrt_att_result[[i]]) ) } if (verbose_boot == TRUE) { print(paste0("Finish bootstrapping ", j)) } } # Save the results of bootstrapping result <- NULL for (i in 1:(n_trt - 1)) { assign(paste0("RD_", i), list(as.double(eval( parse(text = paste0( "iptw_multitrt_att_result_", i, "_all" )) )[1, ]))) assign(paste0("RR_", i), list(as.double(eval( parse(text = paste0( "iptw_multitrt_att_result_", i, "_all" )) )[2, ]))) assign(paste0("OR_", i), list(as.double(eval( parse(text = paste0( "iptw_multitrt_att_result_", i, "_all" )) )[3, ]))) assign(paste0("RD_", i), stats::setNames(eval(parse(text = ( paste0("RD_", i) ))), paste0( "ATT_RD", stringr::str_sub(names_result[i], 4, 5) ))) assign(paste0("RR_", i), stats::setNames(eval(parse(text = ( paste0("RR_", i) ))), paste0( "ATT_RR", stringr::str_sub(names_result[i], 4, 5) ))) assign(paste0("OR_", i), stats::setNames(eval(parse(text = ( paste0("OR_", i) ))), paste0( "ATT_OR", stringr::str_sub(names_result[i], 4, 5) ))) result <- c(result, (eval(parse(text = ( paste0("RD_", i) )))), (eval(parse(text = ( paste0("RR_", i) )))), (eval(parse(text = ( paste0("OR_", i) ))))) } result <- c(result, list(method = parent.frame()$method)) class(result) <- "CIMTx_ATT_posterior" return(result) }
/scratch/gouwar.j/cran-all/cranData/CIMTx/R/ce_estimate_iptw_att_boot.R
#' Causal inference with multiple treatments using RA for ATE effects #' #' The function \code{ce_estimate_ra_ate} implements #' RA to estimate ATE effect with #' multiple treatments using observational data. #' #' @param y A numeric vector (0, 1) representing a binary outcome. #' @param x A dataframe, including all the covariates but not treatments. #' @param w A numeric vector representing the treatment groups. #' @param ndpost A numeric value indicating the number of posterior draws. #' #' @return A summary of the effect estimates can be obtained #' with \code{summary} function. The output also #' contains a list of the posterior samples of causal estimands. #' @importFrom arm bayesglm sim invlogit #' @importFrom dplyr mutate #' @references #' #' Hadley Wickham, Romain François, Lionel Henry and Kirill Müller (2021). #' \emph{dplyr: A Grammar of Data Manipulation}. #' R package version 1.0.7. #' URL: \url{https://CRAN.R-project.org/package=dplyr} #' #' Andrew Gelman and Yu-Sung Su (2020). #' \emph{arm: Data Analysis Using Regression and #' Multilevel/Hierarchical Models}. #' R package version 1.11-2. #' \emph{https://CRAN.R-project.org/package=arm} ce_estimate_ra_ate <- function(y, x, w, ndpost) { n_trt <- length(unique(w)) # Number of unique treatments for (i in 1:n_trt) { # Number of individuals receiving each treatment assign(paste0("n", i), sum(w == i)) } n <- length(w) xwdata <- cbind(w, x) xwydata <- cbind(y, xwdata) # Fit Bayesian logistic regression reg_mod <- arm::bayesglm( y ~ ., data = as.data.frame(xwydata), family = stats::binomial(link = "logit"), x = TRUE ) mod_sims <- arm::sim(reg_mod, n.sims = ndpost) sim_beta <- as.matrix(stats::coef(mod_sims)) x_tilde <- stats::model.matrix(reg_mod) for (i in 1:n_trt) { assign(paste0("x_tilde", i), as.data.frame(x_tilde) %>% dplyr::mutate(w = i)) } # Predict potential outcomes for each treatment group for (i in 1:n_trt) { assign(paste0("p", i, "_tilde"), arm::invlogit(as.matrix(sim_beta %*% t(eval( parse(text = paste0("x_tilde", i)) ))))) assign(paste0("y", i, "_tilde"), matrix(stats::rbinom(ndpost * n, 1, eval( parse(text = paste0("p", i, "_tilde")) )), nrow = ndpost)) } for (i in 1:(n_trt - 1)) { for (j in (i + 1):(n_trt)) { assign(paste0("RD", i, j, "_est"), NULL) assign(paste0("RR", i, j, "_est"), NULL) assign(paste0("OR", i, j, "_est"), NULL) } } for (i in 1:n_trt) { assign(paste0("y", i, "_pred"), rowMeans(eval(parse( text = paste0("y", i, "_tilde") )))) } # Estimate causal effects in terms of OR, RR and RD result <- NULL for (i in 1:(n_trt - 1)) { for (j in (i + 1):n_trt) { assign(paste0("RD", i, j, "_est"), list(eval(parse( text = (paste0("y", i, "_pred")) )) - eval(parse( text = (paste0("y", j, "_pred")) )))) assign(paste0("RR", i, j, "_est"), list(eval(parse( text = (paste0("y", i, "_pred")) )) / eval(parse( text = (paste0("y", j, "_pred")) )))) assign(paste0("OR", i, j, "_est"), list((eval( parse(text = (paste0( "y", i, "_pred" ))) ) / ( 1 - eval(parse(text = ( paste0("y", i, "_pred") ))) )) / (eval( parse(text = (paste0( "y", j, "_pred" ))) ) / ( 1 - eval(parse(text = ( paste0("y", j, "_pred") ))) )))) assign(paste0("RD", i, j, "_est"), stats::setNames(eval(parse( text = (paste0("RD", i, j, "_est")) )), paste0("ATE_RD", i, j))) assign(paste0("RR", i, j, "_est"), stats::setNames(eval(parse( text = (paste0("RR", i, j, "_est")) )), paste0("ATE_RR", i, j))) assign(paste0("OR", i, j, "_est"), stats::setNames(eval(parse( text = (paste0("OR", i, j, "_est")) )), paste0("ATE_OR", i, j))) result <- c(result, (eval(parse( text = (paste0("RD", i, j, "_est")) ))), (eval(parse( text = (paste0("RR", i, j, "_est")) ))), (eval(parse( text = (paste0("OR", i, j, "_est")) )))) } } result <- c(result, list(method = parent.frame()$method)) class(result) <- "CIMTx_ATE_posterior" return(result) }
/scratch/gouwar.j/cran-all/cranData/CIMTx/R/ce_estimate_ra_ate.R
#' Causal inference with multiple treatments using RA for ATT effects #' #' The function \code{ce_estimate_ra_att} implements #' RA to estimate ATT effect with #' multiple treatments using observational data. #' #' @param y A numeric vector (0, 1) representing a binary outcome. #' @param x A dataframe, including all the covariates but not treatments. #' @param w A numeric vector representing the treatment groups. #' @param ndpost A numeric value indicating the number of posterior draws. #' @param reference_trt A numeric value indicating reference treatment group #' for ATT effect. #' #' @return A summary of the effect estimates can be obtained #' with \code{summary} function. The output also #' contains a list of the posterior samples of causal estimands. #' @importFrom arm bayesglm sim invlogit #' @importFrom dplyr mutate #' @references #' #' Hadley Wickham, Romain François, Lionel Henry and Kirill Müller (2021). #' \emph{dplyr: A Grammar of Data Manipulation}. #' R package version 1.0.7. #' URL: \url{https://CRAN.R-project.org/package=dplyr} #' #' Andrew Gelman and Yu-Sung Su (2020). #' \emph{arm: Data Analysis Using Regression and #' Multilevel/Hierarchical Models}. #' R package version 1.11-2. \emph{https://CRAN.R-project.org/package=arm} ce_estimate_ra_att <- function(y, x, w, ndpost, reference_trt) { n_trt <- length(unique(w)) # Number of unique treatments for (i in 1:n_trt) { # Number of individuals receiving each treatment assign(paste0("n", i), sum(w == i)) } trt_indicator <- 1:n_trt trt_indicator_no_reference <- trt_indicator[trt_indicator != reference_trt] xwdata <- cbind(w, x) xwydata <- cbind(y, xwdata) # Fit Bayesian logistic regression reg_mod <- arm::bayesglm( y ~ ., data = xwydata, family = stats::binomial(link = "logit"), x = TRUE ) mod_sims <- arm::sim(reg_mod, n.sims = ndpost) sim_beta <- as.matrix(stats::coef(mod_sims)) x_tilde <- as.data.frame(stats::model.matrix(reg_mod)) for (i in 1:n_trt) { assign(paste0("x_tilde", reference_trt, i), x_tilde[x_tilde[["w"]] == reference_trt, ]) } # Predict potential outcomes for each treatment group # assuming every one receives the reference_trt for (i in seq_len(length(trt_indicator_no_reference))) { assign( paste0("x_tilde", reference_trt, trt_indicator_no_reference[i]), eval(parse( text = paste0("x_tilde", reference_trt, trt_indicator_no_reference[i]) )) %>% dplyr::mutate(w = trt_indicator_no_reference[i]) ) } for (i in 1:n_trt) { assign(paste0("p", reference_trt, i, "_tilde"), arm::invlogit(as.matrix(sim_beta %*% t(eval( parse(text = paste0("x_tilde", reference_trt, i)) ))))) assign(paste0("y", reference_trt, i, "_tilde"), matrix(stats::rbinom(ndpost * eval( parse(text = paste0("n", reference_trt)) ), 1, eval( parse(text = paste0("p", reference_trt, i, "_tilde")) )), nrow = ndpost)) assign(paste0("y", i, "_pred"), rowMeans(eval(parse( text = paste0("y", reference_trt, i, "_tilde") )))) } for (j in seq_len(length(trt_indicator_no_reference))) { assign(paste0("RD", reference_trt, trt_indicator_no_reference[j], "_est"), NULL) assign(paste0("RR", reference_trt, trt_indicator_no_reference[j], "_est"), NULL) assign(paste0("OR", reference_trt, trt_indicator_no_reference[j], "_est"), NULL) } # Estimate causal effects in terms of OR, RR and RD result <- NULL for (i in 1:(n_trt - 1)) { for (j in seq_len(length(trt_indicator_no_reference))) { assign( paste0( "RD", reference_trt, trt_indicator_no_reference[j], "_est" ), list(eval(parse( text = (paste0("y", reference_trt, "_pred")) )) - eval(parse( text = (paste0( "y", trt_indicator_no_reference[j], "_pred" )) ))) ) assign( paste0( "RR", reference_trt, trt_indicator_no_reference[j], "_est" ), list(eval(parse( text = (paste0("y", reference_trt, "_pred")) )) / eval(parse( text = (paste0( "y", trt_indicator_no_reference[j], "_pred" )) ))) ) assign(paste0( "OR", reference_trt, trt_indicator_no_reference[j], "_est" ), list((eval( parse(text = ( paste0("y", reference_trt, "_pred") )) ) / ( 1 - eval(parse(text = ( paste0("y", reference_trt, "_pred") ))) )) / (eval( parse(text = ( paste0("y", trt_indicator_no_reference[j], "_pred") )) ) / ( 1 - eval(parse(text = ( paste0("y", trt_indicator_no_reference[j], "_pred") ))) )))) assign( paste0( "RD", reference_trt, trt_indicator_no_reference[j], "_est" ), stats::setNames( eval(parse(text = ( paste0( "RD", reference_trt, trt_indicator_no_reference[j], "_est" ) ))), paste0("ATT_RD", reference_trt, trt_indicator_no_reference[j]) ) ) assign( paste0( "RR", reference_trt, trt_indicator_no_reference[j], "_est" ), stats::setNames( eval(parse(text = ( paste0( "RR", reference_trt, trt_indicator_no_reference[j], "_est" ) ))), paste0("ATT_RR", reference_trt, trt_indicator_no_reference[j]) ) ) assign( paste0( "OR", reference_trt, trt_indicator_no_reference[j], "_est" ), stats::setNames( eval(parse(text = ( paste0( "OR", reference_trt, trt_indicator_no_reference[j], "_est" ) ))), paste0("ATT_OR", reference_trt, trt_indicator_no_reference[j]) ) ) result <- c(result, (eval(parse( text = ( paste0( "RD", reference_trt, trt_indicator_no_reference[j], "_est" ) ) ))), (eval(parse( text = ( paste0( "RR", reference_trt, trt_indicator_no_reference[j], "_est" ) ) ))), (eval(parse( text = ( paste0( "OR", reference_trt, trt_indicator_no_reference[j], "_est" ) ) )))) } } result <- c(result, list(method = parent.frame()$method)) class(result) <- "CIMTx_ATT_posterior" return(result) }
/scratch/gouwar.j/cran-all/cranData/CIMTx/R/ce_estimate_ra_att.R
#' Causal inference with multiple treatments using RAMS for ATE effects #' #' The function \code{ce_estimate_rams_ate} implements #' RAMS to estimate ATE effect with #' multiple treatments using observational data. #' #' @param y A numeric vector (0, 1) representing a binary outcome. #' @param w A numeric vector representing the treatment groups. #' @param x A dataframe, including all the covariates but not treatments. #' @param method A character string. Users can selected from the #' following methods including \code{"RAMS-Multinomial"}, #' \code{"RAMS-GBM"}, \code{"RAMS-SL"}. #' @param ... Other parameters that can be passed through to functions. #' #' @return A summary of the effect estimates can be obtained #' with \code{summary} function. #' @importFrom mgcv gam #' @importFrom nnet multinom #' @importFrom WeightIt weightit #' #' @references #' Matthew Cefalu, Greg Ridgeway, Dan McCaffrey, #' Andrew Morral, Beth Ann Griffin and Lane Burgette (2021). #' \emph{twang: Toolkit for Weighting and Analysis of Nonequivalent Groups}. #' R package version 2.5. #' URL:\url{https://CRAN.R-project.org/package=twang} #' #' Venables, W. N. & Ripley, B. D. (2002) #' \emph{Modern Applied Statistics with S}. #' Fourth Edition. Springer, New York. ISBN 0-387-95457-0 #' #' Noah Greifer (2021). #' \emph{WeightIt: Weighting for Covariate Balance in Observational Studies}. #' R package version 0.12.0. #' URL:\url{https://CRAN.R-project.org/package=WeightIt} #' #' Wood, S.N. (2011) #' Fast stable restricted maximum likelihood and marginal likelihood #' estimation of semiparametric generalized linear models. #' \emph{Journal of the Royal Statistical Society (B)} \strong{73}(1):3-36 ce_estimate_rams_ate <- function(y, w, x, method, ...) { n.trees <- parent.frame()$n.trees interaction.depth <- parent.frame()$interaction.depth trim_perc <- parent.frame()$trim_perc n_trt <- length(unique(w)) xwydata <- as.data.frame(cbind(y = y, x, w = w)) xwdata <- as.data.frame(cbind(x, w = w)) n <- nrow(xwydata) if (method == "RAMS-Multinomial" && is.null(trim_perc)) { # Fit a multinomial logistic regression model with # treatment indicator as the outcome psmod2 <- nnet::multinom(w ~ ., data = xwdata, trace = FALSE) pred_ps <- stats::fitted(psmod2) for (i in 1:n_trt) { assign(paste0("ps", i), pred_ps[, i]) } } else if (method == "RAMS-Multinomial" && !is.null(trim_perc)) { # Fit a multinomial logistic regression model with # treatment indicator as the outcome psmod2 <- nnet::multinom(w ~ ., data = xwdata, trace = FALSE) # Trim the PS pred_ps <- stats::fitted(psmod2) for (i in 1:n_trt) { assign(paste0("ps", i), trunc_fun(pred_ps[, i])) } } else if (method == "RAMS-GBM" && is.null(trim_perc)) { # Fit a GBM model with treatment indicator as the outcome temp <- noquote(names(x)) str_formula <- sprintf("w~%s", paste(temp, sep = "", collapse = "+")) psmod <- twang::mnps( stats::as.formula(str_formula), data = xwdata %>% mutate(w = as.factor(w)), estimand = "ATE", treatATT = NULL, ... ) es.max.ATE <- NULL # Extract the PS for (i in 1:n_trt) { assign(paste0("ps", i), psmod$psList[[i]]$ps %>% pull(es.max.ATE)) } } else if (method == "RAMS-GBM" && !is.null(trim_perc)) { # Fit a GBM model with treatment indicator as the outcome temp <- noquote(names(x)) str_formula <- sprintf("w~%s", paste(temp, sep = "", collapse = "+")) psmod <- twang::mnps( stats::as.formula(str_formula), data = xwdata %>% mutate(w = as.factor(w)), estimand = "ATE", treatATT = NULL, ... ) # Extract and trim the PS for (i in 1:n_trt) { assign(paste0("ps", i), trunc_fun(psmod$psList[[i]]$ps %>% pull(es.max.ATE))) } } else if (method == "RAMS-SL" && is.null(trim_perc)) { # Fit a SL model with treatment indicator as the outcome sl_library <- parent.frame()$sl_library if (any((sl_library %in% getNamespaceExports("SuperLearner")[ grepl(pattern = "^[S]L", getNamespaceExports("SuperLearner"))]) == F)) stop( "sl_library argument unrecgonized; please use listWrappers() in SuperLearner to find the list of supported values", call. = FALSE ) weightit_superlearner <- WeightIt::weightit( as.factor(w) ~ ., data = xwdata, method = "super", estimand = "ATE", SL.library = sl_library, ... ) # Get the PS for (i in 1:n_trt) { assign(paste0("ps", i), 1 / weightit_superlearner$weights) } } else if (method == "RAMS-SL" && !is.null(trim_perc)) { # Fit a SL model with treatment indicator as the outcome sl_library <- parent.frame()$sl_library if (any((sl_library %in% getNamespaceExports("SuperLearner")[ grepl(pattern = "^[S]L", getNamespaceExports("SuperLearner"))]) == F)) stop( "sl_library argument unrecgonized; please use listWrappers() in SuperLearner to find the list of supported values", call. = FALSE ) weightit_superlearner <- WeightIt::weightit( as.factor(w) ~ ., data = xwdata, method = "super", estimand = "ATE", SL.library = sl_library, ... ) # Get the trimmed PS for (i in 1:n_trt) { assign( paste0("ps", i), trunc_fun(1 / weightit_superlearner$weights, trim_perc = trim_perc) ) } } # logit of propensity scores logit_ps1 <- NULL logit_ps2 <- NULL for (i in 1:n_trt) { assign(paste0("logit_ps", i), stats::qlogis(eval(parse(text = paste0( "ps", i ))))) } # Fit a generalized additive model using the treatment indicator # and multivariate spline function of the logit of GPS as the predictors mod_splinedat <- as.data.frame(cbind(w = xwydata$w, logit_ps1, logit_ps2)) mod_spline <- mgcv::gam( y ~ w + te(logit_ps1, logit_ps2), family = stats::binomial(link = "logit"), data = mod_splinedat ) # Predict the potential outcomes using the fitted GAM model for (i in 1:n_trt) { assign(paste0("newdata", i), data.frame(w = rep(i, n), logit_ps1, logit_ps2)) assign(paste0("spline.pred", i), stats::plogis(stats::predict(mod_spline, newdata = eval( parse(text = paste0("newdata", i)) )))) assign(paste0("y", i, ".hat"), mean(eval(parse( text = paste0("spline.pred", i) )))) } # Estimate the causal effects in terms of OR, RR and RD result_list <- NULL for (i in 1:(n_trt - 1)) { result_once <- NULL for (j in (i + 1):n_trt) { assign(paste0("RD", i, j), eval(parse(text = paste0("y", i, ".hat"))) - eval(parse(text = paste0("y", j, ".hat")))) assign(paste0("RR", i, j), eval(parse(text = paste0("y", i, ".hat"))) / eval(parse(text = paste0("y", j, ".hat")))) assign(paste0("OR", i, j), (eval(parse( text = paste0("y", i, ".hat") )) / (1 - eval( parse(text = paste0("y", i, ".hat")) ))) / (eval(parse( text = paste0("y", j, ".hat") )) / (1 - eval( parse(text = paste0("y", j, ".hat")) )))) result_once <- round(rbind(eval(parse( text = paste0("RD", i, j) )), eval(parse( text = paste0("RR", i, j) )), eval(parse( text = paste0("OR", i, j) ))), 2) colnames(result_once) <- "EST" rownames(result_once) <- c("RD", "RR", "OR") result_once_list <- list(result_once) names(result_once_list) <- paste0("ATE", i, j) result_list <- c(result_list, result_once_list) } } if (!is.null(trim_perc)) { method <- paste0(method, "-Trim") } result_list <- c(result_list, list(estimand = "ATE"), method = method) class(result_list) <- "CIMTx_nonIPTW_once" return(result_list) }
/scratch/gouwar.j/cran-all/cranData/CIMTx/R/ce_estimate_rams_ate.R
#' Causal inference with multiple treatments using RAMS for ATE effects #' (bootstrapping for CI) #' #' The function \code{ce_estimate_rams_ate_boot} implements #' RAMS with bootstrapping to estimate ATE effect with #' multiple treatments using observational data. #' #' @param y A numeric vector (0, 1) representing a binary outcome. #' @param w A numeric vector representing the treatment groups. #' @param x A dataframe, including all the covariates but not treatments. #' @param method A character string. Users can selected from the #' following methods including \code{"RAMS-Multinomial"}, #' \code{"RAMS-GBM"}, \code{"RAMS-SL"}. #' @param nboots A numeric value representing the number of bootstrap samples. #' @param verbose_boot A logical value indicating whether to #' print the progress of nonparametric bootstrap. #' @param ... Other parameters that can be passed through to functions. #' #' @return A summary of the effect estimates can be obtained #' with \code{summary} function. #' @importFrom stringr str_sub #' @references #' Hadley Wickham (2019). #' \emph{stringr: Simple, Consistent Wrappers for Common String Operations}. #' R package version 1.4.0. #' URL:\url{https://CRAN.R-project.org/package=stringr} ce_estimate_rams_ate_boot <- function(y, w, x, method, nboots, verbose_boot, ...) { sl_library <- parent.frame()$sl_library n_trt <- length(unique(w)) for (i in 1:n_trt) { assign(paste0("rams_ate_result_", i, "_all"), NULL) } names_result <- NULL # Start bootstrapping for (j in 1:nboots) { bootstrap_id <- sample(length(y), replace = T) y_boot <- y[bootstrap_id] trt_boot <- w[bootstrap_id] x_boot <- x[bootstrap_id, ] rams_ate_result <- ce_estimate_rams_ate( y = y_boot, x = x_boot, w = trt_boot, method = method, ... ) names_result <- names(rams_ate_result) for (i in 1:n_trt) { assign(paste0("rams_ate_result_", i, "_all"), cbind(eval(parse( text = paste0("rams_ate_result_", i, "_all") )), rams_ate_result[[i]])) } if (verbose_boot == TRUE) { print(paste0("Finish bootstrapping ", j)) } } # Save the results of bootstrapping result <- NULL for (i in 1:n_trt) { assign(paste0("RD_", i), list(as.double(eval( parse(text = paste0("rams_ate_result_", i, "_all")) )[1, ]))) assign(paste0("RR_", i), list(as.double(eval( parse(text = paste0("rams_ate_result_", i, "_all")) )[2, ]))) assign(paste0("OR_", i), list(as.double(eval( parse(text = paste0("rams_ate_result_", i, "_all")) )[3, ]))) assign(paste0("RD_", i), stats::setNames(eval(parse(text = ( paste0("RD_", i) ))), paste0( "ATE_RD", stringr::str_sub(names_result[i], 4, 5) ))) assign(paste0("RR_", i), stats::setNames(eval(parse(text = ( paste0("RR_", i) ))), paste0( "ATE_RR", stringr::str_sub(names_result[i], 4, 5) ))) assign(paste0("OR_", i), stats::setNames(eval(parse(text = ( paste0("OR_", i) ))), paste0( "ATE_OR", stringr::str_sub(names_result[i], 4, 5) ))) result <- c(result, (eval(parse(text = ( paste0("RD_", i) )))), (eval(parse(text = ( paste0("RR_", i) )))), (eval(parse(text = ( paste0("OR_", i) ))))) } result <- c(result, list(method = parent.frame()$method)) class(result) <- "CIMTx_ATE_posterior" return(result) }
/scratch/gouwar.j/cran-all/cranData/CIMTx/R/ce_estimate_rams_ate_boot.R
#' Causal inference with multiple treatments using RAMS for ATT effects #' #' The function \code{ce_estimate_rams_att} implements #' RAMS to estimate ATT effect with #' multiple treatments using observational data. #' #' @param y A numeric vector (0, 1) representing a binary outcome. #' @param w A numeric vector representing the treatment groups. #' @param x A dataframe, including all the covariates but not treatments. #' @param method A character string. Users can selected from the #' following methods including \code{"RAMS-Multinomial"}, #' \code{"RAMS-GBM"}, \code{"RAMS-SL"}. #' @param reference_trt A numeric value indicating #' reference treatment group for ATT effect. #' @param ... Other parameters that can be passed through to functions. #' #' @return A summary of the effect estimates can be obtained #' with \code{summary} function. #' @importFrom mgcv gam #' @importFrom nnet multinom #' @importFrom WeightIt weightit #' @references #' Matthew Cefalu, Greg Ridgeway, Dan McCaffrey, Andrew Morral, #' Beth Ann Griffin and Lane Burgette (2021). #' \emph{twang: Toolkit for Weighting and Analysis of Nonequivalent Groups}. #' R package version 2.5. #' URL:\url{https://CRAN.R-project.org/package=twang} #' #' Venables, W. N. & Ripley, B. D. (2002) #' \emph{Modern Applied Statistics with S}. #' Fourth Edition. Springer, New York. ISBN 0-387-95457-0 #' #' Noah Greifer (2021). #' \emph{WeightIt: Weighting for Covariate Balance in Observational Studies}. #' R package version 0.12.0. #' URL:\url{https://CRAN.R-project.org/package=WeightIt} #' #' Wood, S.N. (2011) #' Fast stable restricted maximum likelihood and #' marginal likelihood estimation of semiparametric generalized linear models. #' \emph{Journal of the Royal Statistical Society (B)} \strong{73}(1):3-36 ce_estimate_rams_att <- function(y, w, x, method, reference_trt, ...) { n.trees <- parent.frame()$n.trees interaction.depth <- parent.frame()$interaction.depth n_trt <- length(unique(w)) xwydata <- as.data.frame(cbind(y = y, x, w = w)) xwdata <- as.data.frame(cbind(x, w = w)) trt_indicator <- 1:n_trt trt_indicator_no_reference <- trt_indicator[trt_indicator != reference_trt] n_trt <- length(unique(w)) trim_perc <- parent.frame()$trim_perc for (i in 1:n_trt) { assign(paste0("n", i), sum(w == i)) } if (method == "RAMS-Multinomial" && is.null(trim_perc)) { # Fit a multinomial logistic regression model with # treatment indicator as the outcome psmod2 <- nnet::multinom(w ~ ., data = xwdata, trace = FALSE) pred_ps <- stats::fitted(psmod2) for (i in 1:n_trt) { assign(paste0("ps", i), pred_ps[, i]) } } else if (method == "RAMS-Multinomial-Trim" && !is.null(trim_perc)) { # Fit a multinomial logistic regression model with # treatment indicator as the outcome psmod2 <- nnet::multinom(w ~ ., data = xwdata, trace = FALSE) pred_ps <- stats::fitted(psmod2) # Trim the PS for (i in 1:n_trt) { assign(paste0("ps", i), trunc_fun(pred_ps[, i])) } } else if (method == "RAMS-GBM" && is.null(trim_perc)) { es_max_ate <- NULL # Fit a GBM model with treatment indicator as the outcome temp <- noquote(names(x)) str_formula <- sprintf("w~%s", paste(temp, sep = "", collapse = "+")) psmod <- twang::mnps(stats::as.formula(str_formula), data = xwdata %>% mutate(w = as.factor(w)), ...) for (i in 1:n_trt) { assign(paste0("ps", i), psmod$psList[[i]]$ps %>% pull(es_max_ate)) } } else if (method == "RAMS-GBM-Trim" && !is.null(trim_perc)) { temp <- noquote(names(x)) str_formula <- sprintf("w~%s", paste(temp, sep = "", collapse = "+")) psmod <- twang::mnps(stats::as.formula(str_formula), data = xwdata %>% mutate(w = as.factor(w)), ...) # Trim the PS for (i in 1:n_trt) { assign(paste0("ps", i), trunc_fun(psmod$psList[[i]]$ps %>% pull(es_max_ate))) } } else if (method == "RAMS-SL" && is.null(trim_perc)) { # Fit a SL model with treatment indicator as the outcome sl_library <- parent.frame()$sl_library weightit_superlearner <- WeightIt::weightit(as.factor(w) ~ ., data = xwdata, method = "super", SL.library = sl_library, ...) for (i in 1:n_trt) { assign(paste0("ps", i), 1 / weightit_superlearner$weights) } } else if (method == "RAMS-SL-Trim" && !is.null(trim_perc)) { # Fit a SL model with treatment indicator as the outcome sl_library <- parent.frame()$sl_library weightit_superlearner <- WeightIt::weightit(as.factor(w) ~ ., data = xwdata, method = "super", SL.library = sl_library, ...) # Trim the PS for (i in 1:n_trt) { assign(paste0("ps", i), trunc_fun(1 / weightit_superlearner$weights)) } } # logit of propensity scores logit_ps1 <- NULL logit_ps2 <- NULL for (i in 1:n_trt) { assign(paste0("logit_ps", i), stats::qlogis(eval(parse(text = paste0( "ps", i ))))) } mod_splinedat <- as.data.frame(cbind( w = xwydata$w, logit_ps1 = logit_ps1, logit_ps32 = logit_ps2 )) # Fit a generalized additive model using the treatment indicator and # multivariate spline function of the logit of GPS as the predictors mod_spline <- mgcv::gam( y ~ w + te(logit_ps1, logit_ps2), family = stats::binomial(link = "logit"), data = mod_splinedat ) # Predict the potential outcomes using the fitted GAM model for (i in 1:n_trt) { assign( paste0("newdata", i), data.frame( w = rep(i, sum(w == reference_trt)), logit_ps1 = logit_ps1[w == reference_trt], logit_ps2 = logit_ps2[w == reference_trt] ) ) assign(paste0("spline.pred", i), stats::plogis(stats::predict(mod_spline, newdata = eval( parse(text = paste0("newdata", i)) )))) assign(paste0("y", i, ".hat"), mean(eval(parse( text = paste0("spline.pred", i) )))) } # Estimate the causal effects in terms of OR, RR and RD result_list_rams_att <- NULL for (j in seq_len(length(trt_indicator_no_reference))) { assign( paste0("RD", reference_trt, trt_indicator_no_reference[j]), eval(parse(text = ( paste0("y", reference_trt, ".hat") ))) - eval(parse(text = ( paste0("y", trt_indicator_no_reference[j], ".hat") ))) ) assign( paste0("RR", reference_trt, trt_indicator_no_reference[j]), eval(parse(text = ( paste0("y", reference_trt, ".hat") ))) / eval(parse(text = ( paste0("y", trt_indicator_no_reference[j], ".hat") ))) ) assign(paste0("OR", reference_trt, trt_indicator_no_reference[j]), (eval(parse(text = ( paste0("y", reference_trt, ".hat") ))) / (1 - eval(parse( text = (paste0("y", reference_trt, ".hat")) )))) / (eval(parse(text = ( paste0("y", trt_indicator_no_reference[j], ".hat") ))) / (1 - eval(parse( text = (paste0( "y", trt_indicator_no_reference[j], ".hat" )) ))))) result_once <- rbind(eval(parse( text = paste0("RD", reference_trt, trt_indicator_no_reference[j]) )), eval(parse( text = paste0("RR", reference_trt, trt_indicator_no_reference[j]) )), eval(parse( text = paste0("OR", reference_trt, trt_indicator_no_reference[j]) ))) colnames(result_once) <- "EST" rownames(result_once) <- c("RD", "RR", "OR") result_once_list <- list(result_once) names(result_once_list) <- paste0("ATT", reference_trt, trt_indicator_no_reference[j]) result_list_rams_att <- c(result_list_rams_att, result_once_list) } if (!is.null(trim_perc)) { method <- paste0(method, "-Trim") } result_list_rams_att <- c(result_list_rams_att, list(estimand = "ATT"), method = method) class(result_list_rams_att) <- "CIMTx_nonIPTW_once" return(result_list_rams_att) }
/scratch/gouwar.j/cran-all/cranData/CIMTx/R/ce_estimate_rams_att.R
#' Causal inference with multiple treatments using RAMS for ATT effects #' (bootstrapping for CI) #' #' The function \code{ce_estimate_rams_att_boot} implements #' RAMS with bootstrapping to estimate ATT effect with #' multiple treatments using observational data. #' #' @param y A numeric vector (0, 1) representing a binary outcome. #' @param w A numeric vector representing the treatment groups. #' @param x A dataframe, including all the covariates but not treatments. #' @param reference_trt A numeric value indicating reference treatment group #' for ATT effect. #' @param method A character string. Users can selected from the #' following methods including \code{"RAMS-Multinomial"}, #' \code{"RAMS-GBM"}, \code{"RAMS-SL"}. #' @param nboots A numeric value representing the number of bootstrap samples. #' @param verbose_boot A logical value indicating whether to #' print the progress of nonparametric bootstrap. #' @param ... Other parameters that can be passed through to functions. #' #' @return A summary of the effect estimates can be obtained #' with \code{summary} function. #' @importFrom stringr str_sub #' @references #' Hadley Wickham (2019). #' \emph{stringr: Simple, Consistent Wrappers for Common String Operations}. #' R package version 1.4.0. #' URL:\url{https://CRAN.R-project.org/package=stringr} ce_estimate_rams_att_boot <- function(y, w, x, reference_trt, method, nboots, verbose_boot, ...) { trim_alpha <- parent.frame()$trim_alpha sl_library <- parent.frame()$sl_library n_trt <- length(unique(w)) for (i in 1:n_trt) { assign(paste0("rams_att_result_", i, "_all"), NULL) } # Start bootstrapping names_result <- NULL for (j in 1:nboots) { bootstrap_id <- sample(length(y), replace = T) y_boot <- y[bootstrap_id] trt_boot <- w[bootstrap_id] x_boot <- x[bootstrap_id, ] rams_att_result <- ce_estimate_rams_att( y = y_boot, x = x_boot, w = trt_boot, reference_trt = reference_trt, method = method, ... ) names_result <- names(rams_att_result) for (i in 1:(n_trt - 1)) { assign(paste0("rams_att_result_", i, "_all"), cbind(eval(parse( text = paste0("rams_att_result_", i, "_all") )), rams_att_result[[i]])) } if (verbose_boot == TRUE) { print(paste0("Finish bootstrapping ", j)) } } # Save the results of bootstrapping result <- NULL for (i in 1:(n_trt - 1)) { assign(paste0("RD_", i), list(as.double(eval( parse(text = paste0("rams_att_result_", i, "_all")) )[1, ]))) assign(paste0("RR_", i), list(as.double(eval( parse(text = paste0("rams_att_result_", i, "_all")) )[2, ]))) assign(paste0("OR_", i), list(as.double(eval( parse(text = paste0("rams_att_result_", i, "_all")) )[3, ]))) assign(paste0("RD_", i), stats::setNames(eval(parse(text = ( paste0("RD_", i) ))), paste0( "ATT_RD", stringr::str_sub(names_result[i], 4, 5) ))) assign(paste0("RR_", i), stats::setNames(eval(parse(text = ( paste0("RR_", i) ))), paste0( "ATT_RR", stringr::str_sub(names_result[i], 4, 5) ))) assign(paste0("OR_", i), stats::setNames(eval(parse(text = ( paste0("OR_", i) ))), paste0( "ATT_OR", stringr::str_sub(names_result[i], 4, 5) ))) result <- c(result, (eval(parse(text = ( paste0("RD_", i) )))), (eval(parse(text = ( paste0("RR_", i) )))), (eval(parse(text = ( paste0("OR_", i) ))))) } result <- c(result, list(method = parent.frame()$method)) class(result) <- "CIMTx_ATT_posterior" return(result) }
/scratch/gouwar.j/cran-all/cranData/CIMTx/R/ce_estimate_rams_att_boot.R
#' Causal inference with multiple treatments using TMLE for ATE effects #' #' The function \code{ce_estimate_tmle_ate} implements #' TMLE to estimate ATE effect with #' multiple treatments using observational data. #' #' @param y A numeric vector (0, 1) representing a binary outcome. #' @param w A numeric vector representing the treatment groups. #' @param x A dataframe, including all the covariates but not treatments. #' @param sl_library A character vector of prediction algorithms. #' A list of functions included in the SuperLearner package #' can be found with \code{\link[SuperLearner:listWrappers]{listWrappers}}. #' @param ... Other parameters that can be passed through to functions. #' #' @return A summary of the effect estimates can be obtained #' with \code{summary} function. #' @importFrom dplyr as_tibble mutate case_when select bind_cols #' @import SuperLearner SuperLearner #' @import tmle tmle #' @references #' Hadley Wickham, Romain François, Lionel Henry and Kirill Müller (2021). #' \emph{dplyr: A Grammar of Data Manipulation}. #' R package version 1.0.7. #' URL: \url{https://CRAN.R-project.org/package=dplyr} #' #' Eric Polley, Erin LeDell, Chris Kennedy and Mark van der Laan (2021). #' \emph{SuperLearner: Super Learner Prediction}. #' R package version 2.0-28. #' URL:\url{https://CRAN.R-project.org/package=SuperLearner} #' #' Susan Gruber, Mark J. van der Laan (2012). #' tmle: An R Package for Targeted Maximum Likelihood Estimation. #' \emph{Journal of Statistical Software}, \strong{51}(13), 1-35. ce_estimate_tmle_ate <- function(y, w, x, sl_library, ...) { if (any((sl_library %in% getNamespaceExports("SuperLearner")[ grepl(pattern = "^[S]L", getNamespaceExports("SuperLearner"))]) == F)) stop( "sl_library argument unrecgonized; please use listWrappers() in SuperLearner to find the list of supported values", call. = FALSE ) n_trt <- length(unique(w)) x_mat <- cbind(w, x) for (i in 1:n_trt) { x_mat <- x_mat %>% dplyr::as_tibble() %>% dplyr::mutate(dplyr::case_when(w == i ~ 1, TRUE ~ 0)) %>% as.data.frame() names(x_mat)[length(x_mat)] <- paste0("w", i) } k <- n_trt n <- dim(x_mat)[1] t_mat <- NULL for (i in 1:n_trt) { t_mat_once <- x_mat %>% dplyr::select(paste0("w", i)) t_mat <- dplyr::bind_cols(t_mat, t_mat_once) } w <- x #---------------------------------------------# ### Create Counterfactual Treatment Scenarios### #---------------------------------------------# for (i in 1:n_trt) { assign(paste0("w", i, "_countfactual"), w) } for (j in 1:n_trt) { for (i in 1:n_trt) { if (i == j) { names_w_countfactual <- names(eval(parse(text = ( paste0("w", i, "_countfactual") )))) assign(paste0("w", i, "_countfactual"), eval(parse(text = paste0( "w", i, "_countfactual" ))) %>% dplyr::mutate(1)) assign(paste0("w", i, "_countfactual"), stats::setNames(eval(parse( text = (paste0("w", i, "_countfactual")) )), c( names_w_countfactual, paste0("w", j) ))) } else { names_w_countfactual <- names(eval(parse(text = ( paste0("w", i, "_countfactual") )))) assign(paste0("w", i, "_countfactual"), eval(parse(text = paste0( "w", i, "_countfactual" ))) %>% dplyr::mutate(0)) assign(paste0("w", i, "_countfactual"), stats::setNames(eval(parse( text = (paste0("w", i, "_countfactual")) )), c( names_w_countfactual, paste0("w", j) ))) } } } w_countfactual_combined <- NULL for (i in 1:n_trt) { w_countfactual_combined <- as.data.frame(rbind(w_countfactual_combined, eval(parse( text = paste0("w", i, "_countfactual") )))) } # Run Super Learner Once, Obtain Initial Predicted Values # for All Counterfactual Settings### # Step 1: Estimating the outcome regression using super learner sl_fit <- SuperLearner::SuperLearner( Y = y, X = x_mat[, -1], newX = w_countfactual_combined, SL.library = sl_library, family = stats::binomial(), verbose = FALSE, ... ) q_0 <- rep(0, n * k) q_tvector <- cbind(q_0, sl_fit$SL.predict) q_tmat <- matrix(unlist(split( as.data.frame(q_tvector), rep(1:k, each = n) )), ncol = 2 * k) # Run TMLE to Calculate Point Estimates of each T=t # Steps 2-5 are performed in this code chunk# w_results <- matrix(NA, nrow = k, ncol = 4) w_results_row_names <- NULL for (i in 1:n_trt) { w_results_row_names_once <- paste0("w", i) w_results_row_names <- c(w_results_row_names, w_results_row_names_once) } rownames(w_results) <- w_results_row_names colnames(w_results) <- c("EYt", "SE", "CI1", "CI2") start <- 1 end <- 2 for (t in 1:k) { # Step 2: Super learner fit for P(T_k=t|W) specified with # g.sl_library=sl_library in tmle call# # Steps 3-4: Performed in tmle call, target EYt parameter # using A=NULL and Delta=Tmat[,t]# fit <- tmle::tmle( Y = y, A = NULL, Delta = t_mat[, t], W = w, Q = q_tmat[, c(start, end)], g.SL.library = sl_library, family = "binomial", verbose = FALSE, ... ) # Step 5: The parameter estimates are stored in fit$estimates$EY1$psi# w_results[t, 1] <- fit$estimates$EY1$psi w_results[t, 2] <- fit$estimates$EY1$var.psi w_results[t, 3] <- fit$estimates$EY1$CI[1] w_results[t, 4] <- fit$estimates$EY1$CI[2] start <- start + 2 end <- end + 2 } w_result_one_repetition <- w_results %>% dplyr::as_tibble(rownames = "treatment") result <- list( method = "TMLE", result_TMLE = w_result_one_repetition, estimand = "ATE", n_trt = n_trt ) class(result) <- "CIMTx_nonIPTW_once" return(result) }
/scratch/gouwar.j/cran-all/cranData/CIMTx/R/ce_estimate_tmle_ate.R
#' Causal inference with multiple treatments using TMLE for ATE effects #' (bootstrapping for CI) #' #' @param y A numeric vector (0, 1) representing a binary outcome. #' @param x A dataframe, including all the covariates but not treatments. #' @param w A numeric vector representing the treatment groups. #' @param nboots A numeric value representing the number of bootstrap samples. #' @param verbose_boot A logical value indicating whether to print the #' progress of nonparametric bootstrap. #' @param ... Other parameters that can be passed through to functions. #' #' @return A summary of the effect estimates can be obtained #' with \code{summary} function. #' @importFrom stringr str_sub #' @references #' Hadley Wickham (2019). #' \emph{stringr: Simple, Consistent Wrappers for Common String Operations}. #' R package version 1.4.0. #' URL:\url{https://CRAN.R-project.org/package=stringr} ce_estimate_tmle_ate_boot <- function(y, x, w, nboots, verbose_boot, ...) { # Get the number of treatment group n_trt <- length(unique(w)) for (i in 1:n_trt) { assign(paste0("tmle_multiTrt_ate_result_", i, "_all"), NULL) } names_result <- NULL # Start bootstrapping for (j in 1:nboots) { bootstrap_id <- sample(length(y), replace = T) y_boot <- y[bootstrap_id] w_boot <- w[bootstrap_id] x_boot <- x[bootstrap_id, ] tmle_multitrt_ate_result <- ce_estimate_tmle_ate(y = y_boot, x = x_boot, w = w_boot, ...) tmle_multitrt_ate_result <- summary(tmle_multitrt_ate_result) names_result <- colnames(tmle_multitrt_ate_result) for (i in 1:n_trt) { assign( paste0("tmle_multiTrt_ate_result_", i, "_all"), cbind(eval(parse( text = paste0("tmle_multiTrt_ate_result_", i, "_all") )), tmle_multitrt_ate_result[, i, drop = F]) ) } if (verbose_boot == TRUE) { print(paste0("Finish bootstrapping ", j)) } } # Save the results of bootstrapping result <- NULL for (i in 1:n_trt) { assign(paste0("RD_", i), list(as.double(eval( parse(text = paste0( "tmle_multiTrt_ate_result_", i, "_all" )) )[1, ]))) assign(paste0("RR_", i), list(as.double(eval( parse(text = paste0( "tmle_multiTrt_ate_result_", i, "_all" )) )[2, ]))) assign(paste0("OR_", i), list(as.double(eval( parse(text = paste0( "tmle_multiTrt_ate_result_", i, "_all" )) )[3, ]))) assign(paste0("RD_", i), stats::setNames(eval(parse(text = ( paste0("RD_", i) ))), paste0( "ATE_RD", stringr::str_sub(names_result[i], 4, 5) ))) assign(paste0("RR_", i), stats::setNames(eval(parse(text = ( paste0("RR_", i) ))), paste0( "ATE_RR", stringr::str_sub(names_result[i], 4, 5) ))) assign(paste0("OR_", i), stats::setNames(eval(parse(text = ( paste0("OR_", i) ))), paste0( "ATE_OR", stringr::str_sub(names_result[i], 4, 5) ))) result <- c(result, (eval(parse(text = ( paste0("RD_", i) )))), (eval(parse(text = ( paste0("RR_", i) )))), (eval(parse(text = ( paste0("OR_", i) ))))) } result <- c(result, list(method = parent.frame()$method)) class(result) <- "CIMTx_ATE_posterior" return(result) }
/scratch/gouwar.j/cran-all/cranData/CIMTx/R/ce_estimate_tmle_ate_boot.R
#' Causal inference with multiple treatments using VM for ATT effects #' #' The function \code{ce_estimate_vm_att} implements #' VM to estimate ATT effect with #' multiple treatments using observational data. #' #' @param y A numeric vector (0, 1) representing a binary outcome. #' @param x A dataframe, including all the covariates but not treatments. #' @param w A numeric vector representing the treatment groups. #' @param reference_trt A numeric value indicating reference treatment group #' for ATT effect. #' @param caliper A numeric value denoting the caliper on the logit of #' GPS within each cluster formed by K-means clustering. #' The caliper is in standardized units. #' For example, \code{caliper = 0.25} means that #' all matches greater than 0.25 standard deviations of the #' logit of GPS are dropped. The default value is 0.25. #' @param n_cluster A numeric value denoting the number of clusters to #' form using K means clustering on the logit of GPS. #' #' @return A summary of the effect estimates can be obtained #' with \code{summary} function. The output also contains the number #' of matched individuals. #' @importFrom dplyr filter group_by summarise ungroup inner_join mutate select #' @importFrom nnet multinom #' @importFrom Matching Matchby #' @references #' Venables, W. N. & Ripley, B. D. (2002) #' \emph{Modern Applied Statistics with S}. #' Fourth Edition. Springer, New York. ISBN 0-387-95457-0 #' #' Hadley Wickham, Romain François, Lionel Henry and Kirill Müller (2021). #' \emph{dplyr: A Grammar of Data Manipulation}. #' R package version 1.0.7. #' URL: \url{https://CRAN.R-project.org/package=dplyr} #' #' Jasjeet S. Sekhon (2011). #' Multivariate and Propensity Score Matching Software with A #' utomated Balance Optimization: The Matching Package for R. #' \emph{Journal of Statistical Software}, \strong{42}(7), 1-52 ce_estimate_vm_att <- function(y, x, w, reference_trt, caliper, n_cluster) { n_trt <- length(unique(w)) if (n_trt > 3) { stop("We do not recommend using VM for more than 3 treatments") } # estimate generalized propensity scores using # multinomial logistic regression xwdata <- cbind(w, x) xwdata <- xwdata[order(xwdata$w), ] # Estimate the GPS from the full data using multinomial logistic regressio ps_fit <- nnet::multinom(as.factor(w) ~ ., data = xwdata, trace = FALSE) probs_logit1 <- data.frame(stats::fitted(ps_fit)) colnames_probs_logit1 <- NULL for (i in 1:n_trt) { colnames_probs_logit1_once <- paste0("p", i) colnames_probs_logit1 <- c(colnames_probs_logit1, colnames_probs_logit1_once) } colnames(probs_logit1) <- colnames_probs_logit1 xwdata <- cbind(xwdata, probs_logit1) # Determine eligibility min_max_ps <- NULL for (i in 1:n_trt) { xwdata_summarise_once <- xwdata %>% dplyr::group_by(w) %>% dplyr::summarise(min(eval(parse(text = paste0( "p", i )))), max(eval(parse(text = paste0( "p", i ))))) %>% dplyr::ungroup() names(xwdata_summarise_once)[c(2, 3)] <- c(paste0("min", i), paste0("max", i)) if (i == 1) { min_max_ps <- xwdata_summarise_once } else { min_max_ps <- min_max_ps %>% dplyr::inner_join(xwdata_summarise_once, by = "w") } } # Discard units that fall outside the rectangular region (common # support region) defined by the maximum value of the smallest GPS # and the minimum value of the largest GPS in each treatment group. eligible <- TRUE for (i in 1:n_trt) { eligible_once <- xwdata[[paste0("p", i)]] >= max(min_max_ps[[paste0("min", i)]]) & xwdata[[paste0("p", i)]] <= min(min_max_ps[[paste0("max", i)]]) eligible <- eligible & eligible_once } xwdata <- xwdata %>% dplyr::mutate(eligible = eligible) xwydata <- cbind(y, xwdata) xwydata <- dplyr::filter(xwydata, eligible) # Recalculate the GPS for the inferential units within # the common support region p1 <- NULL; p2 <- NULL; p3 <- NULL ps_fit_e <- nnet::multinom(w ~ ., data = xwydata %>% dplyr::select(-p1, -p2, -p3, -eligible, -y), trace = FALSE) probs_logit1_e <- stats::fitted(ps_fit_e) colnames_probs_logit1_e <- NULL for (i in 1:n_trt) { colnames_probs_logit1_e_once <- paste0("p", i) colnames_probs_logit1_e <- c(colnames_probs_logit1_e, colnames_probs_logit1_e_once) } colnames(probs_logit1_e) <- colnames_probs_logit1_e xwydata <- xwydata %>% dplyr::select(-"p1", -"p2", -"p3") xwydata <- cbind(xwydata, probs_logit1_e) for (i in 1:n_trt) { assign(paste0("n", i), sum(xwydata$w == i)) } # k-means clustering based on the logit GPS for (i in 1:n_trt) { temp_once <- stats::kmeans(stats::qlogis(xwydata[[paste0("p", i)]]), n_cluster) xwydata <- xwydata %>% dplyr::mutate(temp_once$cluster) names(xwydata)[length(names(xwydata))] <- paste0("Quint", i) } treat <- NULL colnames(xwydata)[1:2] <- c("Y_obs", "treat") trt_indicator <- 1:n_trt trt_indicator_no_reference <- trt_indicator[trt_indicator != reference_trt] for (i in seq_len(length(trt_indicator_no_reference))) { assign( paste0("temp", reference_trt, trt_indicator_no_reference[i]), dplyr::filter( xwydata, treat %in% c(reference_trt, trt_indicator_no_reference[i]) ) ) } assign( paste0( "temp", trt_indicator_no_reference[1], trt_indicator_no_reference[2] ), dplyr::filter(xwydata, treat %in% trt_indicator_no_reference) ) # 1:1 matching based on the GPS # Those receiving w = 1 are matched to those receiving w = 2 # using stats::qlogis(temp12$gps1) # within K-means strata of stats::qlogis(xwydata$gps3) # Those receiving w = 1 are matched to those receiving w = 3 # using stats::qlogis(temp13$gps1) # within K-means strata of stats::qlogis(xwydata$gps2) for (i in seq_len(length(trt_indicator_no_reference))) { trt_indicator_left <- trt_indicator[!(trt_indicator %in% c(reference_trt, trt_indicator_no_reference[i]))] assign( paste0("match", reference_trt, trt_indicator_no_reference[i]), Matching::Matchby( Y = eval(parse( text = paste0("temp", reference_trt, trt_indicator_no_reference[i]) ))[["Y_obs"]], Tr = eval(parse( text = paste0("temp", reference_trt, trt_indicator_no_reference[i]) ))[["treat"]] == reference_trt, X = stats::qlogis(eval(parse( text = paste0("temp", reference_trt, trt_indicator_no_reference[i]) ))[[paste0("p", reference_trt)]]), by = eval(parse( text = paste0("temp", reference_trt, trt_indicator_no_reference[i]) ))[[paste0("Quint", trt_indicator_left)]], caliper = caliper, replace = T, estimand = "ATT", print.level = 0 ) ) } # Extract the units receiving w = 1 who were matched to # units receiving w = 2 and w = 3 as well as their matches rownames(xwydata) <- seq_len(nrow(xwydata)) xwydata$id <- seq_len(nrow(xwydata)) eligible_matching <- TRUE for (i in seq_len(length(trt_indicator_no_reference))) { eligible_matching_once <- xwydata$id %in% eval(parse( text = paste0("match", reference_trt, trt_indicator_no_reference[i]) ))[["index.treated"]] eligible_matching <- eligible_matching & eligible_matching_once } if (sum(eligible_matching) == 0) { stop("No eligible matches could be found.") } xwydata$both_1 <- eligible_matching temp <- xwydata[xwydata$both_1 == "TRUE", ] for (i in seq_len(length(trt_indicator_no_reference))) { if (i == 1) { assign( paste0("m", reference_trt, trt_indicator_no_reference[i]), cbind(eval(parse( text = paste0("match", reference_trt, trt_indicator_no_reference[i]) ))[["index.treated"]], eval(parse( text = paste0("match", reference_trt, trt_indicator_no_reference[i]) ))[["index.control"]]) ) } else { trt_indicator_left <- trt_indicator[!(trt_indicator %in% c(reference_trt, trt_indicator_no_reference[i]))] assign( paste0("m", reference_trt, trt_indicator_no_reference[i]), cbind( eval(parse( text = paste0("match", reference_trt, trt_indicator_no_reference[i]) ))[["index.treated"]], eval(parse( text = paste0("match", reference_trt, trt_indicator_no_reference[i]) ))[["index.control"]] + sum(xwydata[["treat"]] == trt_indicator_left) ) ) } } # Identify those who matched with w = 2 and w = 3 for (i in seq_len(length(trt_indicator_no_reference))) { assign(paste0("m", reference_trt, trt_indicator_no_reference[i]), eval(parse( text = paste0("m", reference_trt, trt_indicator_no_reference[i]) ))[eval(parse(text = paste0( "m", reference_trt, trt_indicator_no_reference[i] )))[, 1] %in% rownames(temp), ]) } triplets <- NULL for (i in seq_len(length(trt_indicator_no_reference))) { triplets_once <- eval(parse(text = paste0( "m", reference_trt, trt_indicator_no_reference[i] )))[order(eval(parse( text = paste0("m", reference_trt, trt_indicator_no_reference[i]) ))[, 1]), ] triplets <- cbind(triplets, triplets_once) } triplets <- as.matrix(triplets[, c(1, 2, 4)]) n_trip <- nrow(triplets) # Estimate the ATT effects based on the matched individuals: for (i in 1:3) { assign(paste0("Y", i, "_imp"), xwydata$Y_obs[triplets[, i]]) assign(paste0("y", i, "_hat"), mean(eval(parse( text = paste0("Y", i, "_imp") )))) } for (i in seq_len(length(trt_indicator_no_reference))) { assign( paste0("RD", reference_trt, trt_indicator_no_reference[i], "_est"), eval(parse(text = paste0( "y", reference_trt, "_hat" ))) - eval(parse( text = paste0("y", trt_indicator_no_reference[i], "_hat") )) ) assign( paste0("RR", reference_trt, trt_indicator_no_reference[i], "_est"), eval(parse(text = paste0( "y", reference_trt, "_hat" ))) / eval(parse( text = paste0("y", trt_indicator_no_reference[i], "_hat") )) ) assign( paste0("OR", reference_trt, trt_indicator_no_reference[i], "_est"), (eval(parse( text = paste0("y", reference_trt, "_hat") )) / (1 - eval( parse(text = paste0("y", reference_trt, "_hat")) ))) / (eval(parse( text = paste0("y", trt_indicator_no_reference[i], "_hat") )) / (1 - eval( parse(text = paste0( "y", trt_indicator_no_reference[i], "_hat" )) ))) ) } result_list <- NULL for (j in seq_len(length(trt_indicator_no_reference))) { result_once <- rbind(eval(parse( text = paste0( "round(RD", reference_trt, trt_indicator_no_reference[j], "_est,2)" ) )), eval(parse( text = paste0( "round(RR", reference_trt, trt_indicator_no_reference[j], "_est,2)" ) )), eval(parse( text = paste0( "round(OR", reference_trt, trt_indicator_no_reference[j], "_est,2)" ) ))) colnames(result_once) <- "EST" rownames(result_once) <- c("RD", "RR", "OR") result_once_list <- list(result_once) names(result_once_list) <- paste0("ATT", reference_trt, trt_indicator_no_reference[j]) result_list <- c(result_list, result_once_list) } result_list <- c( result_list, number_matched = n_trip, method = "VM", estimand = "ATT" ) class(result_list) <- "CIMTx_nonIPTW_once" return(result_list) }
/scratch/gouwar.j/cran-all/cranData/CIMTx/R/ce_estimate_vm_att.R
#' Covariate overlap figure #' #' @param treatment A numeric vector representing the treatment groups. #' @param prob Probability of being assigned to the treatment group. #' #' @return A ggplot figure. #' #' @importFrom ggplot2 ggplot aes geom_boxplot ggtitle xlab ylab #' theme_bw ylim theme element_text #' @importFrom cowplot ggdraw draw_label plot_grid #' @references #' H. Wickham. #' \emph{ggplot2: Elegant Graphics for Data Analysis}. #' Springer-Verlag New York, 2016. #' #' Claus O. Wilke (2020). #' \emph{cowplot: Streamlined Plot Theme and Plot Annotations for 'ggplot2'}. #' R package version 1.1.1. #' URL:\url{https://CRAN.R-project.org/package=cowplot} covariate_overlap <- function(treatment, prob) { treatment <- as.factor(treatment) df <- data.frame(cbind(treatment, prob)) plot_list <- list() for (i in seq_len(length(unique(treatment)))) { # gather boxplot for each treatment plot_list[[i]] <- local({ i <- i ggplot2::ggplot(ggplot2::aes( y = prob[, i], x = treatment, group = treatment ), data = df) + ggplot2::geom_boxplot() + ggplot2::ggtitle(bquote( italic(P) ~ "(" ~ italic(W) ~ "=" ~ .(i) ~ "|" ~ bolditalic(X) ~ ")" )) + ggplot2::xlab("Treatment") + ggplot2::ylab("") + ggplot2::theme_bw() }) + ggplot2::ylim(0, 1) + ggplot2::theme(plot.title = ggplot2::element_text(hjust = 0.5)) } # set title title <- cowplot::ggdraw() + cowplot::draw_label( "Covariate Overlap", fontface = "bold", x = 0.42, hjust = 0 ) # if the number of treatment equal or less than 3, # then plot them in a row together if (length(unique(treatment)) <= 3) { cowplot::plot_grid( title, cowplot::plot_grid(plotlist = plot_list, nrow = 1), ncol = 1, rel_heights = c(0.1, 1) ) } else { cowplot::plot_grid( title, cowplot::plot_grid(plotlist = plot_list), ncol = 1, rel_heights = c(0.1, 1) ) } }
/scratch/gouwar.j/cran-all/cranData/CIMTx/R/covariate_overlap.R
#' Simulate data for binary outcome with multiple treatments #' #' The function \code{data_sim} simulate data for binary outcome with #' multiple treatments. Users can adjust the following 7 design factors: #' (1) sample size, (2) ratio of units across treatment groups, #' (3) whether the treatment assignment model and the outcome generating model #' are linear or nonlinear, (4) whether the covariates that best predict #' the treatment also predict the outcome well, #' (5) whether the response surfaces are parallel across treatment groups, #' (6) outcome prevalence, and (7) degree of covariate overlap. #' #' @param sample_size A numeric value indicating the total number of units. #' @param n_trt A numeric value indicating the number of treatments. #' The default is set to 3. #' @param x A vector of characters representing covariates, #' with each covariate being generated from the standard probability. #' The default is set to "rnorm(0, 1)". #' \code{\link[stats:Distributions]{distributions}} in the #' \code{\link[stats:stats-package]{stats}} package. #' @param lp_y A vector of characters of length \code{n_trt}, #' representing the linear effects in the outcome generating model. #' The default is set to rep("x1", 3). #' @param nlp_y A vector of characters of length \code{n_trt}, #' representing the nonlinear effects in the outcome generating model. #' The default is set to NULL. #' @param align A logical indicating whether the predictors in the #' treatment assignment model are the same as the predictors for #' the outcome generating model. #' The default is \code{TRUE}. If the argument is set to \code{FALSE}, #' users need to specify additional two arguments \code{lp_w} and \code{nlp_w}. #' @param tau A numeric vector of length \code{n_trt} inducing different #' outcome event probabilities across treatment groups. #' Higher values mean higher outcome event probability for the treatment group; #' lower values mean lower outcome event probability for the treatment group. #' The default is set to c(0, 0, 0), which corresponds to an #' approximately equal outcome event probability across three treatment groups. #' @param delta A numeric vector of length \code{n_trt}-1 inducing different #' ratio of units across treatment groups. #' Higher values mean higher proportion for the treatment group; #' lower values mean lower proportion for the treatment group. #' The default is set to c(0,0), which corresponds to an approximately #' equal sample sizes across three treatment groups. #' @param psi A numeric value for the parameter governing the sparsity #' of covariate overlap. Higher values mean weaker covariate overlap; #' lower values mean stronger covariate overlap. The default is set to 1, #' which corresponds to a moderate covariate overlap. #' @param lp_w is a vector of characters of length \code{n_trt} - 1, #' representing in the treatment assignment model #' @param nlp_w is a vector of characters of length \code{n_trt} - 1, #' representing in the treatment assignment model #' #' @import dplyr #' #' @return A list with 7 elements for simulated data. It contains #' \item{covariates:}{x matrix} #' \item{w:}{treatment indicators} #' \item{y:}{observed binary outcomes} #' \item{y_prev:}{outcome prevalence rates} #' \item{ratio_of_units:}{the proportions of units in each treatment group} #' \item{overlap_fig:}{the visualization of covariate overlap #' via boxplots of the distributions of true GPS} #' \item{y_true:}{simulated true outcome in each treatment group} #' @importFrom stringr str_locate str_sub str_locate #' @importFrom dplyr mutate #' @export #' #' @references #' #' Hadley Wickham (2019). #' \emph{stringr: Simple, Consistent Wrappers for Common String Operations}. #' R package version 1.4.0. #' URL:\url{https://CRAN.R-project.org/package=stringr} #' #' Hadley Wickham, Romain François, #' Lionel Henry and Kirill Müller (2021). #' \emph{dplyr: A Grammar of Data Manipulation}. #' R package version 1.0.7. #' URL: \url{https://CRAN.R-project.org/package=dplyr} #' @examples #' library(CIMTx) #' lp_w_all <- #' c( #' ".4*x1 + .1*x2 - .1*x4 + .1*x5", # w = 1 #' ".2 * x1 + .2 * x2 - .2 * x4 - .3 * x5" #' ) # w = 2 #' nlp_w_all <- #' c( #' "-.5*x1*x4 - .1*x2*x5", # w = 1 #' "-.3*x1*x4 + .2*x2*x5" #' ) # w = 2 #' lp_y_all <- rep(".2*x1 + .3*x2 - .1*x3 - .1*x4 - .2*x5", 3) #' nlp_y_all <- rep(".7*x1*x1 - .1*x2*x3", 3) #' X_all <- c( #' "rnorm(0, 0.5)", # x1 #' "rbeta(2,0.4)", # x2 #' "runif(0, 0.5)", # x3 #' "rweibull(1,2)", # x4 #' "rbinom(1,0.4)" # x5 #' ) #' #' set.seed(111111) #' data <- data_sim( #' sample_size = 300, #' n_trt = 3, #' x = X_all, #' lp_y = lp_y_all, #' nlp_y = nlp_y_all, #' align = FALSE, #' lp_w = lp_w_all, #' nlp_w = nlp_w_all, #' tau = c(-1.5, 0, 1.5), #' delta = c(0.5, 0.5), #' psi = 1 #' ) data_sim <- function(sample_size, n_trt = 3, x = "rnorm(0, 1)", lp_y = rep("x1", 3), nlp_y = NULL, align = TRUE, tau = c(0, 0, 0), delta = c(0, 0), psi = 1, lp_w, nlp_w) { if (align == TRUE) { lp_w <- lp_y nlp_w <- nlp_y } if (is.null(lp_y)) { lp_y <- rep(0, n_trt) } if (is.null(nlp_y)) { nlp_y <- rep(0, n_trt) } if (is.null(lp_w)) { lp_w <- rep(0, n_trt) } if (is.null(nlp_w)) { nlp_w <- rep(0, n_trt) } for (i in seq_len(length(x))) { str_locate_parenthesis <- stringr::str_locate(x[i], "\\(") assign(paste0("x", i), eval(parse(text = paste0( paste0( stringr::str_sub(x[i], 1, str_locate_parenthesis[1]), sample_size, ",", stringr::str_sub(x[i], str_locate_parenthesis[1] + 1) ) )))) } x_matrix <- matrix(NA, nrow = sample_size, ncol = length(x)) for (i in 1:dim(x_matrix)[2]) { x_matrix[, i] <- eval(parse(text = paste0("x", i))) } treatment_exp_matrix_all <- NULL for (i in 1:(n_trt - 1)) { treatment_exp_matrix <- exp(eval(parse( text = paste0(psi, "*(", delta[i], "+", lp_w[i], "+", nlp_w[i], ")") ))) treatment_exp_matrix_all <- cbind(treatment_exp_matrix_all, treatment_exp_matrix) } treatment_exp_matrix_all[is.infinite(treatment_exp_matrix_all)] <- 10 ^ 8 probs <- sweep(treatment_exp_matrix_all, 1, (rowSums(treatment_exp_matrix_all) + 1), "/") prob_last_all <- rep(NA, dim(probs)[1]) for (i in 1:dim(probs)[1]) { prob_last_all[i] <- 1 - sum(probs[i, ]) } probs_all <- cbind(probs, prob_last_all) w <- rep(NA, dim(probs)[1]) for (i in 1:dim(probs)[1]) { w[i] <- sample( x = 1:n_trt, size = 1, prob = c(probs[i, ], 1 - sum(probs[i, ])), replace = TRUE ) } w for (i in 1:n_trt) { assign(paste0("Y", i, "_final"), NULL) } for (j in 1:n_trt) { assign(paste0("y", j), stats::plogis(eval(parse( text = paste0(tau[j], "+", lp_y[j], "+", nlp_y[j]) )))) } for (j in 1:n_trt) { assign(paste0("Y", j, "_final"), stats::rbinom( n = sample_size, size = 1, prob = eval(parse(text = paste0("y", j))) )) } y_true <- matrix(NA, nrow = sample_size, ncol = n_trt) for (i in 1:n_trt) { y_true[, i] <- eval(parse(text = paste0("Y", i, "_final"))) } y_true_with_treatment <- cbind(y_true, w) # observed outcomes y_obs <- apply(y_true_with_treatment, 1, function(x) x[1:n_trt][x[n_trt + 1]]) y_prev <- tibble(w = as.character(w), y_obs) %>% group_by(w) %>% summarise(y_prev = mean(y_obs)) %>% bind_rows(tibble(w = "Overall", y_prev = mean(y_obs))) %>% dplyr::mutate(y_prev = round(y_prev, 2)) %>% as.data.frame() p_covariate_overlap <- covariate_overlap(treatment = w, prob = probs_all) covariates <- as.data.frame(x_matrix) names(covariates) <- paste0("x", seq_len(length(x))) return( list( covariates = covariates, w = w, y = y_obs, y_prev = y_prev, ratio_of_units = round(table(w) / length(w), 2), overlap_fig = p_covariate_overlap, y_true = y_true ) ) }
/scratch/gouwar.j/cran-all/cranData/CIMTx/R/data_sim.R
#' Plot for non-IPTW estimation methods with bootstrapping for ATE effect #' #' @param x a \code{CIMTx_ATE_posterior} object obtained #' @param ... further arguments passed to or from other methods. #' #' @return an error message #' @export #' #' @examples #' \dontrun{ #' result <- list(method = "RA") #' class(result) <- "CIMTx_ATE_posterior" #' plot(result) #' } plot.CIMTx_ATE_posterior <- function(x, ...) { if (x$method %in% c("IPTW-Multinomial", "IPTW-GBM", "IPTW-SL")) { stop( "Plot function is not supported for estimation method using ", x$method, " when boot is set to TRUE. Plot function is only supported", " for estimation method using IPTW when boot is set to FALSE." ) } else { stop( "Plot function is not supported for estimation method using ", x$method, ". Plot function is only supported for estimation method using", " IPTW when boot is set to FALSE." ) } }
/scratch/gouwar.j/cran-all/cranData/CIMTx/R/plot.CIMTx_ATE_posterior.R
#' Plot for non-IPTW estimation methods for ATT effect #' #' @param x a \code{CIMTx_ATT_posterior} object obtained #' @param ... further arguments passed to or from other methods. #' #' @return an error message #' @export #' #' @examples #' \dontrun{ #' result <- list(method = "RA") #' class(result) <- "CIMTx_ATT_posterior" #' plot(result) #' } plot.CIMTx_ATT_posterior <- function(x, ...) { if (x$method %in% c("IPTW-Multinomial", "IPTW-GBM", "IPTW-SL")) { stop( "Plot function is not supported for estimation method using ", x$method, " when boot is set to TRUE. Plot function is only supported for", " estimation method using IPTW when boot is set to FALSE." ) } else { stop( "Plot function is not supported for estimation method using ", x$method, ". Plot function is only supported for estimation method using", " IPTW when boot is set to FALSE." ) } }
/scratch/gouwar.j/cran-all/cranData/CIMTx/R/plot.CIMTx_ATT_posterior.R
#' Boxplot for weight distribution #' #' This function make the boxplot plot for the weights estimated by #' different IPTW methods. #' The inputs of the function are from the output of ce_estimate.R function #' when the methods are "IPTW-Multinomial", "IPTW-GBM", "IPTW-SL". #' #' @param ... Objects from IPTW related methods #' #' @return A ggplot figure #' @importFrom stringr str_detect #' @importFrom dplyr mutate #' @importFrom ggplot2 ggplot geom_boxplot scale_fill_manual #' facet_wrap labs theme_bw theme element_blank #' @importFrom cowplot plot_grid get_legend #' @export #' #' @references #' Hadley Wickham (2019). #' \emph{stringr: Simple, Consistent Wrappers for Common String Operations}. #' R package version 1.4.0. #' URL:\url{https://CRAN.R-project.org/package=stringr} #' #' Hadley Wickham, Romain François, Lionel Henry and Kirill Müller (2021). #' \emph{dplyr: A Grammar of Data Manipulation}. #' R package version 1.0.7. #' URL: \url{https://CRAN.R-project.org/package=dplyr} #' #' H. Wickham. \emph{ggplot2: Elegant Graphics for Data Analysis}. #' Springer-Verlag New York, 2016. #' #' Claus O. Wilke (2020). #' \emph{cowplot: Streamlined Plot Theme and Plot Annotations for 'ggplot2'}. #' R package version 1.1.1. #' URL:\url{https://CRAN.R-project.org/package=cowplot} #' @examples #' iptw_object_example <- list(weight = rnorm(1000, 1, 1), method = "IPTW-SL") #' class(iptw_object_example) <- "CIMTx_IPTW" #' plot(iptw_object_example) plot.CIMTx_IPTW <- function(...) { iptw_object <- list(...) weight <- NULL method <- NULL weight_all <- NULL method_all <- NULL trim <- NULL for (i in seq_len(length(iptw_object))) { weight_all <- c(weight_all, iptw_object[[i]]$weight) method_all <- c(method_all, rep(iptw_object[[i]]$method, length(iptw_object[[i]]$weight))) } boxplot_figure_data <- data.frame(weight = weight_all, method = method_all) if (any(stringr::str_detect(method_all, "Trim")) == TRUE && length(unique(method_all)) == 6) { boxplot_figure_data <- boxplot_figure_data %>% dplyr::mutate(trim = ifelse( stringr::str_detect(method_all, "Trim"), "(b) trimmed weights", "(a) untrimmed weights" )) boxplot_figure_data_reordered <- boxplot_figure_data %>% dplyr::mutate(method = factor( method, levels = c( "IPTW-Multinomial", "IPTW-SL", "IPTW-GBM", "IPTW-Multinomial-Trim", "IPTW-SL-Trim", "IPTW-GBM-Trim" ) )) boxplot_figure_main <- ggplot2::ggplot(ggplot2::aes(x = method, y = weight, fill = method), data = boxplot_figure_data_reordered) + ggplot2::geom_boxplot() + ggplot2::scale_fill_manual(values = c( "#CCCCCC", "#4D4D4D", "white", "#CCCCCC", "#4D4D4D", "white" )) + ggplot2::facet_wrap(~ trim, scales = "free_x") + ggplot2::labs(color = "", y = "Weights", x = "") + ggplot2::theme_bw() + ggplot2::theme( legend.position = "none", axis.title.x = ggplot2::element_blank(), axis.text.x = ggplot2::element_blank(), axis.ticks.x = ggplot2::element_blank() ) boxplot_figure_data_for_legend <- boxplot_figure_data %>% dplyr::mutate(method = ifelse( trim == "(b) trimmed weights", stringr::str_sub(method, 1, -6), method )) %>% dplyr::mutate(method = factor( method, levels = c("IPTW-Multinomial", "IPTW-SL", "IPTW-GBM") )) boxplot_figure_legend <- ggplot2::ggplot(ggplot2::aes(x = method, y = weight, fill = method), data = boxplot_figure_data_for_legend) + ggplot2::geom_boxplot() + ggplot2::scale_fill_manual(values = c( "#CCCCCC", "#4D4D4D", "white", "#CCCCCC", "#4D4D4D", "white" )) + ggplot2::facet_wrap(~ trim, scales = "free_x") + ggplot2::labs(color = "", y = "Weights", fill = "") + ggplot2::theme_bw() + ggplot2::theme(legend.position = "top") boxplot_figure <- cowplot::plot_grid( cowplot::get_legend(boxplot_figure_legend), boxplot_figure_main, rel_heights = c(0.1, 0.9), nrow = 2 ) } else { boxplot_figure <- ggplot2::ggplot(ggplot2::aes(x = method, y = weight, fill = method), data = boxplot_figure_data) + ggplot2::geom_boxplot() + ggplot2::scale_fill_manual(values = c( "#CCCCCC", "#4D4D4D", "white", "#CCCCCC", "#4D4D4D", "white" )) + ggplot2::labs(color = "", y = "Weights", fill = "") + ggplot2::theme_bw() + ggplot2::theme(legend.position = "top") } return(boxplot_figure) }
/scratch/gouwar.j/cran-all/cranData/CIMTx/R/plot.CIMTx_IPTW.R
#' Plot for non-IPTW estimation methods for ATE effect #' #' @param x a \code{CIMTx_nonIPTW_once} object obtained #' @param ... further arguments passed to or from other methods. #' #' @return an error message #' @export #' #' @examples #' \dontrun{ #' result <- list(method = "TMLE") #' class(result) <- "CIMTx_nonIPTW_once" #' plot(result) #' } plot.CIMTx_nonIPTW_once <- function(x, ...) { stop( "Plot function is not supported for estimation method using ", x$method, ". Plot function is only supported for estimation method using IPTW" ) }
/scratch/gouwar.j/cran-all/cranData/CIMTx/R/plot.CIMTx_nonIPTW_once.R
#' Contour plot for the grid specification of sensitivity analysis #' #' This function make the countor plot after the grid specification #' of sensitivity analysis. #' The input of the function is from the output of the sa.R function. #' #' @param x Object from sa function #' @param ate a character indicating the ATE effect to plot, #' eg, "1,3" or "2,3" #' @param att a character indicating the ATT effect to plot, #' eg, "1,3" or "1,2" #' @param ... further arguments passed to or from other methods. #' #' @return A ggplot figure #' @importFrom stringr str_sub #' @importFrom ggplot2 ggplot aes_string geom_contour #' labs theme element_text theme_bw #' @importFrom metR geom_text_contour #' @export #' #' @references #' #' Hadley Wickham (2019). #' \emph{stringr: Simple, Consistent Wrappers for Common String Operations}. #' R package version 1.4.0. #' URL:\url{https://CRAN.R-project.org/package=stringr} #' #' Elio Campitelli (2021). #' \emph{metR: Tools for Easier Analysis of Meteorological Fields}. #' R package version 0.11.0. #' URL:\url{https://github.com/eliocamp/metR} #' #' @examples #' sa_object_example <- list( #' ATE13 = seq(0, 1, length.out = 25), grid_index = c(4, 5), #' c_functions = data.frame( #' c4 = rep(seq(-0.6, 0, 0.15), each = 5), #' c5 = rep(seq(0, 0.6, 0.15), 5) #' ) #' ) #' class(sa_object_example) <- "CIMTx_sa_grid" #' plot(sa_object_example, ate = "1,3") plot.CIMTx_sa_grid <- function(x, ate = NULL, att = NULL, ...) { if (!is.null(ate)) { estimand <- paste0("ATE", as.numeric(gsub("\\,", "", ate))) m <- stringr::str_sub(ate, 1, 1) n <- stringr::str_sub(ate, 3, 3) plot_data <- x$c_functions %>% as.data.frame() %>% select(paste0("c", x$grid_index)) %>% mutate(estimand = x[[estimand]]) plot_result <- plot_data %>% ggplot2::ggplot(ggplot2::aes_string( x = names(plot_data)[1], y = names(plot_data)[2], z = names(plot_data)[3] )) + ggplot2::geom_contour() + metR::geom_text_contour() + ggplot2::labs( x = bquote(italic(c) ~ "(" ~ .(m) ~ "," ~ .(n) ~ ")"), y = bquote(italic(c) ~ "(" ~ .(n) ~ "," ~ .(m) ~ ")"), title = bquote(ATE[.(m) ~ "," ~ .(n)]) ) + ggplot2::theme(plot.title = ggplot2::element_text(hjust = 0.5)) + ggplot2::theme_bw() + ggplot2::theme(plot.title = ggplot2::element_text(hjust = 0.5)) return(plot_result) } if (!is.null(att)) { estimand <- paste0("ATT", as.numeric(gsub("\\,", "", att))) m <- stringr::str_sub(att, 1, 1) n <- stringr::str_sub(att, 3, 3) plot_data <- x$c_functions %>% as.data.frame() %>% select(paste0("c", x$grid_index)) %>% mutate(estimand = x[[estimand]]) plot_result <- plot_data %>% ggplot2::ggplot(ggplot2::aes_string( x = names(plot_data)[1], y = names(plot_data)[2], z = names(plot_data)[3] )) + ggplot2::geom_contour() + metR::geom_text_contour() + ggplot2::labs( x = bquote(italic(c) ~ "(" ~ .(m) ~ "," ~ .(n) ~ ")"), y = bquote(italic(c) ~ "(" ~ .(n) ~ "," ~ .(m) ~ ")"), title = bquote(ATT[.(m) ~ "," ~ .(n)]) ) + ggplot2::theme(plot.title = ggplot2::element_text(hjust = 0.5)) + ggplot2::theme_bw() + ggplot2::theme(plot.title = ggplot2::element_text(hjust = 0.5)) return(plot_result) } }
/scratch/gouwar.j/cran-all/cranData/CIMTx/R/plot.CIMTx_sa_grid.R
#' Posterior distribution summary #' #' @param rd_est Posterior distribution for rd estimates. #' @param rr_est Posterior distribution for rr estimates. #' @param or_est Posterior distribution for rr estimates. #' #' @return A list of causal estimands including risk difference (rd), #' odds ratios (or) and relative risk (rr) #' between different treatment groups. posterior_summary <- function(rd_est, rr_est, or_est) { # Risk difference (rd) rd_mean <- mean(rd_est) rd_se <- stats::sd(rd_est) rd_lower <- stats::quantile(rd_est, probs = 0.025, na.rm = T) rd_upper <- stats::quantile(rd_est, probs = 0.975, na.rm = T) # Relative risk (rr) rr_mean <- mean(rr_est) rr_se <- stats::sd(rr_est) rr_lower <- stats::quantile(rr_est, probs = 0.025, na.rm = T) rr_upper <- stats::quantile(rr_est, probs = 0.975, na.rm = T) # Odds ratio (or) or_mean <- mean(or_est) or_se <- stats::sd(or_est) or_lower <- stats::quantile(or_est, probs = 0.025, na.rm = T) or_upper <- stats::quantile(or_est, probs = 0.975, na.rm = T) # summarize results rd <- c(rd_mean, rd_se, rd_lower, rd_upper) rr <- c(rr_mean, rr_se, rr_lower, rr_upper) or <- c(or_mean, or_se, or_lower, or_upper) res <- rbind(rd, rr, or) rownames(res) <- c("RD", "RR", "OR") colnames(res) <- c("EST", "SE", "LOWER", "UPPER") return(res) }
/scratch/gouwar.j/cran-all/cranData/CIMTx/R/posterior_summary.R
#' Print the ATE results for non-IPTW results #' #' The \code{\link{print}} method for class "CIMTx_ATE_posterior" #' #' @param x a \code{CIMTx_ATE_posterior} object obtained #' from \code{\link{ce_estimate}} function #' @param ... further arguments passed to or from other methods. #' #' @return The output from \code{\link{print}} #' @export #' #' @examples #' result <- list(method = "RA") #' class(result) <- "CIMTx_ATE_posterior" #' print(result) print.CIMTx_ATE_posterior <- function(x, ...) { if (x$method %in% c("RA", "BART")) { cat( "This is ATE results from estimation method", x$method, "with confidence interval estimated by Bayesian posterior samples.", "For effect estimates, please use summary function." ) } else { cat( "This is ATE results from estimation method", x$method, "with confidence interval estimated by bootstrapping.", " For effect estimates, please use summary function." ) } }
/scratch/gouwar.j/cran-all/cranData/CIMTx/R/print.CIMTx_ATE_posterior.R
#' Print the ATE results for from sensitivity analysis #' #' The \code{\link{print}} method for class "CIMTx_ATE_sa" #' #' @param x a \code{CIMTx_ATE_sa} object obtained #' from \code{\link{sa}} function #' @param ... further arguments passed to or from other methods. #' #' @return The output from \code{\link{print}} #' @export #' #' @examples #' result <- list(estimand = "ATE") #' class(result) <- "CIMTx_ATE_sa" #' print(result) print.CIMTx_ATE_sa <- function(x, ...) { cat( "This is sa results using CIMTx pakcage", "For effect estimates, please use summary function." ) }
/scratch/gouwar.j/cran-all/cranData/CIMTx/R/print.CIMTx_ATE_sa.R
#' Print the ATT results #' #' The \code{\link{print}} method for class "CIMTx_ATT_posterior" #' #' @param x a \code{CIMTx_ATT_posterior} x obtained #' from \code{\link{ce_estimate}} function #' @param ... further arguments passed to or from other methods. #' #' @return The output from \code{\link{print}} #' @export #' #' @examples #' result <- list(method = "RA") #' class(result) <- "CIMTx_ATT_posterior" #' print(result) print.CIMTx_ATT_posterior <- function(x, ...) { if (x$method %in% c("RA", "BART")) { cat( "This is ATT results from estimation method", x$method, "with confidence interval estimated by", " Bayesian posterior samples.", " For effect estimates, please use summary function." ) } else { cat( "This is ATT results from estimation method", x$method, "with confidence interval estimated by", " bootstrapping. For effect estimates", " please use summary function." ) } }
/scratch/gouwar.j/cran-all/cranData/CIMTx/R/print.CIMTx_ATT_posterior.R
#' Print the ATT results for from sensitivity analysis #' #' The \code{\link{print}} method for class "CIMTx_ATT_sa" #' #' @param x a \code{CIMTx_ATT_sa} object obtained #' from \code{\link{sa}} function #' @param ... further arguments passed to or from other methods. #' #' @return The output from \code{\link{print}} #' @export #' #' @examples #' result <- list(estimand = "ATT") #' class(result) <- "CIMTx_ATT_sa" #' print(result) print.CIMTx_ATT_sa <- function(x, ...) { cat( "This is sa results using CIMTx pakcage", "For effect estimates, please use summary function." ) }
/scratch/gouwar.j/cran-all/cranData/CIMTx/R/print.CIMTx_ATT_sa.R
#' Print the ATE/ATT results for IPTW results #' #' The \code{\link{print}} method for class "CIMTx_IPTW" #' #' @param x a \code{CIMTx_ATE_posterior} x obtained #' @param ... further arguments passed to or from other methods. #' #' @return The output from \code{\link{print}} #' @export #' #' @examples #' result <- list(method = "IPTW-Multinomial", estimand = "ATE") #' class(result) <- "CIMTx_IPTW" #' print(result) print.CIMTx_IPTW <- function(x, ...) { cat( "This is", x$estimand, "results from estimation method", x$method, "using CIMTx. For effect estimates,", "please use summary function.", "To visualize weight,", "please use plot function." ) }
/scratch/gouwar.j/cran-all/cranData/CIMTx/R/print.CIMTx_IPTW.R
#' Print the ATE/ATT results for non-IPTW results #' #' The \code{\link{print}} method for class "CIMTx_nonIPTW_once" #' #' @param x a \code{CIMTx_ATE_posterior} x obtained #' from \code{\link{ce_estimate}} function #' @param ... further arguments passed to or from other methods. #' #' @return The output from \code{\link{print}} #' @export #' #' @examples #' result <- list(method = "TMLE", estimand = "ATE") #' class(result) <- "CIMTx_nonIPTW_once" #' print(result) print.CIMTx_nonIPTW_once <- function(x, ...) { cat( "This is", x$estimand, "results from estimation method", x$method, "using CIMTx. For effect estimates,", "please use summary function." ) }
/scratch/gouwar.j/cran-all/cranData/CIMTx/R/print.CIMTx_nonIPTW_once.R
#' Print the ATT results for from sensitivity analysis #' #' The \code{\link{print}} method for class "CIMTx_sa_grid" #' #' @param x a \code{CIMTx_sa_grid} object obtained from #' \code{\link{sa}} function #' @param ... further arguments passed to or from other methods. #' #' @return The output from \code{\link{print}} #' @export #' #' @examples #' result <- list(estimand = "ATE") #' class(result) <- "CIMTx_sa_grid" #' print(result) print.CIMTx_sa_grid <- function(x, ...) { cat( "This is sa results using CIMTx pakcage", "when the c functions involves a range of point mass priors", "To visualize effect estimates, please plot function." ) }
/scratch/gouwar.j/cran-all/cranData/CIMTx/R/print.CIMTx_sa_grid.R
#' Flexible Monte Carlo sensitivity analysis for unmeasured confounding #' #' The function \code{sa} implements the flexible sensitivity analysis #' approach for unmeasured confounding with multiple treatments #' and a binary outcome. #' #' @param y A numeric vector (0, 1) representing a binary outcome. #' @param x A dataframe, including all the covariates but not treatments. #' @param w A numeric vector representing the treatment groups. #' @param formula A \code{\link[stats]{formula}} object for the analysis. #' The default is to use all terms specified in \code{x}. #' @param prior_c_function 1) A vector of characters indicating the #' prior distributions for the confounding functions. #' Each character contains the random number generation code #' from the standard probability #' \code{\link[stats:Distributions]{distributions}} #' in the \code{\link[stats:stats-package]{stats}} package. #' 2) A vector of characters including the grid specifications for #' the confounding functions. It should be used when users want to formulate #' the confounding functions as scalar values. #' 3) A matrix indicating the point mass prior for the confounding functions #' @param m1 A numeric value indicating the number of draws of the GPS #' from the posterior predictive distribution #' @param m2 A numeric value indicating the number of draws from #' the prior distributions of the confounding functions #' @param n_cores A numeric value indicating number of cores to use #' for parallel computing. #' @param estimand A character string representing the type of #' causal estimand. Only \code{"ATT"} or \code{"ATE"} is allowed. #' When the \code{estimand = "ATT"}, users also need to specify the #' reference treatment group by setting the \code{reference_trt} argument. #' @param reference_trt A numeric value indicating reference treatment group #' for ATT effect. #' @param ... Other parameters that can be passed to BART functions #' #' @return A list of causal estimands including risk difference (RD) #' between different treatment groups. #' #' @export #' @importFrom foreach %dopar% foreach #' @importFrom stringr str_detect str_locate str_sub #' @importFrom tidyr expand_grid #' @importFrom BART mbart2 wbart pwbart #' @importFrom parallel makeCluster stopCluster #' @importFrom doParallel registerDoParallel #' @references #' #' Hadley Wickham (2019). #' \emph{stringr: Simple, Consistent Wrappers for Common String Operations}. #' R package version 1.4.0. #' URL:\url{https://CRAN.R-project.org/package=stringr} #' #' Hadley Wickham (2021). #' \emph{tidyr: Tidy Messy Data}. #' R package version 1.1.4. #'URL:\url{https://CRAN.R-project.org/package=tidyr} #' #' Sparapani R, Spanbauer C, McCulloch R #' Nonparametric Machine Learning and #' Efficient Computation with Bayesian Additive Regression Trees: #' The BART R Package. \emph{Journal of Statistical Software}, #' \strong{97}(1), 1-66. #' #' Microsoft Corporation and Steve Weston (2020). #' \emph{doParallel: Foreach Parallel Adaptor for the 'parallel' Package}. #' R package version 1.0.16. #' URL:\url{https://CRAN.R-project.org/package=doParallel} #' #' Microsoft and Steve Weston (2020). #' \emph{foreach: Provides Foreach Looping Construct.}. #' R package version 1.5.1 #' URL:\url{https://CRAN.R-project.org/package=foreach} #' @examples #' \donttest{ #' lp_w_all <- #' c( #' ".4*x1 + .1*x2 - 1.1*x4 + 1.1*x5", # w = 1 #' ".2 * x1 + .2 * x2 - 1.2 * x4 - 1.3 * x5" #' ) # w = 2 #' nlp_w_all <- #' c( #' "-.5*x1*x4 - .1*x2*x5", # w = 1 #' "-.3*x1*x4 + .2*x2*x5" #' ) # w = 2 #' lp_y_all <- rep(".2*x1 + .3*x2 - .1*x3 - 1.1*x4 - 1.2*x5", 3) #' nlp_y_all <- rep(".7*x1*x1 - .1*x2*x3", 3) #' X_all <- c( #' "rnorm(0, 0.5)", # x1 #' "rbeta(2, .4)", # x2 #' "runif(0, 0.5)", # x3 #' "rweibull(1,2)", # x4 #' "rbinom(1, .4)" # x5 #' ) #' set.seed(1111) #' data <- data_sim( #' sample_size = 100, #' n_trt = 3, #' x = X_all, #' lp_y = lp_y_all, #' nlp_y = nlp_y_all, #' align = FALSE, #' lp_w = lp_w_all, #' nlp_w = nlp_w_all, #' tau = c(0.5, -0.5, 0.5), #' delta = c(0.5, 0.5), #' psi = 2 #' ) #' c_grid <- c( #' "runif(-0.6, 0)", # c(1,2) #' "runif(0, 0.6)", # c(2,1) #' "runif(-0.6, 0)", # c(2,3) #' "seq(-0.6, 0, by = 0.3)", # c(1,3) #' "seq(0, 0.6, by = 0.3)", # c(3,1) #' "runif(0, 0.6)" # c(3,2) #' ) #' sensitivity_analysis_parallel_result <- #' sa( #' m1 = 1, #' x = data$covariates, #' y = data$y, #' w = data$w, #' prior_c_function = c_grid, #' n_cores = 1, #' estimand = "ATE", #' ) #' } sa <- function(x, y, w, formula = NULL, prior_c_function, m1, m2 = NULL, n_cores = 1, estimand, reference_trt, ...) { # First check the user's inputs if (!(estimand %in% c("ATE", "ATT"))) stop("Estimand only supported for \"ATT\" or \"ATE\"", call. = FALSE) if (estimand == "ATT" && !(reference_trt %in% unique(w))) stop(paste0( "Please set the reference_trt from ", paste0(sort(unique(w)), collapse = ", "), "." ), call. = FALSE) if (sum(c( length(w) == length(y), length(w) == nrow(x), length(y) == nrow(x) )) != 3) stop( paste0( "The length of y, the length of w and the nrow for x should be equal. Please double check the input." ), call. = FALSE ) if (!is.null(formula)) { x <- as.data.frame(stats::model.matrix(object = formula, cbind(y, x))) x <- x[, !(names(x) == "(Intercept)")] } # When the confounding function is a full prior with uncertainty specified # and without a range of point mass priors if (any(stringr::str_detect(prior_c_function, "seq")) == FALSE && is.numeric(prior_c_function) == FALSE) { prior_c_function_all <- matrix(NA, ncol = length(prior_c_function), nrow = m2) for (i in seq_len(length(prior_c_function))) { str_locate_parenthesis <- stringr::str_locate(prior_c_function[i], "\\(") prior_c_function_all[, i] <- eval(parse(text = paste0( paste0( stringr::str_sub(prior_c_function[i], 1, str_locate_parenthesis[1]), m2, ",", stringr::str_sub(prior_c_function[i], str_locate_parenthesis[1] + 1) ) ))) } prior_c_function_used <- prior_c_function_all } # When the confounding function involves a re-analysis # over a range of point mass priors if (any(stringr::str_detect(prior_c_function, "seq")) == TRUE) { # First extract those involves a range of point mass priors c_index_with_grid <- which(stringr::str_detect(prior_c_function, "seq")) c_index_without_grid <- which(!stringr::str_detect(prior_c_function, "seq")) n_c_with_grid <- length(prior_c_function[stringr::str_detect(prior_c_function, "seq")]) grid_length <- length(eval(parse(text = prior_c_function[ stringr::str_detect(prior_c_function, "seq")]))) m2 <- grid_length ^ n_c_with_grid c_with_grid <- prior_c_function[c_index_with_grid] c_without_grid <- prior_c_function[c_index_without_grid] # Then handle the other confounding functions c_without_grid_all <- matrix(NA, ncol = length(c_without_grid), nrow = m2) for (i in seq_len(length(c_without_grid))) { str_locate_parenthesis <- stringr::str_locate(c_without_grid[i], "\\(") c_without_grid_all[, i] <- eval(parse(text = paste0( paste0( stringr::str_sub(c_without_grid[i], 1, str_locate_parenthesis[1]), m2, ",", stringr::str_sub(c_without_grid[i], str_locate_parenthesis[1] + 1) ) ))) } colnames(c_without_grid_all) <- c_index_without_grid c_with_grid_1 <- NULL for (i in seq_len(length(c_index_with_grid))) { assign(paste0("c_with_grid_", i), eval(parse(text = c_with_grid[i]))) } c_with_grid_all <- c_with_grid_1 for (i in 1:(length(c_index_with_grid) - 1)) { c_with_grid_all <- tidyr::expand_grid(c_with_grid_all, eval(parse(text = paste0( "c_with_grid_", (i + 1) )))) } # Combine the c functions with a range of point mass priors and without colnames(c_with_grid_all) <- c_index_with_grid c_functions_grid_final <- cbind(as.data.frame(c_without_grid_all), c_with_grid_all) names(c_functions_grid_final) <- paste0("c", names(c_functions_grid_final)) c_functions_grid_final <- c_functions_grid_final %>% select(paste0("c", seq_len(length(prior_c_function)))) prior_c_function_used <- c_functions_grid_final } if (is.numeric(prior_c_function) == TRUE) { prior_c_function_used <- t(apply(prior_c_function, 2, mean)) } # change the type of y and w as the input parameter of bart function x <- as.matrix(x) y <- as.numeric(y) w <- as.integer(w) n_trt <- length(unique(w)) prior_c_function_used <- as.matrix(prior_c_function_used) n_alpha <- nrow(prior_c_function_used) # fit the treatment assigment model, to use gap-sampling, # we over sample n * 10 samples, and select a sample per 10 turns a_model <- BART::mbart2( x.train = x, as.integer(as.factor(w)), x.test = x, ndpost = m1 * 10, mc.cores = n_cores ) # assign the estimated assignment probability to each sample, # the size is (n, #treatment, sample_size) gps <- array(a_model$prob.test[seq(1, nrow(a_model$prob.test), 10), ], dim = c(m1, length(unique(w)), length(w))) train_x <- cbind(x, w) n_trt <- length(unique(w)) cl <- parallel::makeCluster(n_cores) doParallel::registerDoParallel(cl) # When the estimand is ATE if (estimand == "ATE") { # First set up the paramters used for parallel computing out <- foreach::foreach( i = 1:n_alpha, .combine = function(x, y) { result_list_final <- vector("list", length = (n_trt * (n_trt - 1) / 2)) counter <- 1 for (k in 1:(n_trt - 1)) { for (m in (k + 1):n_trt) { result_list_final[[counter]] <- rbind(x[[paste0("ATE_", k, m)]], y[[paste0("ATE_", k, m)]]) names(result_list_final)[[counter]] <- paste0("ATE_", k, m) counter <- counter + 1 } } result_list_final } ) %dopar% { # Start parallel computing cat("Starting ", i, "th job.\n", sep = "") for (k in 1:(n_trt - 1)) { for (m in (k + 1):n_trt) { assign(paste0("ATE_", k, m), NULL) } } for (j in 1:m1) { # correct the binary outcome based on w, prior_c_function_used, gps train_y <- ifelse( train_x[, "w"] == sort(unique(train_x[, "w"]))[1], y - ( unlist(prior_c_function_used[i, 1]) * gps[j, 2, ] + unlist(prior_c_function_used[i, 4]) * gps[j, 3, ] ), ifelse( train_x[, "w"] == sort(unique(train_x[, "w"]))[2], y - ( unlist(prior_c_function_used[i, 2]) * gps[j, 1, ] + unlist(prior_c_function_used[i, 3]) * gps[j, 3, ] ), y - ( unlist(prior_c_function_used[i, 5]) * gps[j, 1, ] + unlist(prior_c_function_used[i, 6]) * gps[j, 2, ] ) ) ) # fit the bart model to estimate causal effect bart_mod <- BART::wbart( x.train = cbind(x, w), y.train = train_y, printevery = 10000 ) n_trt <- length(unique(w)) for (k in 1:n_trt) { assign(paste0("predict_", k), BART::pwbart(cbind(x, w = k), bart_mod$treedraws)) } # save the final ATE estimates for (k in 1:(n_trt - 1)) { for (m in (k + 1):n_trt) { assign(paste0("ATE_", k, m), c(eval(parse( text = paste0("ATE_", k, m) )), rowMeans(eval( parse(text = paste0("predict_", k)) ) - eval( parse(text = paste0("predict_", m)) )))) } } } result_list <- vector("list", length = (n_trt * (n_trt - 1) / 2)) # Add the names for ATE counter <- 1 for (k in 1:(n_trt - 1)) { for (m in (k + 1):n_trt) { result_list[[counter]] <- eval(parse(text = paste0("ATE_", k, m))) names(result_list)[[counter]] <- paste0("ATE_", k, m) counter <- counter + 1 } } return(result_list) } parallel::stopCluster(cl) result_list_final <- vector("list", length = (n_trt * (n_trt - 1) / 2)) # Add the list names for the final result list counter <- 1 for (k in 1:(n_trt - 1)) { for (m in (k + 1):n_trt) { result_list_final[[counter]] <- out[[counter]] names(result_list_final)[[counter]] <- paste0("ATE_", k, m) counter <- counter + 1 } } # When the confounding function involves a range of point mass priors if (any(stringr::str_detect(prior_c_function, "seq")) == TRUE) { result_final <- vector("list", length = (n_trt * (n_trt - 1) / 2)) counter <- 1 for (k in 1:(n_trt - 1)) { for (m in (k + 1):n_trt) { result_final[[counter]] <- apply(result_list_final[[paste0("ATE_", k, m)]], 1, mean) names(result_final)[[counter]] <- paste0("ATE", k, m) counter <- counter + 1 } } result_final <- c( result_final, list(c_functions = prior_c_function_used, grid_index = c_index_with_grid) ) class(result_final) <- "CIMTx_sa_grid" return(result_final) } # When the confounding function do not involve # a range of point mass priors if (any(stringr::str_detect(prior_c_function, "seq")) == FALSE) { result_final <- NULL counter <- 1 for (k in 1:(n_trt - 1)) { for (m in (k + 1):n_trt) { result_final <- c(result_final, list(result_list_final[[paste0("ATE_", k, m)]])) names(result_final)[[counter]] <- paste0("ATE_RD", k, m) counter <- counter + 1 } } class(result_final) <- "CIMTx_ATE_sa" return(result_final) } } if (estimand == "ATT") { w_ind <- 1:n_trt w_ind_no_reference <- w_ind[w_ind != reference_trt] # First set up the paramters used for parallel computing out <- foreach::foreach( i = 1:n_alpha, .combine = function(x, y) { result_list_final <- vector("list", length = (n_trt - 1)) counter <- 1 for (k in 1:(n_trt - 1)) { result_list_final[[counter]] <- rbind(x[[paste0("ATT_", reference_trt, w_ind_no_reference[k])]], y[[paste0("ATT_", reference_trt, w_ind_no_reference[k])]]) names(result_list_final)[[counter]] <- paste0("ATT_", reference_trt, w_ind_no_reference[k]) counter <- counter + 1 } result_list_final } ) %dopar% { # Start parallel computing cat("Starting ", i, "th job.\n", sep = "") for (k in 1:(n_trt - 1)) { assign(paste0("ATT_", reference_trt, w_ind_no_reference[k]), NULL) } for (j in 1:m1) { # correct the binary outcome based on w, prior_c_function, gps train_y <- ifelse( train_x[, "w"] == sort(unique(train_x[, "w"]))[1], y - ( unlist(prior_c_function[i, 1]) * gps[j, 2, ] + unlist(prior_c_function[i, 4]) * gps[j, 3, ] ), ifelse( train_x[, "w"] == sort(unique(train_x[, "w"]))[2], y - ( unlist(prior_c_function[i, 2]) * gps[j, 1, ] + unlist(prior_c_function[i, 3]) * gps[j, 3, ] ), y - ( unlist(prior_c_function[i, 5]) * gps[j, 1, ] + unlist(prior_c_function[i, 6]) * gps[j, 2, ] ) ) ) # fit the bart model to estimate causal effect bart_mod <- BART::wbart( x.train = cbind(x, w), y.train = train_y, printevery = 10000, ... ) n_trt <- length(unique(w)) for (k in 1:n_trt) { assign(paste0("predict_", k), BART::pwbart(cbind(x[w == reference_trt, ], w = k), bart_mod$treedraws)) } for (k in 1:(n_trt - 1)) { # Save the final adjusted ATT effect assign(paste0("ATT_", reference_trt, w_ind_no_reference[k]), c(eval(parse( text = paste0("ATT_", reference_trt, w_ind_no_reference[k]) )), rowMeans(eval( parse(text = paste0("predict_", reference_trt)) ) - eval( parse(text = paste0( "predict_", w_ind_no_reference[k] )) )))) } } result_list <- vector("list", length = (n_trt * (n_trt - 1) / 2)) counter <- 1 for (k in 1:(n_trt - 1)) { result_list[[counter]] <- eval(parse(text = paste0( "ATT_", reference_trt, w_ind_no_reference[k] ))) names(result_list)[[counter]] <- paste0("ATT_", reference_trt, w_ind_no_reference[k]) counter <- counter + 1 } return(result_list) } parallel::stopCluster(cl) result_list_final <- vector("list", length = (n_trt - 1)) counter <- 1 # Add the names of the ATT effect for (k in 1:(n_trt - 1)) { result_list_final[[counter]] <- out[[counter]] names(result_list_final)[[counter]] <- paste0("ATT_", reference_trt, w_ind_no_reference[k]) counter <- counter + 1 } # When the confounding function involves a range of point mass priors if (any(stringr::str_detect(prior_c_function, "seq")) == TRUE) { result_final <- vector("list", length = (n_trt - 1)) counter <- 1 for (k in 1:(n_trt - 1)) { result_final[[counter]] <- apply(result_list_final[[paste0("ATT_", reference_trt, w_ind_no_reference[k])]], 1, mean) names(result_final)[[counter]] <- paste0("ATT", reference_trt, w_ind_no_reference[k]) counter <- counter + 1 } result_final <- c( result_final, list(c_functions = prior_c_function_used, grid_index = c_index_with_grid) ) class(result_final) <- "CIMTx_sa_grid" return(result_final) } # When the confounding function do not involve # a range of point mass priors if (any(stringr::str_detect(prior_c_function, "seq")) == FALSE) { result_final <- NULL counter <- 1 for (k in 1:(n_trt - 1)) { result_final <- c(result_final, list(result_list_final[[paste0("ATT_", reference_trt, w_ind_no_reference[k])]])) names(result_final)[[counter]] <- paste0("ATT_RD", reference_trt, w_ind_no_reference[k]) counter <- counter + 1 } } class(result_final) <- "CIMTx_ATT_sa" return(result_final) } }
/scratch/gouwar.j/cran-all/cranData/CIMTx/R/sa.R
#' Summarize a CIMTx_ATE_posterior object #' #' @param object a \code{CIMTx_ATE_posterior} object #' obtained with \code{\link{ce_estimate}} function. #' @param ... further arguments passed to or from other methods. #' #' @return a list with w*(w-1)/2 elements for ATE effect. #' Each element of the list contains the estimation, #' standard error, lower and upper 95\% CI for RD/RR/OR. #' @importFrom stringr str_detect str_sub #' @export #' #' @references #' Hadley Wickham (2019). #' \emph{stringr: Simple, Consistent Wrappers for Common String Operations}. #' R package version 1.4.0. #' URL:\url{https://CRAN.R-project.org/package=stringr} #' #' @examples #' library(CIMTx) #' lp_w_all <- #' c( #' ".4*x1 + .1*x2 - .1*x4 + .1*x5", # w = 1 #' ".2 * x1 + .2 * x2 - .2 * x4 - .3 * x5" #' ) # w = 2 #' nlp_w_all <- #' c( #' "-.5*x1*x4 - .1*x2*x5", # w = 1 #' "-.3*x1*x4 + .2*x2*x5" #' ) # w = 2 #' lp_y_all <- rep(".2*x1 + .3*x2 - .1*x3 - .1*x4 - .2*x5", 3) #' nlp_y_all <- rep(".7*x1*x1 - .1*x2*x3", 3) #' X_all <- c( #' "rnorm(0, 0.5)", # x1 #' "rbeta(2, .4)", # x2 #' "runif(0, 0.5)", # x3 #' "rweibull(1,2)", # x4 #' "rbinom(1, .4)" # x5 #' ) #' #' set.seed(111111) #' data <- data_sim( #' sample_size = 300, #' n_trt = 3, #' x = X_all, #' lp_y = lp_y_all, #' nlp_y = nlp_y_all, #' align = FALSE, #' lp_w = lp_w_all, #' nlp_w = nlp_w_all, #' tau = c(-1.5, 0, 1.5), #' delta = c(0.5, 0.5), #' psi = 1 #' ) #' ce_estimate_ra_ate_result <- ce_estimate( #' y = data$y, x = data$covariates, #' w = data$w, ndpost = 10, method = "RA", estimand = "ATE" #' ) #' summary(ce_estimate_ra_ate_result) summary.CIMTx_ATE_posterior <- function(object, ...) { object <- object[stringr::str_detect(names(object), "ATE")] n_trt <- length(unique(as.integer(stringr::str_sub( names(object), 8, 8 )))) + 1 result_summary <- NULL for (i in 1:(n_trt - 1)) { for (j in (i + 1):n_trt) { assign(paste0("ate", i, j), posterior_summary(object[[paste0("ATE_RD", i, j)]], object[[paste0("ATE_RR", i, j)]], object[[paste0("ATE_OR", i, j)]])) assign(paste0("ATE", i, j), list(round(eval( parse(text = (paste0("ate", i, j))) ), digits = 2))) assign(paste0("ATE", i, j), stats::setNames(eval(parse( text = (paste0("ATE", i, j)) )), paste0("ATE", i, j))) result_summary <- c(result_summary, (eval(parse( text = (paste0("ATE", i, j)) )))) } } return(result_summary) }
/scratch/gouwar.j/cran-all/cranData/CIMTx/R/summary.CIMTx_ATE_posterior.R
#' Summarize a CIMTx_ATE_sa object #' #' @param object a \code{CIMTx_ATE_sa} object obtained with #' \code{\link{sa}} function. #' @param ... further arguments passed to or from other methods. #' #' @return a data frame containing the estimation, standard error, #' lower and upper 95\% CI for the causal estimand in terms of RD. #' @importFrom stringr str_detect str_sub #' @export #' #' @references #' Hadley Wickham (2019). #' \emph{stringr: Simple, Consistent Wrappers for Common String Operations}. #' R package version 1.4.0. #' URL:\url{https://CRAN.R-project.org/package=stringr} #' @examples #' \donttest{ #' lp_w_all <- #' c( #' ".4*x1 + .1*x2 - 1.1*x4 + 1.1*x5", # w = 1 #' ".2 * x1 + .2 * x2 - 1.2 * x4 - 1.3 * x5" #' ) # w = 2 #' nlp_w_all <- #' c( #' "-.5*x1*x4 - .1*x2*x5", # w = 1 #' "-.3*x1*x4 + .2*x2*x5" #' ) # w = 2 #' lp_y_all <- rep(".2*x1 + .3*x2 - .1*x3 - 1.1*x4 - 1.2*x5", 3) #' nlp_y_all <- rep(".7*x1*x1 - .1*x2*x3", 3) #' X_all <- c( #' "rnorm(0, 0.5)", # x1 #' "rbeta(2, .4)", # x2 #' "runif(0, 0.5)", # x3 #' "rweibull(1,2)", # x4 #' "rbinom(1, .4)" # x5 #' ) #' set.seed(1111) #' data <- data_sim( #' sample_size = 100, #' n_trt = 3, #' x = X_all, #' lp_y = lp_y_all, #' nlp_y = nlp_y_all, #' align = FALSE, #' lp_w = lp_w_all, #' nlp_w = nlp_w_all, #' tau = c(0.5, -0.5, 0.5), #' delta = c(0.5, 0.5), #' psi = 2 #' ) #' c_grid <- c( #' "runif(-0.6, 0)", # c(1,2) #' "runif(0, 0.6)", # c(2,1) #' "runif(-0.6, 0)", # c(2,3) #' "seq(-0.6, 0, by = 0.3)", # c(1,3) #' "seq(0, 0.6, by = 0.3)", # c(3,1) #' "runif(0, 0.6)" # c(3,2) #' ) #' sensitivity_analysis_parallel_ATE_result <- #' sa( #' m1 = 1, #' x = data$covariates, #' y = data$y, #' w = data$w, #' prior_c_function = c_grid, #' nCores = 1, #' estimand = "ATE", #' ) #' summary(sensitivity_analysis_parallel_ATE_result) #' } summary.CIMTx_ATE_sa <- function(object, ...) { object <- object[stringr::str_detect(names(object), "ATE")] n_trt <- length(unique(as.integer(stringr::str_sub( names(object), 8, 8 )))) + 1 result_final <- NULL counter <- 1 for (k in 1:(n_trt - 1)) { for (m in (k + 1):n_trt) { assign(paste0("mean", k, m), mean(object[[paste0("ATE_RD", k, m)]])) assign(paste0("sd", k, m), stats::sd(object[[paste0("ATE_RD", k, m)]])) assign(paste0("lower", k, m), eval(parse(text = paste0("mean", k, m))) - 1.96 * eval(parse(text = paste0("sd", k, m)))) assign(paste0("upper", k, m), eval(parse(text = paste0("mean", k, m))) + 1.96 * eval(parse(text = paste0("sd", k, m)))) assign(paste0("RD", k, m), round(c( eval(parse(text = paste0("mean", k, m))), eval(parse(text = paste0("sd", k, m))), eval(parse(text = paste0("lower", k, m))), eval(parse(text = paste0("upper", k, m))) ), 2)) result_final <- rbind(result_final, eval(parse(text = paste0("RD", k, m)))) rownames(result_final)[[counter]] <- paste0("ATE_RD", k, m) counter <- counter + 1 } } colnames(result_final) <- c("EST", "SE", "LOWER", "UPPER") return(result_final) }
/scratch/gouwar.j/cran-all/cranData/CIMTx/R/summary.CIMTx_ATE_sa.R
#' Summarize a CIMTx_ATT_posterior object #' #' @param object a \code{CIMTx_ATT_posterior} object #' obtained with \code{\link{ce_estimate}} function. #' @param ... further arguments passed to or from other methods. #' #' @return a list with w-1 elements for ATT effect. #' Each element of the list contains the estimation, standard error, #' lower and upper 95\% CI for RD/RR/OR. #' @importFrom stringr str_detect str_sub #' @export #' #' @references #' Hadley Wickham (2019). #' \emph{stringr: Simple, Consistent Wrappers for Common String Operations}. #' R package version 1.4.0. #' URL:\url{https://CRAN.R-project.org/package=stringr} #' #' @examples #' lp_w_all <- #' c( #' ".4*x1 + .1*x2 - .1*x4 + .1*x5", # w = 1 #' ".2 * x1 + .2 * x2 - .2 * x4 - .3 * x5" #' ) # w = 2 #' nlp_w_all <- #' c( #' "-.5*x1*x4 - .1*x2*x5", # w = 1 #' "-.3*x1*x4 + .2*x2*x5" #' ) # w = 2 #' lp_y_all <- rep(".2*x1 + .3*x2 - .1*x3 - .1*x4 - .2*x5", 3) #' nlp_y_all <- rep(".7*x1*x1 - .1*x2*x3", 3) #' X_all <- c( #' "rnorm(0, 0.5)", # x1 #' "rbeta(2, .4)", # x2 #' "runif(0, 0.5)", # x3 #' "rweibull(1,2)", # x4 #' "rbinom(1, .4)" # x5 #' ) #' #' set.seed(111111) #' data <- data_sim( #' sample_size = 300, #' n_trt = 3, #' x = X_all, #' lp_y = lp_y_all, #' nlp_y = nlp_y_all, #' align = FALSE, #' lp_w = lp_w_all, #' nlp_w = nlp_w_all, #' tau = c(-1.5, 0, 1.5), #' delta = c(0.5, 0.5), #' psi = 1 #' ) #' ce_estimate_ra_att_result <- ce_estimate( #' y = data$y, x = data$covariates, #' w = data$w, reference_trt = 1, ndpost = 10, method = "RA", estimand = "ATT" #' ) #' summary(ce_estimate_ra_att_result) summary.CIMTx_ATT_posterior <- function(object, ...) { object <- object[stringr::str_detect(names(object), "ATT")] reference_trt <- as.integer(stringr::str_sub(names(object)[1], 7, 7)) trt_indicator_no_reference <- unique(as.integer(stringr::str_sub(names(object), 8, 8))) result_summary <- NULL for (j in seq_len(length(trt_indicator_no_reference))) { assign( paste0("ATT", reference_trt, trt_indicator_no_reference[j]), posterior_summary(object[[paste0("ATT_RD", reference_trt, trt_indicator_no_reference[j])]], object[[paste0("ATT_RR", reference_trt, trt_indicator_no_reference[j])]], object[[paste0("ATT_OR", reference_trt, trt_indicator_no_reference[j])]]) ) assign(paste0("ATT", reference_trt, trt_indicator_no_reference[j]), list(round(eval(parse( text = ( paste0("ATT", reference_trt, trt_indicator_no_reference[j]) ) )), digits = 2))) assign( paste0("ATT", reference_trt, trt_indicator_no_reference[j]), stats::setNames( eval(parse(text = ( paste0("ATT", reference_trt, trt_indicator_no_reference[j]) ))), paste0("ATT", reference_trt, trt_indicator_no_reference[j]) ) ) result_summary <- c(result_summary, (eval(parse(text = ( paste0("ATT", reference_trt, trt_indicator_no_reference[j]) ))))) } return(result_summary) }
/scratch/gouwar.j/cran-all/cranData/CIMTx/R/summary.CIMTx_ATT_posterior.R
#' Summarize a CIMTx_ATT_sa object #' #' @param object a \code{CIMTx_ATT_sa} object obtained with #' \code{\link{sa}} function. #' @param ... further arguments passed to or from other methods. #' #' @return a data frame containing the estimation, standard error, #' lower and upper 95\% CI for the causal estimand in terms of RD. #' @importFrom stringr str_detect str_sub #' @export #' #' @references #' Hadley Wickham (2019). #' \emph{stringr: Simple, Consistent Wrappers for Common String Operations}. #' R package version 1.4.0. #' URL:\url{https://CRAN.R-project.org/package=stringr} #' #' @examples #' \donttest{ #' lp_w_all <- #' c( #' ".4*x1 + .1*x2 - 1.1*x4 + 1.1*x5", # w = 1 #' ".2 * x1 + .2 * x2 - 1.2 * x4 - 1.3 * x5" #' ) # w = 2 #' nlp_w_all <- #' c( #' "-.5*x1*x4 - .1*x2*x5", # w = 1 #' "-.3*x1*x4 + .2*x2*x5" #' ) # w = 2 #' lp_y_all <- rep(".2*x1 + .3*x2 - .1*x3 - 1.1*x4 - 1.2*x5", 3) #' nlp_y_all <- rep(".7*x1*x1 - .1*x2*x3", 3) #' X_all <- c( #' "rnorm(0, 0.5)", # x1 #' "rbeta(2, .4)", # x2 #' "runif(0, 0.5)", # x3 #' "rweibull(1,2)", # x4 #' "rbinom(1, .4)" # x5 #' ) #' set.seed(1111) #' data <- data_sim( #' sample_size = 100, #' n_trt = 3, #' x = X_all, #' lp_y = lp_y_all, #' nlp_y = nlp_y_all, #' align = FALSE, #' lp_w = lp_w_all, #' nlp_w = nlp_w_all, #' tau = c(0.5, -0.5, 0.5), #' delta = c(0.5, 0.5), #' psi = 2 #' ) #' c_grid <- c( #' "runif(-0.6, 0)", # c(1,2) #' "runif(0, 0.6)", # c(2,1) #' "runif(-0.6, 0)", # c(2,3) #' "seq(-0.6, 0, by = 0.3)", # c(1,3) #' "seq(0, 0.6, by = 0.3)", # c(3,1) #' "runif(0, 0.6)" # c(3,2) #' ) #' sensitivity_analysis_parallel_ATT_result <- #' sa( #' m1 = 1, #' x = data$covariates, #' y = data$y, #' w = data$w, #' prior_c_function = c_grid, #' nCores = 1, #' estimand = "ATE", #' ) #' summary(sensitivity_analysis_parallel_ATT_result) #' } summary.CIMTx_ATT_sa <- function(object, ...) { object <- object[stringr::str_detect(names(object), "ATT")] reference_trt <- as.integer(stringr::str_sub(names(object)[1], 7, 7)) n_trt <- length(unique(as.integer(stringr::str_sub( names(object), 8, 8 )))) + 1 w_ind_no_reference <- unique(as.integer(stringr::str_sub(names(object), 8, 8))) result_final <- NULL counter <- 1 for (k in 1:(n_trt - 1)) { assign(paste0("mean", reference_trt, w_ind_no_reference[k]), mean(object[[paste0("ATT_RD", reference_trt, w_ind_no_reference[k])]])) assign(paste0("sd", reference_trt, w_ind_no_reference[k]), stats::sd(object[[paste0("ATT_RD", reference_trt, w_ind_no_reference[k])]])) assign( paste0("lower", reference_trt, w_ind_no_reference[k]), eval(parse( text = paste0("mean", reference_trt, w_ind_no_reference[k]) )) - 1.96 * eval(parse( text = paste0("sd", reference_trt, w_ind_no_reference[k]) )) ) assign( paste0("upper", reference_trt, w_ind_no_reference[k]), eval(parse( text = paste0("mean", reference_trt, w_ind_no_reference[k]) )) + 1.96 * eval(parse( text = paste0("sd", reference_trt, w_ind_no_reference[k]) )) ) assign(paste0("RD", reference_trt, w_ind_no_reference[k]), round(c( eval(parse( text = paste0("mean", reference_trt, w_ind_no_reference[k]) )), eval(parse( text = paste0("sd", reference_trt, w_ind_no_reference[k]) )), eval(parse( text = paste0("lower", reference_trt, w_ind_no_reference[k]) )), eval(parse( text = paste0("upper", reference_trt, w_ind_no_reference[k]) )) ), 2)) result_final <- rbind(result_final, eval(parse( text = paste0("RD", reference_trt, w_ind_no_reference[k]) ))) rownames(result_final)[[counter]] <- paste0("ATT_RD", reference_trt, w_ind_no_reference[k]) counter <- counter + 1 } colnames(result_final) <- c("EST", "SE", "LOWER", "UPPER") return(result_final) }
/scratch/gouwar.j/cran-all/cranData/CIMTx/R/summary.CIMTx_ATT_sa.R
#' Summarize a CIMTx_IPTW object #' #' @param object a \code{CIMTx_IPTW} object #' @param ... further arguments passed to or from other methods. #' #' @return a data frame with ATT/ATE effect estimates in terms of #' RD, RR and OR. #' @importFrom stringr str_detect str_sub #' @export #' #' @references #' Hadley Wickham (2019). #' \emph{stringr: Simple, Consistent Wrappers for Common String Operations}. #' R package version 1.4.0. #' URL:\url{https://CRAN.R-project.org/package=stringr} #' #' @examples #' lp_w_all <- #' c( #' ".4*x1 + .1*x2 - .1*x4 + .1*x5", # w = 1 #' ".2 * x1 + .2 * x2 - .2 * x4 - .3 * x5" #' ) # w = 2 #' nlp_w_all <- #' c( #' "-.5*x1*x4 - .1*x2*x5", # w = 1 #' "-.3*x1*x4 + .2*x2*x5" #' ) # w = 2 #' lp_y_all <- rep(".2*x1 + .3*x2 - .1*x3 - .1*x4 - .2*x5", 3) #' nlp_y_all <- rep(".7*x1*x1 - .1*x2*x3", 3) #' X_all <- c( #' "rnorm(0, 0.5)", # x1 #' "rbeta(2, .4)", # x2 #' "runif(0, 0.5)", # x3 #' "rweibull(1,2)", # x4 #' "rbinom(1, .4)" # x5 #' ) #' #' set.seed(111111) #' data <- data_sim( #' sample_size = 300, #' n_trt = 3, #' x = X_all, #' lp_y = lp_y_all, #' nlp_y = nlp_y_all, #' align = FALSE, #' lp_w = lp_w_all, #' nlp_w = nlp_w_all, #' tau = c(-1.5, 0, 1.5), #' delta = c(0.5, 0.5), #' psi = 1 #' ) #' iptw_multi_res <- ce_estimate( #' y = data$y, x = data$covariates, #' w = data$w, method = "IPTW-Multinomial", estimand = "ATE" #' ) #' summary(iptw_multi_res) summary.CIMTx_IPTW <- function(object, ...) { if (object$estimand == "ATE") { object <- object[stringr::str_detect(names(object), "ATE")] n_trt <- length(unique(as.integer(stringr::str_sub( names(object), 5, 5 )))) + 1 result_summary <- NULL for (i in 1:(n_trt - 1)) { for (j in (i + 1):n_trt) { result_once <- object[[paste0("ATE", i, j)]] result_once <- round(result_once, digits = 2) colnames(result_once) <- paste0("ATE", i, j) result_summary <- cbind(result_summary, result_once) } } return(result_summary) } if (object$estimand == "ATT") { object <- object[stringr::str_detect(names(object), "ATT")] reference_trt <- as.integer(stringr::str_sub(names(object)[1], 4, 4)) trt_indicator_no_reference <- unique(as.integer(stringr::str_sub(names(object), 5, 5))) result_summary <- NULL for (j in seq_len(length(trt_indicator_no_reference))) { result_once <- object[[paste0("ATT", reference_trt, trt_indicator_no_reference[j])]] result_once <- round(result_once, digits = 2) colnames(result_once) <- paste0("ATT", reference_trt, trt_indicator_no_reference[j]) result_summary <- cbind(result_summary, result_once) } return(result_summary) } }
/scratch/gouwar.j/cran-all/cranData/CIMTx/R/summary.CIMTx_IPTW.R
#' Summarize a CIMTx_nonIPTW_once object #' #' @param object a \code{CIMTx_nonIPTW_once} object #' @param ... further arguments passed to or from other methods. #' #' @return a data frame with ATT/ATE effect estimates in terms of #' RD, RR and OR. #' @importFrom dplyr select slice pull #' @importFrom stringr str_detect str_sub #' @export #' #' @references #' #' Hadley Wickham, Romain François, Lionel Henry and Kirill Müller (2021). #' \emph{dplyr: A Grammar of Data Manipulation}. #' R package version 1.0.7. #' URL: \url{https://CRAN.R-project.org/package=dplyr} #' #' Hadley Wickham (2019). #' \emph{stringr: Simple, Consistent Wrappers for Common String Operations}. #' R package version 1.4.0. #' URL:\url{https://CRAN.R-project.org/package=stringr} #' #' @examples #' \donttest{ #' lp_w_all <- #' c( #' ".4*x1 + .1*x2 - .1*x4 + .1*x5", # w = 1 #' ".2 * x1 + .2 * x2 - .2 * x4 - .3 * x5" #' ) # w = 2 #' nlp_w_all <- #' c( #' "-.5*x1*x4 - .1*x2*x5", # w = 1 #' "-.3*x1*x4 + .2*x2*x5" #' ) # w = 2 #' lp_y_all <- rep(".2*x1 + .3*x2 - .1*x3 - .1*x4 - .2*x5", 3) #' nlp_y_all <- rep(".7*x1*x1 - .1*x2*x3", 3) #' X_all <- c( #' "rnorm(0, 0.5)", # x1 #' "rbeta(2, .4)", # x2 #' "runif(0, 0.5)", # x3 #' "rweibull(1,2)", # x4 #' "rbinom(1, .4)" # x5 #' ) #' #' set.seed(111111) #' data <- data_sim( #' sample_size = 300, #' n_trt = 3, #' x = X_all, #' lp_y = lp_y_all, #' nlp_y = nlp_y_all, #' align = FALSE, #' lp_w = lp_w_all, #' nlp_w = nlp_w_all, #' tau = c(-1.5, 0, 1.5), #' delta = c(0.5, 0.5), #' psi = 1 #' ) #' iptw_tmle_res <- ce_estimate( #' y = data$y, x = data$covariates, #' w = data$w, method = "TMLE", estimand = "ATE", #' sl_library = c("SL.glm", "SL.glmnet") #' ) #' summary(iptw_tmle_res) #' } summary.CIMTx_nonIPTW_once <- function(object, ...) { if (object$method == "VM") { object <- object[stringr::str_detect(names(object), "ATT")] reference_trt <- as.integer(stringr::str_sub(names(object)[1], 4, 4)) trt_indicator_no_reference <- unique(as.integer(stringr::str_sub(names(object), 5, 5))) result_final <- NULL for (j in seq_len(length(trt_indicator_no_reference))) { result_once <- object[[paste0("ATT", reference_trt, trt_indicator_no_reference[j])]] result_once <- round(result_once, digits = 2) colnames(result_once) <- paste0("ATT", reference_trt, trt_indicator_no_reference[j]) result_final <- cbind(result_final, result_once) } return(result_final) } if (object$method == "TMLE") { n_trt <- object$n_trt w_result_one_repetition <- object$result_TMLE for (i in 1:n_trt) { assign( paste0("mu_", i, "_hat"), w_result_one_repetition %>% dplyr::select("EYt") %>% dplyr::slice(i) %>% dplyr::pull("EYt") ) } for (i in 1:n_trt) { assign( paste0("lower_", i, "_hat"), w_result_one_repetition %>% dplyr::select("CI1") %>% dplyr::slice(i) %>% dplyr::pull("CI1") ) } for (i in 1:n_trt) { assign( paste0("upper_", i, "_hat"), w_result_one_repetition %>% dplyr::select("CI2") %>% dplyr::slice(i) %>% dplyr::pull("CI2") ) } result_final <- NULL for (i in 1:(n_trt - 1)) { result_once <- NULL for (j in (i + 1):n_trt) { assign(paste0("RD", i, j), eval(parse(text = paste0( "mu_", i, "_hat" ))) - eval(parse(text = paste0( "mu_", j, "_hat" )))) assign(paste0("RR", i, j), eval(parse(text = paste0( "mu_", i, "_hat" ))) / eval(parse(text = paste0( "mu_", j, "_hat" )))) assign(paste0("OR", i, j), (eval(parse( text = paste0("mu_", i, "_hat") )) / (1 - eval( parse(text = paste0("mu_", i, "_hat")) ))) / (eval(parse( text = paste0("mu_", j, "_hat") )) / (1 - eval( parse(text = paste0("mu_", j, "_hat")) )))) result_once <- rbind(eval(parse(text = paste0( "round(RD", i, j, ",2)" ))), eval(parse(text = paste0( "round(RR", i, j, ",2)" ))), eval(parse(text = paste0( "round(OR", i, j, ",2)" )))) colnames(result_once) <- "EST" rownames(result_once) <- c("RD", "RR", "OR") colnames(result_once) <- paste0("ATE", i, j) result_final <- cbind(result_final, result_once) } } return(result_final) } if (object$method %in% c("RAMS-Multinomial", "RAMS-SL", "RAMS-GBM")) { if (object$estimand == "ATE") { object <- object[stringr::str_detect(names(object), "ATE")] n_trt <- length(unique(as.integer(stringr::str_sub( names(object), 5, 5 )))) + 1 result_summary <- NULL for (i in 1:(n_trt - 1)) { for (j in (i + 1):n_trt) { result_once <- object[[paste0("ATE", i, j)]] result_once <- round(result_once, digits = 2) colnames(result_once) <- paste0("ATE", i, j) result_summary <- cbind(result_summary, result_once) } } return(result_summary) } if (object$estimand == "ATT") { object <- object[stringr::str_detect(names(object), "ATT")] reference_trt <- as.integer(stringr::str_sub(names(object)[1], 4, 4)) trt_indicator_no_reference <- unique(as.integer(stringr::str_sub(names(object), 5, 5))) result_summary <- NULL for (j in seq_len(length(trt_indicator_no_reference))) { result_once <- object[[paste0("ATT", reference_trt, trt_indicator_no_reference[j])]] result_once <- round(result_once, digits = 2) colnames(result_once) <- paste0("ATT", reference_trt, trt_indicator_no_reference[j]) result_summary <- cbind(result_summary, result_once) } return(result_summary) } } }
/scratch/gouwar.j/cran-all/cranData/CIMTx/R/summary.CIMTx_nonIPTW_once.R
#' Calculate the true c functions with 3 treatments and a binary predictor #' #' This function calculates the true confounding functions #' with 3 treatments and a binary predictor for simulated data. #' #' @param x A matrix with one column for the binary predictor #' with values 0 and 1 #' @param w A treatment indicator #' #' @return A matrix with 2 rows and 6 columns #' @export #' #' @examples #' set.seed(111) #' data_SA <- data_sim( #' sample_size = 100, #' n_trt = 3, #' x = c( #' "rbinom(1, .5)", # x1:measured confounder #' "rbinom(1, .4)" #' ), # x2:unmeasured confounder #' lp_y = rep(".2*x1+2.3*x2", 3), # parallel response surfaces #' nlp_y = NULL, #' align = FALSE, # w model is not the same as the y model #' lp_w = c( #' "0.2 * x1 + 2.4 * x2", # w = 1 #' "-0.3 * x1 - 2.8 * x2" #' ), #' nlp_w = NULL, #' tau = c(-2, 0, 2), #' delta = c(0, 0), #' psi = 1 #' ) #' x1 <- data_SA$covariates[, 1, drop = FALSE] #' w <- data_SA$w #' Y1 <- data_SA$Y_true[, 1] #' Y2 <- data_SA$Y_true[, 2] #' Y3 <- data_SA$Y_true[, 3] #' true_c_fun <- true_c_fun_cal(x = x1, w = w) true_c_fun_cal <- function(x, w) { # Calculate the true confounding functions within x = 1 and x= 0 stratum c_truth_list <- vector("list", length(unique(x[, 1]))) x_unique <- unique(x[, 1]) for (i in seq_len(length(unique(x[, 1])))) { assign(paste0("c_1_x_", x_unique[i]), eval(parse(text = ( paste0("mean(Y1[w==1&x==", x_unique[i], "])") ))) - eval(parse(text = ( paste0("mean(Y1[w==2&x==", x_unique[i], "])") )))) # This is c(1,2) assign(paste0("c_2_x_", x_unique[i]), eval(parse(text = ( paste0("mean(Y2[w==2&x==", x_unique[i], "])") ))) - eval(parse(text = ( paste0("mean(Y2[w==1&x==", x_unique[i], "])") )))) # This is c(2,1) assign(paste0("c_3_x_", x_unique[i]), eval(parse(text = ( paste0("mean(Y2[w==2&x==", x_unique[i], "])") ))) - eval(parse(text = ( paste0("mean(Y2[w==3&x==", x_unique[i], "])") )))) # This is c(2,3) assign(paste0("c_4_x_", x_unique[i]), eval(parse(text = ( paste0("mean(Y1[w==1&x==", x_unique[i], "])") ))) - eval(parse(text = ( paste0("mean(Y1[w==3&x==", x_unique[i], "])") )))) # This is c(1,3) assign(paste0("c_5_x_", x_unique[i]), eval(parse(text = ( paste0("mean(Y3[w==3&x==", x_unique[i], "])") ))) - eval(parse(text = ( paste0("mean(Y3[w==1&x==", x_unique[i], "])") )))) # This is c(3,1) assign(paste0("c_6_x_", x_unique[i]), eval(parse(text = ( paste0("mean(Y3[w==3&x==", x_unique[i], "])") ))) - eval(parse(text = ( paste0("mean(Y3[w==2&x==", x_unique[i], "])") )))) # This is c(3,2) assign(paste0("c_x_", x_unique[i]), eval(parse(text = ( paste0( "cbind(c_1_x_", x_unique[i], ", c_2_x_", x_unique[i], ", c_3_x_", x_unique[i], ", c_4_x_", x_unique[i], ", c_5_x_", x_unique[i], ", c_6_x_", x_unique[i], ")" ) )))) c_truth_list[[i]] <- eval(parse(text = paste0("c_x_", x_unique[i]))) } do.call(rbind, c_truth_list) }
/scratch/gouwar.j/cran-all/cranData/CIMTx/R/true_c_fun_cal.R
#' Trimming #' #' The function trims the weights for IPTW methods. #' #' @param x A numeric vector #' @param trim_perc A numeric vector with length 2 indicating trimming #' percentile. #' #' @return A numeric vector #' trunc_fun <- function(x, trim_perc = 0.05) { pmin(stats::quantile(x, trim_perc[2]), pmax(stats::quantile(x, trim_perc[1]), x)) }
/scratch/gouwar.j/cran-all/cranData/CIMTx/R/trunc_fun.R
#' My StopWords #' @format character "MyStopWords"
/scratch/gouwar.j/cran-all/cranData/CINE/R/MyStopWords.R
utils::globalVariables(c("as.tibble", "word", "value", "df_LEMMA", "unite", "AcademicLevel_COD")) options(dplyr.summarise.inform = FALSE) #' Classifies educational programs using lemmatization and CINE classification #' #' @description Uses the lemmatization of the education program name to combine with the CINE dataframe. #' #' @import dplyr #' @import tm #' @import tidytext #' #' @param df Name of dataframe #' @param EducationProgram Name of Education Program #' @param filterBy Academic level code. Use 'AUX' for 'Auxiliar técnico', 'TEC' for 'Técnico', 'PTC' for 'Profesional técnico', 'PRF' for 'Profesional', '2DA' for 'Segunda especialidad', 'MAG' for 'Maestría' and 'PHD' for 'Doctorado' #' #' @return A dataframe with CINE classification result fields #' @export #' #' @examples #' df <- data.frame(c("Administración de Negocios Internacionales", #' "Ingeniería de Telecomunicaciones", #' "Ingeniería Geográfica", #' "Psicología Organizacional y de la Gestión Humana", #' "Educación Secundaria Especialidad Lengua y Literatura", #' "Educación Secundaria, Mención en: Ciencias Matemáticas", #' "Ciencias de la Comunicación con Especialidad en Periodismo", #' "Ingeniería Pesquera", #' "Medicina Humana", #' "Medicina Veterinaria", #' "Carrera de Economía", #' "Radiología", #' "Biología - Microbiología", #' "Marketing y Negocios Internacionales", #' "Tecnología Médica con Especialidad en Laboratorio Clínico")) #' colnames(df) <- "ProgramaEducativo" #' cine(df=df, EducationProgram="ProgramaEducativo", filterBy='PRF') #' cine <- function(df, EducationProgram, filterBy){ d <- df[,colnames(df)==EducationProgram] d <- data.frame(d) colnames(d) = "x" d = d$x d <- VCorpus(VectorSource(d)) d <- tm_map(d, tolower) d <- tm_map(d, stripWhitespace) d <- tm_map(d, removePunctuation) d <- tm_map(d, removeNumbers) MyStopWords <- CINE::MyStopWords d <- tm_map(d, removeWords, c(stopwords("spanish"), MyStopWords)) z <- data.frame(text = get("content", d)) Programa_TXT <- t(z) Programa_TXT <- trimws(Programa_TXT) for (i in 1:length(Programa_TXT)) { Programa_TXT[i] = gsub("\\s+", " ", Programa_TXT[i]) } largo <- vector() for (i in 1:length(Programa_TXT)) { largo[i] = nchar(Programa_TXT[i]) } m <- df[,colnames(df)==EducationProgram] m <- data.frame(m) colnames(m) = "x" m = m$x VF = largo==0 lista_eli <- m[VF] if(sum(VF)!=0){ message("The following programs do not contain information to be classified:") message(lista_eli) } VF = largo!=0 Programa_TXT <- Programa_TXT[VF] df <- filter(df, largo!=0) a <- vector() for (i in 1:length(Programa_TXT)) { b <- as_tibble(Programa_TXT[i]) %>% unnest_tokens(word, value) b <- left_join(b, df_LEMMA, by=c("word")) if (dim(b)[1]==0){ l = "-" } else { l <- unique(b) l <- data.frame(t(l)) l <- tidyr::unite(l, l, sep=" ") } a[i] <- l } aa <- data.frame(text = sapply(a, as.character), stringsAsFactors = FALSE) aa <- data.frame(t(aa)) Programa_LEMMA <- aa$X2 df["EducationProgram_Lemma"] <- Programa_LEMMA df_CINE <- CINE::df_CINE df_CINE <- dplyr::filter(df_CINE, AcademicLevel_COD==filterBy) df_CINE$EducationProgram <- NULL df_CINE <- unique(df_CINE) dX <- left_join(df, df_CINE, by=c("EducationProgram_Lemma")) return(dX) }
/scratch/gouwar.j/cran-all/cranData/CINE/R/cine.R
#' Peru: International Standard Classification of Education #' @format dataframe #' \describe{ #' \item{Education_COD}{chr Education code} #' \item{Education}{chr Education} #' \item{Specific_COD}{chr Specific code} #' \item{Specific}{chr Specific} #' \item{AcademicLevel}{dbl Academic Level} #' \item{AcademicLevel_COD}{dbl Academic Level code} #' \item{EducationProgram}{dbl Education Program} #' \item{EducationProgram_Lemma}{dbl Lemma of the Education Program} #' } "df_CINE"
/scratch/gouwar.j/cran-all/cranData/CINE/R/df_CINE.R
#' Lemma of the Education Program #' @format dataframe #' \describe{ #' \item{word}{chr word} #' \item{lemma}{chr lemma} #' } "df_LEMMA"
/scratch/gouwar.j/cran-all/cranData/CINE/R/df_LEMMA.R
.onAttach <- function(libname, pkgname) { #packageStartupMessage("") #packageStartupMessage(" =========================================") packageStartupMessage("For examples, please visit https://github.com/musajajorge/CINE") #packageStartupMessage(" =========================================") packageStartupMessage("") }
/scratch/gouwar.j/cran-all/cranData/CINE/R/msg.R
cinid.plot <- function(cinid.out, breaks = 50, xlab = "Headcapsules width", ylab1 = "Density", ylab2 = "Number of Larvae", main = "", ...) { if((length(cinid.out) != 2) | (is.list(cinid.out) == FALSE)) stop("Erreur : cinid.out must be a list of two elements provided by the cinid.table function") Mindiv <- cinid.out$indiv Mpop <- cinid.out$pop par(mar = c(5, 6, 3, 5)) H <- hist(as.numeric(as.vector(Mindiv$HCW)), breaks = 50, plot = F) ## define the four unimodal distribution X <- seq(min(H$breaks), max(H$breaks), length.out = 1000) mod1 <- (exp(- 0.5 * ((X - Mpop[1, 1]) / Mpop[2, 1]) ^ 2) / (Mpop[2, 1] * sqrt(2 * pi))) mod2 <- (exp(- 0.5 * ((X - Mpop[1, 2]) / Mpop[2, 2]) ^ 2) / (Mpop[2, 2] * sqrt(2 * pi))) mod3 <- (exp(- 0.5 * ((X - Mpop[1, 3]) / Mpop[2, 3]) ^ 2) / (Mpop[2, 3] * sqrt(2 * pi))) mod4 <- (exp(- 0.5 * ((X - Mpop[1, 4]) / Mpop[2, 4]) ^ 2) / (Mpop[2, 4] * sqrt(2 * pi))) ## maximal density maxi <- max(max(H$density), max(Mpop[6, 1] * mod1), max(Mpop[6, 2] * mod2), max(Mpop[6, 3] * mod3), max(Mpop[6, 4] * mod4)) ## plot histogram H <- hist(as.numeric(as.vector(Mindiv$HCW)), breaks = breaks, plot = T, prob = T, xlab = xlab, ylab = "", main = main, xaxt = "n", yaxt = "n", ylim = c(0, maxi)) axis(1, at = seq(min(H$breaks), max(H$breaks), by = (H$breaks[2] - H$breaks[1]) * 2), cex.axis = 0.7, line = -0.5) yaxis <- axis(2, las = 1) mtext(side = 2, text = ylab1, line = 4) axis(4, yaxis, labels = pretty(0:max(H$counts), 5)[1:length(yaxis)], las = 1) mtext(side = 4, text = ylab2, line = 3) ## color individual with intermined instar par(new = T) indet <- Mindiv[which(Mindiv$instar_determ == "Indet"), 1] h <- hist(as.numeric(as.vector(indet)), breaks = H$breaks, plot = F) v <- h$counts / sum(H$counts) / (H$breaks[2] - H$breaks[1]) rect(H$mids - 0.5 * (H$breaks[2] - H$breaks[1]), 0, H$mids + 0.5 * (H$breaks[2] - H$breaks[1]), v, col = "grey") ## plot four probabilities' densities lines(X, Mpop[6, 1] * mod1, lwd = 1.5) lines(X, Mpop[6, 2] * mod2, lwd = 1.5) lines(X, Mpop[6, 3] * mod3, lwd = 1.5) lines(X, Mpop[6, 4] * mod4, lwd = 1.5) invisible(H) }
/scratch/gouwar.j/cran-all/cranData/CINID/R/cinid.plot.R
cinid.table <- function(HCW, mu4, sd4, threshold = 0.95, file = NULL, w = c(1, 1, 1, 1)) { HCW <- na.omit(as.vector(unlist(HCW))) ## check validity if(any(c(HCW, mu4, sd4) < 0)) stop("'HCW', 'mu4' and 'sd4' must be higher than zero") if((threshold < 0.25) | (threshold > 1)) return("'threshold' must be higher than 0.25 and lower than 1") if(length(w) != 4) return("'w' must be a four-length vector") n <- length(HCW) instar_determ <- rep(NA, n) instar_stoch <- rep(NA, n) mu1 <- 0.348 * mu4 + 17.24 mu2 <- 0.498 * mu4 + 11.65 mu3 <- 0.693 * mu4 + 32.34 sd1 <- 0.200 * sd4 + 13.63 sd2 <- 0.421 * sd4 + 7.80 sd3 <- 0.699 * sd4 + 3.90 X1 <- (HCW - mu1) / sd1 X2 <- (HCW - mu2) / sd2 X3 <- (HCW - mu3) / sd3 X4 <- (HCW - mu4) / sd4 p1 <- 2 * (1 - pnorm(abs(X1))) p2 <- 2 * (1 - pnorm(abs(X2))) p3 <- 2 * (1 - pnorm(abs(X3))) p4 <- 2 * (1 - pnorm(abs(X4))) p <- cbind(p1, p2, p3, p4) d1 <- dnorm(abs(X1)) * w[1] d2 <- dnorm(abs(X2)) * w[2] d3 <- dnorm(abs(X3)) * w[3] d4 <- dnorm(abs(X4)) * w[4] d <- cbind(d1, d2, d3, d4) d_tot <- apply(d, 1, sum) d_freq <- d / d_tot for(i in 1:n) { if((d_tot[i] == 0) | (length(which(d_freq[i, ] == max(d_freq[i, ]))) > 1)) { instar_determ[i] <- "Indet" instar_stoch[i] <- "Indet" } else { if(max(d_freq[i, ]) < as.numeric(threshold)) instar_determ[i] <- "Indet" else instar_determ[i] <- as.numeric(which(d[i, ] == max(d[i, ]))) K <- as.null() K <- rmultinom(1, 1, d_freq[i, ]) instar_stoch[i] <- which(K == 1) } } ## output for each individuals table_indiv <- as.null() table_indiv <- as.data.frame(cbind(HCW, instar_determ, instar_stoch, round(p, 4), round(d_freq, 4))) colnames(table_indiv) <- c("HCW", "instar_determ", "instar_stoch", "p1", "p2", "p3", "p4", "rd1", "rd2", "rd3", "rd4") ## output for the population number_instar_determ <- table(instar_determ) freq_instar_determ <- round(number_instar_determ / sum(number_instar_determ), 4) number_instar_stoch <- table(instar_stoch) freq_instar_stoch <- round(number_instar_stoch / sum(number_instar_stoch), 4) table_pop <- matrix(c(mu1, sd1, mu2, sd2, mu3, sd3, mu4, sd4, NA, NA), 2) colnames(table_pop) <- c("Instar1", "Instar2", "Instar3", "Instar4", "InstarIndet") table_pop <- rbind(table_pop, c(max(0, as.numeric(number_instar_determ[which(names(number_instar_determ) == 1)])), max(0, as.numeric(number_instar_determ[which(names(number_instar_determ) == 2)])), max(0, as.numeric(number_instar_determ[which(names(number_instar_determ) == 3)])), max(0, as.numeric(number_instar_determ[which(names(number_instar_determ) == 4)])), max(0, as.numeric(number_instar_determ[which(names(number_instar_determ) == "Indet")])))) table_pop <- rbind(table_pop, c(max(0, as.numeric(freq_instar_determ[which(names(freq_instar_determ) == 1)])), max(0, as.numeric(freq_instar_determ[which(names(freq_instar_determ) == 2)])), max(0, as.numeric(freq_instar_determ[which(names(freq_instar_determ) == 3)])), max(0, as.numeric(freq_instar_determ[which(names(freq_instar_determ) == 4)])), max(0, as.numeric(freq_instar_determ[which(names(freq_instar_determ) == "Indet")])))) table_pop <- rbind(table_pop, c(max(0, as.numeric(number_instar_stoch[which(names(number_instar_stoch) == 1)])), max(0, as.numeric(number_instar_stoch[which(names(number_instar_stoch) == 2)])), max(0, as.numeric(number_instar_stoch[which(names(number_instar_stoch) == 3)])), max(0, as.numeric(number_instar_stoch[which(names(number_instar_stoch) == 4)])), max(0, as.numeric(number_instar_stoch[which(names(number_instar_stoch) == "Indet")])))) table_pop <- rbind(table_pop, c(max(0, as.numeric(freq_instar_stoch[which(names(freq_instar_stoch) == 1)])), max(0, as.numeric(freq_instar_stoch[which(names(freq_instar_stoch) == 2)])), max(0, as.numeric(freq_instar_stoch[which(names(freq_instar_stoch) == 3)])), max(0, as.numeric(freq_instar_stoch[which(names(freq_instar_stoch) == 4)])), max(0, as.numeric(freq_instar_stoch[which(names(freq_instar_stoch) == "Indet")])))) rownames(table_pop) <- c("mu", "sd", "N_determ", "F_determ", "N_stoch", "F_stoch") if(is.null(file) == F) { write.table(table_indiv, paste(file, "_indiv.txt", sep = ""), quote = FALSE, row.names = FALSE) write.table(table_pop, paste(file, "_pop.txt", sep = ""), quote = FALSE, row.names = FALSE) } l <- new.env() l$indiv <- table_indiv l$pop <- table_pop l <- as.list(l) return(l) }
/scratch/gouwar.j/cran-all/cranData/CINID/R/cinid.table.R
#' @title Component extraction of a graph #' #' @description This function extracts all connected components of the #' input, which can be an "igraph" object or a "network" object, #' and converts them to "igraph" objects. #' @param x An igraph or a network object. #' @param directed Whether to create a directed graph (default = TRUE). #' @param bipartite_proj Whether the bipartite network must be projected or not (default = FALSE). #' @param num_proj Numbers 1 or 2 that show the number of projects for bipartite graphs (default = 1). #' @details #' This function separates different components of an "igraph" or a "network" object and #' illustrates them as a list of independent graphs. If the input graph was bipartite and the #' "bipartite_proj" was TRUE, it will project it, and you can decide in which project you want #' to continue working with. #' @seealso \code{\link[igraph]{induced.subgraph}}, \code{\link[igraph]{components}} #' @return A list including the components of the input as igraph objects. #' The output is a list where each element represents a component and is an igraph object. #' The components are disconnected subgraphs of the input graph. #' @author Minoo Ashtiani, Mehdi Mirzaie, Mohieddin Jafari #' @examples #' #' data(zachary) #' #' graph_extract_components(zachary) #' #' @export #' @importFrom igraph is_igraph #' @importFrom igraph is_bipartite #' @importFrom igraph bipartite.projection #' @importFrom igraph simplify #' @importFrom igraph is_simple #' @importFrom igraph clusters #' @importFrom igraph induced.subgraph #' @importFrom igraph graph_from_edgelist #' @importFrom network is.network #' @importFrom network as.edgelist #' @importFrom network network #' @keywords internal #' @return A list including the components of the input as igraph objects. graph_extract_components <- function( x, directed = TRUE, bipartite_proj=FALSE, num_proj=1){ if(!("igraph" %in% class(x)|| "network" %in% class(x))) stop("The input is not an igraph or a network object") if(is_igraph(x)){ if( bipartite_proj){ if(is_bipartite(x)){ x<-bipartite.projection(x)[[num_proj]] if (!is_simple(x)) x<-simplify(x) cl <- clusters(x) graph.splitting <- function(k, x, cl){ induced.subgraph(x, cl$membership == k) } components<-sapply(1:max(cl$membership), graph.splitting, x = x, cl = cl, simplify = FALSE) } } else{ if (!is_simple(x)) x<-simplify(x) cl <- clusters(x) graph_splitting <- function(k, x, cl){ induced.subgraph(x, cl$membership == k) } components<-sapply(1:max(cl$membership), graph_splitting, x = x, cl = cl, simplify = FALSE) } } if( is.network(x)){ edgelist<-as.edgelist(x) x<-graph_from_edgelist(edgelist, directed = TRUE) if (!is_simple(x)) x<-simplify(x) cl <- clusters(x) graph_splitting <- function(k, x, cl){ induced.subgraph(x, cl$membership == k) } components<-sapply(1:max(cl$membership), graph_splitting, x = x, cl = cl, simplify = FALSE) } return(components) } #' @title Component extraction of miscellaneous graph formats #' #' @description This function extracts all components of the input with various formats #' and converts them to "igraph" objects. #' @param x The input can be an edgelist, an adjacency matrix, or a graphNEL object. #' @param directed Whether to create a directed graph. (default = TRUE) #' @param mode Character scalar, explains how to interpret the supplied matrix. #' Possible values are: "directed", "undirected", "upper", "lower", "max", "min", "plus". (default = "directed") #' @param weighted An argument for specifying whether the graph should be weighted or not. #' If it is NULL, then an unweighted graph is created. (default = NULL) #' @param unibipartite A boolean parameter describing whether the input edge list corresponds #' to a bipartite graph. A TRUE value specifies a bipartite graph, and vice versa. (default = FALSE) #' @param diag Logical scalar, whether to consider the diagonal of the matrix or not. #' If it is FALSE, then the diagonal is treated as zeros. (default = TRUE) #' @details #' This function extracts components from the input object, which can be an edgelist, #' an adjacency matrix, or a graphNEL object. The result is a list including the components #' represented as separate graphs. #' @seealso \code{\link[igraph]{induced.subgraph}}, \code{\link[igraph]{components}}, #' \code{\link[igraph]{graph_from_adjacency_matrix}} #' #' @return A list including the components of the input graph as igraph objects. #' Each element of the list represents a component and is an igraph object. #' The components are disconnected subgraphs of the input graph. #' #' @author Minoo Ashtiani, Mehdi Mirzaie, Mohieddin Jafari #' #' @export #' @importFrom igraph graph_from_edgelist #' @importFrom igraph %>% #' @importFrom igraph simplify #' @importFrom igraph clusters #' @importFrom igraph induced.subgraph #' @importFrom igraph graph_from_edgelist #' @importFrom igraph as_edgelist #' @importFrom network is.network #' @importFrom network as.edgelist #' @importFrom network network #' @importFrom igraph graph_from_incidence_matrix #' @importFrom igraph graph_from_adjacency_matrix #' @importFrom plyr . misc_extract_components <- function( x ,directed = TRUE, mode = "directed", weighted = NULL, unibipartite = FALSE, diag = TRUE){ if (ncol(x)%in%2) { if (unibipartite%in%FALSE){ x <- graph_from_edgelist(x, directed = directed) if (!is_simple(x)) x<-simplify(x) cl <- clusters(x) graph_splitting <- function(k, x, cl){ induced.subgraph(x, cl$membership == k) } components <- sapply(1:max(cl$membership), graph_splitting, x = x, cl = cl, simplify = FALSE) return(components) } else{ el <- cbind(x,1) incidence_mat <- el[rep(seq_len(nrow(el)), el[,'1']), c(colnames(el)[1], colnames(el)[2])] %>% {split(.[,colnames(el)[2]], .[,colnames(el)[1]])} %>% table() x <- graph_from_incidence_matrix(incidence_mat, directed=directed) if (!is_simple(x)) x <- simplify(x) cl <- clusters(x) graph_splitting <- function(k, x, cl){ induced.subgraph(x, cl$membership == k) } components <- sapply(1:max(cl$membership), graph_splitting, x = x, cl = cl, simplify = FALSE) return(components) } } if (ncol(x)>2||class(x)%in%"dgCMatrix") { x <- graph_from_adjacency_matrix(x, mode = mode, weighted = weighted, diag = diag, add.colnames = NULL, add.rownames = NA) if (!is_simple(x)) x<-simplify(x) cl <- clusters(x) graph_splitting <- function(k, x, cl){ induced.subgraph(x, cl$membership == k) } components <- sapply(1:max(cl$membership), graph_splitting, x = x, cl = cl, simplify = FALSE) return(components) } } #' @title Giant component extraction of a graph #' #' @description This function extracts the largest connected component or the giant component #' of the input graph, which can be an "igraph" object or a "network" object, and converts #' it to an "igraph" object. For bipartite graphs, this function can perform projection #' before extracting the components. #' @param x An igraph or a network object. #' @param directed Whether to create a directed graph. (default = TRUE) #' @param bipartite_proj Whether the bipartite network must be projected or not. (default = FALSE) #' @param num_proj A number indicating the specific projection to work with, especially for #' bipartite graphs. (default = 1) #' #' @details #' This function identifies the largest component of an "igraph" or a "network" object #' and returns it as a list containing the giant component as an igraph object and its #' corresponding edgelist. If the input graph is bipartite and the "bipartite_proj" parameter #' is set to TRUE, the function can perform projection before extracting the components. You #' can specify which projection to work with using the "num_proj" parameter. #' @seealso \code{\link[igraph]{induced.subgraph}}, \code{\link[igraph]{clusters}} #' #' @return A list containing the giant component of the input graph. The first element is an igraph object #' representing the giant component, and the second element is the corresponding edgelist. #' @author Minoo Ashtiani, Mehdi Mirzaie, Mohieddin Jafari #' @references #' Newman, M. (2010). Networks. Oxford University Press. #' @examples #' # A graph with 4 vertices #' #' data(zachary) #' giant_component_extract(zachary) #' #' @export #' @importFrom igraph is_igraph #' @importFrom igraph is_bipartite #' @importFrom igraph bipartite.projection #' @importFrom igraph is_simple #' @importFrom igraph simplify #' @importFrom igraph clusters #' @importFrom igraph induced.subgraph #' @importFrom igraph graph_from_edgelist #' @importFrom igraph as_edgelist #' @importFrom network is.network #' @importFrom network as.edgelist #' @importFrom network network giant_component_extract <- function( x, directed = TRUE, bipartite_proj=FALSE ,num_proj=1){ if (!("igraph" %in% class(x)|| "network" %in% class(x))) stop("The input is not an igraph or a network object") if (is_igraph(x)){ if ( bipartite_proj){ if (is_bipartite(x)){ x <- bipartite.projection(x)[[num_proj]] if (!is_simple(x)) x <- simplify(x) cl <- clusters(x) giant_comp <- induced.subgraph(x, which(cl$membership == which.max(cl$csize))) giant_comp_edgelist <- as_edgelist(giant_comp, names = TRUE) } else stop("The graph is not bipartite") } else{ if (!is_simple(x)) x<-simplify(x) cl <- clusters(x) giant_comp <- induced.subgraph(x, which(cl$membership == which.max(cl$csize))) giant_comp_edgelist <- as_edgelist(giant_comp, names = TRUE) } } if ( is.network(x)){ edgelist<-as.edgelist(x) x <- graph_from_edgelist(edgelist, directed = directed) if (!is_simple(x)) x<-simplify(x) cl <- clusters(x) giant_comp <- induced.subgraph(x, which(cl$membership == which.max(cl$csize))) giant_comp_edgelist <- as_edgelist(giant_comp, names = TRUE) } result <- list(giant_comp,giant_comp_edgelist) return(result) } #' @title Proper centrality measure representation #' #' @description This function indicates the proper centrality measures of an igraph object #' based on the network topology. #' @param x An igraph object. #' @details #' This function returns a list including the names of centrality measures that are applicable #' for the input graph based on its topology. #' @seealso \code{\link[CINNA]{calculate_centralities}} #' #' @return A list including the names of centrality measures that are suitable for the input graph. #' @author Minoo Ashtiani, Mehdi Mirzaie, Mohieddin Jafari #' @examples #' #' data("zachary") #' proper_centralities(zachary) #' #' @export #' @importFrom igraph is_igraph #' @importFrom igraph is_directed #' @importFrom igraph is_weighted proper_centralities<-function(x){ if (!is_igraph(x)) stop(" Error: x must be a class of igraph object ") if (is_directed(x) && is_weighted(x)){ proper_centralities <- c("Alpha Centrality", "Burt's Constraint", "Page Rank" , "Average Distance", "Barycenter Centrality" , "BottleNeck Centrality", "Centroid value" , "Closeness Centrality (Freeman)" , "ClusterRank" , "Decay Centrality", "Degree Centrality" , "Diffusion Degree", "DMNC - Density of Maximum Neighborhood Component" , "Eccentricity Centrality" , "Harary Centrality", "eigenvector centralities" , "K-core Decomposition" , "Geodesic K-Path Centrality" , "Katz Centrality (Katz Status Index)" , "Kleinberg's authority centrality scores", "Kleinberg's hub centrality scores" , "clustering coefficient" , "Lin Centrality" , "Lobby Index (Centrality)" , "Markov Centrality" , "Radiality Centrality", "Shortest-Paths Betweenness Centrality" , "Current-Flow Closeness Centrality", "Closeness centrality (Latora)" , "Communicability Betweenness Centrality", "Community Centrality" , "Cross-Clique Connectivity" , "Entropy Centrality" , "EPC - Edge Percolated Component" , "Laplacian Centrality" , "Leverage Centrality" , "MNC - Maximum Neighborhood Component" , "Hubbell Index" , "Semi Local Centrality", "Closeness Vitality" , "Residual Closeness Centrality", "Stress Centrality", "Load Centrality", "Flow Betweenness Centrality", "Information Centrality", "Dangalchev Closeness Centrality", "Group Centrality", "Harmonic Centrality", "Local Bridging Centrality", "Wiener Index Centrality", "Weighted Vertex Degree" ) } if (!is_directed(x) && is_weighted(x)) { proper_centralities<-c( "subgraph centrality scores", "Topological Coefficient", "Average Distance", "Barycenter Centrality" , "BottleNeck Centrality", "Centroid value" , "Closeness Centrality (Freeman)" , "ClusterRank" , "Decay Centrality", "Degree Centrality" , "Diffusion Degree", "DMNC - Density of Maximum Neighborhood Component" , "Eccentricity Centrality" , "Harary Centrality", "eigenvector centralities" , "K-core Decomposition" , "Geodesic K-Path Centrality" , "Katz Centrality (Katz Status Index)" , "Kleinberg's authority centrality scores", "Kleinberg's hub centrality scores" , "clustering coefficient" , "Lin Centrality" , "Lobby Index (Centrality)" , "Markov Centrality" , "Radiality Centrality", "Shortest-Paths Betweenness Centrality" , "Current-Flow Closeness Centrality", "Closeness centrality (Latora)" , "Communicability Betweenness Centrality", "Community Centrality" , "Cross-Clique Connectivity" , "Entropy Centrality" , "EPC - Edge Percolated Component" , "Laplacian Centrality" , "Leverage Centrality" , "MNC - Maximum Neighborhood Component" , "Hubbell Index" , "Semi Local Centrality", "Closeness Vitality" , "Residual Closeness Centrality", "Stress Centrality", "Load Centrality", "Flow Betweenness Centrality", "Information Centrality", "Dangalchev Closeness Centrality", "Group Centrality", "Harmonic Centrality", "Local Bridging Centrality", "Wiener Index Centrality", "Weighted Vertex Degree" ) } if (!is_directed(x) && !is_weighted(x)) { proper_centralities <- c( "subgraph centrality scores", "Topological Coefficient", "Average Distance", "Barycenter Centrality" , "BottleNeck Centrality", "Centroid value" , "Closeness Centrality (Freeman)" , "ClusterRank" , "Decay Centrality", "Degree Centrality" , "Diffusion Degree", "DMNC - Density of Maximum Neighborhood Component" , "Eccentricity Centrality" , "Harary Centrality", "eigenvector centralities" , "K-core Decomposition" , "Geodesic K-Path Centrality" , "Katz Centrality (Katz Status Index)" , "Kleinberg's authority centrality scores", "Kleinberg's hub centrality scores" , "clustering coefficient" , "Lin Centrality" , "Lobby Index (Centrality)" , "Markov Centrality" , "Radiality Centrality", "Shortest-Paths Betweenness Centrality" , "Current-Flow Closeness Centrality", "Closeness centrality (Latora)" , "Communicability Betweenness Centrality", "Community Centrality" , "Cross-Clique Connectivity" , "Entropy Centrality" , "EPC - Edge Percolated Component" , "Laplacian Centrality" , "Leverage Centrality" , "MNC - Maximum Neighborhood Component" , "Hubbell Index" , "Semi Local Centrality", "Closeness Vitality" , "Residual Closeness Centrality", "Stress Centrality", "Load Centrality", "Flow Betweenness Centrality", "Information Centrality", "Dangalchev Closeness Centrality", "Group Centrality", "Harmonic Centrality", "Local Bridging Centrality", "Wiener Index Centrality" ) } if (is_directed(x) && !is_weighted(x) ) { proper_centralities <- c("Alpha Centrality" , "Bonacich power centralities of positions" , "Page Rank" , "Average Distance", "Barycenter Centrality" , "BottleNeck Centrality", "Centroid value" , "Closeness Centrality (Freeman)" , "ClusterRank" , "Decay Centrality", "Degree Centrality" , "Diffusion Degree", "DMNC - Density of Maximum Neighborhood Component" , "Eccentricity Centrality" , "Harary Centrality", "eigenvector centralities" , "K-core Decomposition" , "Geodesic K-Path Centrality" , "Katz Centrality (Katz Status Index)" , "Kleinberg's authority centrality scores", "Kleinberg's hub centrality scores" , "clustering coefficient" , "Lin Centrality" , "Lobby Index (Centrality)" , "Markov Centrality" , "Radiality Centrality", "Shortest-Paths Betweenness Centrality" , "Current-Flow Closeness Centrality", "Closeness centrality (Latora)" , "Communicability Betweenness Centrality", "Community Centrality" , "Cross-Clique Connectivity" , "Entropy Centrality" , "EPC - Edge Percolated Component" , "Laplacian Centrality" , "Leverage Centrality" , "MNC - Maximum Neighborhood Component" , "Hubbell Index" , "Semi Local Centrality", "Closeness Vitality" , "Residual Closeness Centrality", "Stress Centrality", "Load Centrality", "Flow Betweenness Centrality", "Information Centrality", "Dangalchev Closeness Centrality", "Group Centrality", "Harmonic Centrality", "Local Bridging Centrality", "Wiener Index Centrality" ) } print(proper_centralities) } #' @title Centrality measure calculation #' #' @description This function computes multitude centrality measures of an igraph object. #' @param x the component of a network as an igraph object #' @param except A vector containing names of centrality measures which could be omitted from the calculations. #' @param include A vector including names of centrality measures which should be computed. #' @param weights A character scalar specifying the edge attribute to use. (default=NULL) #' @details #' This function calculates various types of centrality measures which are applicable to the network topology #' and returns the results as a list. In the "except" argument, you can specify centrality measures that are #' not necessary to calculate. #' #' @seealso \code{\link[igraph]{alpha.centrality}}, \code{\link[igraph]{bonpow}}, \code{\link[igraph]{constraint}}, #' \code{\link[igraph]{centr_degree}}, \code{\link[igraph]{eccentricity}}, \code{\link[igraph]{eigen_centrality}}, #' \code{\link[igraph]{coreness}}, \code{\link[igraph]{authority_score}}, \code{\link[igraph]{hub_score}}, #' \code{\link[igraph]{transitivity}}, \code{\link[igraph]{page_rank}}, \code{\link[igraph]{betweenness}}, #' \code{\link[igraph]{subgraph.centrality}}, \code{\link[sna]{flowbet}}, \code{\link[sna]{infocent}}, #' \code{\link[sna]{loadcent}}, \code{\link[sna]{stresscent}}, \code{\link[sna]{graphcent}}, \code{\link[centiserve]{topocoefficient}}, #' \code{\link[centiserve]{closeness.currentflow}}, \code{\link[centiserve]{closeness.latora}}, #' \code{\link[centiserve]{communibet}}, \code{\link[centiserve]{communitycent}}, #' \code{\link[centiserve]{crossclique}}, \code{\link[centiserve]{entropy}}, #' \code{\link[centiserve]{epc}}, \code{\link[centiserve]{laplacian}}, \code{\link[centiserve]{leverage}}, #' \code{\link[centiserve]{mnc}}, \code{\link[centiserve]{hubbell}}, \code{\link[centiserve]{semilocal}}, #' \code{\link[centiserve]{closeness.vitality}}, #' \code{\link[centiserve]{closeness.residual}}, \code{\link[centiserve]{lobby}}, #' \code{\link[centiserve]{markovcent}}, \code{\link[centiserve]{radiality}}, \code{\link[centiserve]{lincent}}, #' \code{\link[centiserve]{geokpath}}, \code{\link[centiserve]{katzcent}}, \code{\link[centiserve]{diffusion.degree}}, #' \code{\link[centiserve]{dmnc}}, \code{\link[centiserve]{centroid}}, \code{\link[centiserve]{closeness.freeman}}, #' \code{\link[centiserve]{clusterrank}}, \code{\link[centiserve]{decay}}, #' \code{\link[centiserve]{barycenter}}, \code{\link[centiserve]{bottleneck}}, \code{\link[centiserve]{averagedis}}, #' \code{\link[CINNA]{local_bridging_centrality}}, \code{\link[CINNA]{wiener_index_centrality}}, \code{\link[CINNA]{group_centrality}}, #' \code{\link[CINNA]{dangalchev_closeness_centrality}}, \code{\link[CINNA]{harmonic_centrality}}, \code{\link[igraph]{strength}} #' #' @return A list containing centrality measure values. Each column indicates a centrality measure, and each row corresponds to a vertex. #' The structure of the output is as follows: #' - The list has named elements, where each element represents a centrality measure. #' - The value of each element is a numeric vector, where each element of the vector corresponds to a vertex in the network. #' - The order of vertices in the numeric vectors matches the order of vertices in the input igraph object. #' - The class of the output is "centrality". #' #' @author Minoo Ashtiani, Mehdi Mirzaie, Mohieddin Jafari #' @references #' Bonacich, P., & Lloyd, P. (2001). Eigenvector like measures of centrality for asymmetric relations. Social Networks, 23(3), 191–201. #' #' Bonacich, P. (1972). Factoring and weighting approaches to status scores and clique identification. The Journal of Mathematical Sociology, 2(1), 113–120. #' #' Bonacich, P. (1987). Power and Centrality: A Family of Measures. American Journal of Sociology, 92(5), 1170–1182. #' #' Burt, R. S. (2004). Structural Holes and Good Ideas. American Journal of Sociology, 110(2), 349–399. #' #' Batagelj, V., & Zaversnik, M. (2003). An O(m) Algorithm for Cores Decomposition of Networks, 1–9. Retrieved from #' #' Seidman, S. B. (1983). Network structure and minimum degree. Social Networks, 5(3), 269–287. #' #' Kleinberg, J. M. (1999). Authoritative sources in a hyperlinked environment. Journal of the ACM, 46(5), 604–632. #' #' Wasserman, S., & Faust, K. (1994). Social network analysis : methods and applications. American Ethnologist (Vol. 24). #' Barrat, A., Barthélemy, M., Pastor Satorras, R., & Vespignani, A. (2004). The architecture of complex weighted networks. Proceedings of the National Academy of Sciences of the United States of America , 101(11), 3747–3752. #' #' Brin, S., & Page, L. (2010). The Anatomy of a Large Scale Hypertextual Web Search Engine The Anatomy of a Search Engine. Search, 30(June 2000), 1–7. #' #' Freeman, L. C. (1978). Centrality in social networks conceptual clarification. Social Networks, 1(3), 215–239. #' #' Brandes, U. (2001). A faster algorithm for betweenness centrality*. The Journal of Mathematical Sociology, 25(2), 163–177. #' #' Estrada E., Rodriguez-Velazquez J. A.: Subgraph centrality in Complex Networks. Physical Review E 71, 056103. #' #' Freeman, L. C., Borgatti, S. P., & White, D. R. (1991). Centrality in valued graphs: A measure of betweenness based on network flow. Social Networks, 13(2), 141–154. #' #' Brandes, U., & Erlebach, T. (Eds.). (2005). Network Analysis (Vol. 3418). Berlin, Heidelberg: Springer Berlin Heidelberg. #' #' Stephenson, K., & Zelen, M. (1989). Rethinking centrality: Methods and examples. Social Networks, 11(1), 1–37. #' #' Wasserman, S., & Faust, K. (1994). Social network analysis : methods and applications. American Ethnologist (Vol. 24). #' #' Brandes, U. (2008). On variants of shortest path betweenness centrality and their generic computation. Social Networks, 30(2), 136–145. #' #' Goh, K.-I., Kahng, B., & Kim, D. (2001). Universal Behavior of Load Distribution in Scale Free Networks. Physical Review Letters, 87(27), 278701. #' #' Shimbel, A. (1953). Structural parameters of communication networks. The Bulletin of Mathematical Biophysics, 15(4), 501–507. #' #' Assenov, Y., Ramrez, F., Schelhorn, S.-E., Lengauer, T., & Albrecht, M. (2008). Computing topological parameters of biological networks. Bioinformatics, 24(2), 282–284. #' #' Diekert, V., & Durand, B. (Eds.). (2005). STACS 2005 (Vol. 3404). Berlin, Heidelberg: Springer Berlin Heidelberg. #' #' Gräßler, J., Koschützki, D., & Schreiber, F. (2012). CentiLib: comprehensive analysis and exploration of network centralities. Bioinformatics (Oxford, England), 28(8), 1178–9. #' #' Latora, V., & Marchiori, M. (2001). Efficient Behavior of Small World Networks. Physical Review Letters, 87(19), 198701. #' #' Opsahl, T., Agneessens, F., & Skvoretz, J. (2010). Node centrality in weighted networks: Generalizing degree and shortest paths. Social Networks, 32(3), 245–251. #' #' Estrada, E., Higham, D. J., & Hatano, N. (2009). Communicability betweenness in complex networks. Physica A: Statistical Mechanics and Its Applications, 388(5), 764–774. #' #' Hagberg, Aric, Pieter Swart, and Daniel S Chult. Exploring network structure, dynamics, and function using NetworkX. No. LA-UR-08-05495; LA-UR-08-5495. Los Alamos National Laboratory (LANL), 2008. #' #' Kalinka, A. T., & Tomancak, P. (2011). linkcomm: an R package for the generation, visualization, and analysis of link communities in networks of arbitrary size and type. Bioinformatics, 27(14), 2011–2012. #' #' Faghani, M. R., & Nguyen, U. T. (2013). A Study of XSS Worm Propagation and Detection Mechanisms in Online Social Networks. IEEE Transactions on Information Forensics and Security, 8(11), 1815–1826. #' #' Brandes, U., & Erlebach, T. (Eds.). (2005). Network Analysis (Vol. 3418). Berlin, Heidelberg: Springer Berlin Heidelberg. #' #' Lin, C.-Y., Chin, C.-H., Wu, H.-H., Chen, S.-H., Ho, C.-W., & Ko, M.-T. (2008). Hubba: hub objects analyzer--a framework of interactome hubs identification for network biology. Nucleic Acids Research, 36(Web Server), W438–W443. #' #' Chin, C., Chen, S., & Wu, H. (2009). cyto Hubba: A Cytoscape Plug in for Hub Object Analysis in Network Biology. Genome Informatics …, 5(Java 5), 2–3. #' #' Qi, X., Fuller, E., Wu, Q., Wu, Y., & Zhang, C.-Q. (2012). Laplacian centrality: A new centrality measure for weighted networks. Information Sciences, 194, 240–253. #' #' Joyce, K. E., Laurienti, P. J., Burdette, J. H., & Hayasaka, S. (2010). A New Measure of Centrality for Brain Networks. PLoS ONE, 5(8), e12200. #' #' Lin, C.-Y., Chin, C.-H., Wu, H.-H., Chen, S.-H., Ho, C.-W., & Ko, M.-T. (2008). Hubba: hub objects analyzer--a framework of interactome hubs identification for network biology. Nucleic Acids Research, 36(Web Server), W438–W443. #' #' Hubbell, C. H. (1965). An Input Output Approach to Clique Identification. Sociometry, 28(4), 377. #' #' Dangalchev, C. (2006). Residual closeness in networks. Physica A: Statistical Mechanics and Its Applications, 365(2), 556–564. #' #' Brandes, U. & Erlebach, T. (2005). Network Analysis: Methodological Foundations, U.S. Government Printing Office. #' #' Korn, A., Schubert, A., & Telcs, A. (2009). Lobby index in networks. Physica A: Statistical Mechanics and Its Applications, 388(11), 2221–2226. #' #' White, S., & Smyth, P. (2003). Algorithms for estimating relative importance in networks. In Proceedings of the ninth ACM SIGKDD international conference on Knowledge discovery and data mining KDD ’03 (p. 266). New York, New York, USA: ACM Press. #' #' Cornish, A. J., & Markowetz, F. (2014). SANTA: Quantifying the Functional Content of Molecular Networks. PLoS Computational Biology, 10(9), e1003808. #' #' Scardoni, G., Petterlini, M., & Laudanna, C. (2009). Analyzing biological network parameters with CentiScaPe. Bioinformatics, 25(21), 2857–2859. #' #' Lin, N. (1976). Foundations of Social Research. Mcgraw Hill. #' #' Borgatti, S. P., & Everett, M. G. (2006). A Graph theoretic perspective on centrality. Social Networks, 28(4), 466–484. #' #' Newman, M. (2010). Networks. Oxford University Press. #' #' Junker, Bjorn H., Dirk Koschutzki, and Falk Schreiber(2006). "Exploration of biological network centralities with CentiBiN." BMC bioinformatics 7.1 : 219. #' #' Pal, S. K., Kundu, S., & Murthy, C. A. (2014). Centrality measures, upper bound, and influence maximization in large scale directed social networks. Fundamenta Informaticae, 130(3), 317–342. #' #' Lin, C.-Y., Chin, C.-H., Wu, H.-H., Chen, S.-H., Ho, C.-W., & Ko, M.-T. (2008). Hubba: hub objects analyzer--a framework of interactome hubs identification for network biology. Nucleic Acids Research, 36(Web Server), W438–W443. #' #' Scardoni, G., Petterlini, M., & Laudanna, C. (2009). Analyzing biological network parameters with CentiScaPe. Bioinformatics, 25(21), 2857–2859. #' #' Freeman, L. C. (1978). Centrality in social networks conceptual clarification. Social Networks, 1(3), 215–239. #' #' Chen, D.-B., Gao, H., L?, L., & Zhou, T. (2013). Identifying Influential Nodes in Large Scale Directed Networks: The Role of Clustering. PLoS ONE, 8(10), e77455. #' #' Jana Hurajova, S. G. and T. M. (2014). Decay Centrality. In 15th Conference of Kosice Mathematicians. Herlany. #' #' Viswanath, M. (2009). ONTOLOGY BASED AUTOMATIC TEXT SUMMARIZATION. Vishweshwaraiah Institute of Technology. #' #' Przulj, N., Wigle, D. A., & Jurisica, I. (2004). Functional topology in a network of protein interactions. Bioinformatics, 20(3), 340–348. #' #' del Rio, G., Koschtzki, D., & Coello, G. (2009). How to identify essential genes from molecular networks BMC Systems Biology, 3(1), 102. #' #' Scardoni, G. and Carlo Laudanna, C.B.M.C., 2011. Network centralities for Cytoscape. University of Verona. #' #' BOLDI, P. & VIGNA, S. 2014. Axioms for centrality. Internet Mathematics, 00-00. #' #' MARCHIORI, M. & LATORA, V. 2000. Harmony in the small-world. Physica A: Statistical Mechanics and its Applications, 285, 539-546. #' #' OPSAHL, T., AGNEESSENS, F. & SKVORETZ, J. 2010. Node centrality in weighted networks: Generalizing degree and shortest paths. Social Networks, 32, 245-251. #' #' OPSAHL, T. 2010. Closeness centrality in networks with disconnected components (http://toreopsahl.com/2010/03/20/closeness-centrality-in-networks-with-disconnected-components/) #' #' Michalak, T.P., Aadithya, K.V., Szczepanski, P.L., Ravindran, B. and Jennings, N.R., 2013. Efficient computation of the Shapley value for game-theoretic network centrality. Journal of Artificial Intelligence Research, 46, pp.607-650. #' #' Macker, J.P., 2016, November. An improved local bridging centrality model for distributed network analytics. In Military Communications Conference, MILCOM 2016-2016 IEEE (pp. 600-605). IEEE. DOI: 10.1109/MILCOM.2016.7795393 #' #' DANGALCHEV, C. 2006. Residual closeness in networks. Physica A: Statistical Mechanics and its Applications, 365, 556-564. DOI: 10.1016/j.physa.2005.12.020 #' #' Alain Barrat, Marc Barthelemy, Romualdo Pastor-Satorras, Alessandro Vespignani: The architecture of complex weighted networks, Proc. Natl. Acad. Sci. USA 101, 3747 (2004) #' #' @examples #' data("zachary") #' p <- proper_centralities(zachary) #' calculate_centralities(zachary, include = "Degree Centrality") #' #' @export #' #' @importFrom igraph is_directed #' @importFrom igraph is_connected #' @importFrom igraph is_weighted #' @importFrom igraph as_edgelist #' @importFrom stats setNames #' @importFrom igraph alpha.centrality #' @importFrom igraph bonpow #' @importFrom igraph constraint #' @importFrom igraph centr_degree #' @importFrom igraph eccentricity #' @importFrom igraph eigen_centrality #' @importFrom igraph coreness #' @importFrom igraph authority_score #' @importFrom igraph hub_score #' @importFrom igraph transitivity #' @importFrom igraph page_rank #' @importFrom igraph betweenness #' @importFrom igraph subgraph.centrality #' @importFrom igraph strength #' @importFrom network network #' @importFrom sna flowbet #' @importFrom sna infocent #' @importFrom sna loadcent #' @importFrom sna stresscent #' @importFrom sna graphcent #' @importFrom centiserve topocoefficient #' @importFrom centiserve closeness.currentflow #' @importFrom centiserve closeness.latora #' @importFrom centiserve communibet #' @importFrom centiserve communitycent #' @importFrom centiserve crossclique #' @importFrom centiserve entropy #' @importFrom centiserve epc #' @importFrom centiserve laplacian #' @importFrom centiserve leverage #' @importFrom centiserve mnc #' @importFrom centiserve hubbell #' @importFrom centiserve semilocal #' @importFrom centiserve closeness.vitality #' @importFrom centiserve closeness.residual #' @importFrom centiserve lobby #' @importFrom centiserve markovcent #' @importFrom centiserve radiality #' @importFrom centiserve lincent #' @importFrom centiserve geokpath #' @importFrom centiserve katzcent #' @importFrom centiserve diffusion.degree #' @importFrom centiserve dmnc #' @importFrom centiserve centroid #' @importFrom centiserve closeness.freeman #' @importFrom centiserve clusterrank #' @importFrom centiserve decay #' @importFrom centiserve barycenter #' @importFrom centiserve bottleneck #' @importFrom centiserve averagedis calculate_centralities <- function( x, except = NULL, include = NULL, weights = NULL){ if (!("igraph" %in% class(x) && is_connected(x))) stop("The input is not an igraph object or may not be connected.") y <- as_edgelist(x) y <- network(y) if (is_directed(x) && is_weighted(x) ){ centrality_funcs <- list( "Alpha Centrality" = function(x) alpha.centrality(x, weights = weights), "Burt's Constraint" = function(x)constraint(x, weights = weights), "Page Rank" = function(x)page_rank(x)$vector, "Average Distance" = function(x)averagedis(x, weights = weights), "Barycenter Centrality" = function(x)barycenter(x, weights = weights), "BottleNeck Centrality" = function(x)bottleneck(x), "Centroid value" = function(x)centroid(x, weights = weights), "Closeness Centrality (Freeman)" = function(x)closeness.freeman(x, weights = weights), "ClusterRank" = function(x)clusterrank(x), "Decay Centrality" = function(x)decay(x, weights = weights), "Degree Centrality" = function(x)centr_degree(x)$res, "Diffusion Degree" = function(x)diffusion.degree(x), "DMNC - Density of Maximum Neighborhood Component" = function(x)dmnc(x), "Eccentricity Centrality" = function(x)eccentricity(x), "eigenvector centralities" = function(x)eigen_centrality(x, weights = weights)$vector, "K-core Decomposition" = function(x)coreness(x), "Geodesic K-Path Centrality" = function(x)geokpath(x, weights = weights), "Katz Centrality (Katz Status Index)" = function(x)katzcent(x), "Kleinberg's authority centrality scores" = function(x)authority_score(x, weights = weights)$vector, "Kleinberg's hub centrality scores" = function(x)hub_score(x, weights = weights)$vector, "clustering coefficient" = function(x)transitivity(x, weights = weights,type="local"), "Lin Centrality" = function(x)lincent(x, weights = weights), "Lobby Index (Centrality)" = function(x)lobby(x), "Markov Centrality" = function(x)markovcent(x), "Radiality Centrality" = function(x)radiality(x, weights = weights), "Shortest-Paths Betweenness Centrality" = function(x)betweenness(x), "Current-Flow Closeness Centrality" = function(x)closeness.currentflow(x, weights = weights), "Closeness centrality (Latora)" = function(x)closeness.latora(x, weights = weights), "Communicability Betweenness Centrality" = function(x)communibet(x), "Community Centrality" = function(x)communitycent(x), "Cross-Clique Connectivity" = function(x)crossclique(x), "Entropy Centrality" = function(x)entropy(x, weights = weights), "EPC - Edge Percolated Component" = function(x)epc(x), "Laplacian Centrality" = function(x)laplacian(x), "Leverage Centrality" = function(x)leverage(x), "MNC - Maximum Neighborhood Component" = function(x)mnc(x), "Hubbell Index" = function(x)hubbell(x, weights = weights), "Semi Local Centrality" = function(x)semilocal(x), "Closeness Vitality" = function(x)closeness.vitality(x, weights = weights), "Residual Closeness Centrality" = function(x)closeness.residual(x, weights = weights), "Stress Centrality" = function(x)stresscent(y), "Load Centrality" = function(x)loadcent(y), "Flow Betweenness Centrality" = function(x)flowbet(y), "Information Centrality" = function(x)infocent(y), "Weighted Vertex Degree" = function(x)strength(x, vids = V(x), mode ="all", weights = weights), "Harary Centrality" = function(x)graphcent(y, gmode="graph", diag=T, cmode="directed"), "Dangalchev Closeness Centrality"= function(x)dangalchev_closeness_centrality(x, vids = V(x), mode = "all", weights = weights), "Group Centrality"= function(x)group_centrality(x, vids = V(x)), "Harmonic Centrality"= function(x)harmonic_centrality(x, vids = V(x), mode = "all", weights = weights), "Local Bridging Centrality"= function(x)local_bridging_centrality(x, vids = V(x)), "Wiener Index Centrality"= function(x)wiener_index_centrality(x, vids = V(x), mode ="all", weights = weights) ) if (!is.null(include)){ centrality_funcs <- centrality_funcs[intersect(names(centrality_funcs), include)] n <- names(centrality_funcs) warningsText <- "" result <- lapply(setNames(n, n), function(functionName, x) { f <- centrality_funcs[[functionName]] tryCatch(f(x), error = function(e) { warningsText <- paste0(warningsText, "\nError in ", functionName, ":\n", e$message) return(NULL) }) }, x) if (nchar(warningsText) > 0) warning(warningsText) return(result) } else{ centrality_funcs <- centrality_funcs[setdiff(names(centrality_funcs), except)] n <- names(centrality_funcs) warningsText <- "" result <- lapply(setNames(n, n), function(functionName, x) { f <- centrality_funcs[[functionName]] tryCatch(f(x), error = function(e) { warningsText <- paste0(warningsText, "\nError in ", functionName, ":\n", e$message) return(NULL) }) }, x) if (nchar(warningsText) > 0) warning(warningsText) return(result) } } if (!is_directed(x) && is_weighted(x)){ centrality_funcs <- list( "subgraph centrality scores" = function(x)subgraph.centrality(x), "Topological Coefficient" = function(x)topocoefficient(x), "Average Distance" = function(x)averagedis(x, weights = weights), "Barycenter Centrality" = function(x)barycenter(x, weights = weights), "BottleNeck Centrality" = function(x)bottleneck(x), "Centroid value" = function(x)centroid(x, weights = weights), "Closeness Centrality (Freeman)" = function(x)closeness.freeman(x, weights = weights), "ClusterRank" = function(x)clusterrank(x), "Decay Centrality" = function(x)decay(x, weights = weights), "Degree Centrality" = function(x)centr_degree(x)$res, "Diffusion Degree" = function(x)diffusion.degree(x), "DMNC - Density of Maximum Neighborhood Component" = function(x)dmnc(x), "Eccentricity Centrality" = function(x)eccentricity(x), "eigenvector centralities" = function(x)eigen_centrality(x, weights = weights)$vector, "K-core Decomposition" = function(x)coreness(x), "Geodesic K-Path Centrality" = function(x)geokpath(x, weights = weights), "Katz Centrality (Katz Status Index)" = function(x)katzcent(x), "Kleinberg's authority centrality scores" = function(x)authority_score(x, weights = weights)$vector, "Kleinberg's hub centrality scores" = function(x)hub_score(x, weights = weights)$vector, "clustering coefficient" = function(x)transitivity(x, weights = weights,type="local"), "Lin Centrality" = function(x)lincent(x, weights = weights), "Lobby Index (Centrality)" = function(x)lobby(x), "Markov Centrality" = function(x)markovcent(x), "Radiality Centrality" = function(x)radiality(x, weights = weights), "Shortest-Paths Betweenness Centrality" = function(x)betweenness(x), "Current-Flow Closeness Centrality" = function(x)closeness.currentflow(x, weights = weights), "Closeness centrality (Latora)" = function(x)closeness.latora(x, weights = weights), "Communicability Betweenness Centrality" = function(x)communibet(x), "Community Centrality" = function(x)communitycent(x), "Cross-Clique Connectivity" = function(x)crossclique(x), "Entropy Centrality" = function(x)entropy(x, weights = weights), "EPC - Edge Percolated Component" = function(x)epc(x), "Laplacian Centrality" = function(x)laplacian(x), "Leverage Centrality" = function(x)leverage(x), "MNC - Maximum Neighborhood Component" = function(x)mnc(x), "Hubbell Index" = function(x)hubbell(x, weights = weights), "Semi Local Centrality" = function(x)semilocal(x), "Closeness Vitality" = function(x)closeness.vitality(x, weights = weights), "Residual Closeness Centrality" = function(x)closeness.residual(x, weights = weights), "Stress Centrality" = function(x)stresscent(y), "Load Centrality" = function(x)loadcent(y), "Flow Betweenness Centrality" = function(x)flowbet(y), "Information Centrality" = function(x)infocent(y), "Weighted Vertex Degree" = function(x)strength(x, vids = V(x), mode ="all", weights = weights), "Harary Centrality" = function(x)graphcent(y, gmode="graph", diag=T, cmode="undirected"), "Dangalchev Closeness Centrality"= function(x)dangalchev_closeness_centrality(x, vids = V(x), mode = "all", weights = weights), "Group Centrality"= function(x)group_centrality(x, vids = V(x)), "Harmonic Centrality"= function(x)harmonic_centrality(x, vids = V(x), mode = "all", weights = weights), "Local Bridging Centrality"= function(x)local_bridging_centrality(x, vids = V(x)), "Wiener Index Centrality"= function(x)wiener_index_centrality(x, vids = V(x), mode ="all", weights = weights) ) if (!is.null(include)){ centrality_funcs <- centrality_funcs[intersect(names(centrality_funcs), include)] n <- names(centrality_funcs) warningsText <- "" result <- lapply(setNames(n, n), function(functionName, x) { f <- centrality_funcs[[functionName]] tryCatch(f(x), error = function(e) { warningsText <- paste0(warningsText, "\nError in ", functionName, ":\n", e$message) return(NULL) }) }, x) if (nchar(warningsText) > 0) warning(warningsText) return(result) } else{ centrality_funcs <- centrality_funcs[setdiff(names(centrality_funcs), except)] n <- names(centrality_funcs) warningsText <- "" result <- lapply(setNames(n, n), function(functionName, x) { f <- centrality_funcs[[functionName]] tryCatch(f(x), error = function(e) { warningsText <- paste0(warningsText, "\nError in ", functionName, ":\n", e$message) return(NULL) }) }, x) if (nchar(warningsText) > 0) warning(warningsText) return(result) } } if(!is_directed(x) && !is_weighted(x)) { centrality_funcs <- list( "subgraph centrality scores" = function(x)subgraph.centrality(x), "Topological Coefficient" = function(x)topocoefficient(x), "Average Distance" = function(x)averagedis(x, weights = NULL), "Barycenter Centrality" = function(x)barycenter(x, weights = NULL), "BottleNeck Centrality" = function(x)bottleneck(x), "Centroid value" = function(x)centroid(x, weights = NULL), "Closeness Centrality (Freeman)" = function(x)closeness.freeman(x, weights = NULL), "ClusterRank" = function(x)clusterrank(x), "Decay Centrality" = function(x)decay(x, weights = NULL), "Degree Centrality" = function(x)centr_degree(x)$res, "Diffusion Degree" = function(x)diffusion.degree(x), "DMNC - Density of Maximum Neighborhood Component" = function(x)dmnc(x), "Eccentricity Centrality" = function(x)eccentricity(x), "eigenvector centralities" = function(x)eigen_centrality(x, weights = NULL)$vector, "K-core Decomposition" = function(x)coreness(x), "Geodesic K-Path Centrality" = function(x)geokpath(x, weights = NULL), "Katz Centrality (Katz Status Index)" = function(x)katzcent(x), "Kleinberg's authority centrality scores" = function(x)authority_score(x, weights = NULL)$vector, "Kleinberg's hub centrality scores" = function(x)hub_score(x, weights = NULL)$vector, "clustering coefficient" = function(x)transitivity(x, weights = NULL,type="local"), "Lin Centrality" = function(x)lincent(x, weights = NULL), "Lobby Index (Centrality)" = function(x)lobby(x), "Markov Centrality" = function(x)markovcent(x), "Radiality Centrality" = function(x)radiality(x, weights = NULL), "Shortest-Paths Betweenness Centrality" = function(x)betweenness(x), "Current-Flow Closeness Centrality" = function(x)closeness.currentflow(x, weights = NULL), "Closeness centrality (Latora)" = function(x)closeness.latora(x, weights = NULL), "Communicability Betweenness Centrality" = function(x)communibet(x), "Community Centrality" = function(x)communitycent(x), "Cross-Clique Connectivity" = function(x)crossclique(x), "Entropy Centrality" = function(x)entropy(x, weights = NULL), "EPC - Edge Percolated Component" = function(x)epc(x), "Laplacian Centrality" = function(x)laplacian(x), "Leverage Centrality" = function(x)leverage(x), "MNC - Maximum Neighborhood Component" = function(x)mnc(x), "Hubbell Index" = function(x)hubbell(x, weights = NULL), "Semi Local Centrality" = function(x)semilocal(x), "Closeness Vitality" = function(x)closeness.vitality(x, weights = NULL), "Residual Closeness Centrality" = function(x)closeness.residual(x, weights = NULL), "Stress Centrality" = function(x)stresscent(y), "Load Centrality" = function(x)loadcent(y), "Flow Betweenness Centrality" = function(x)flowbet(y), "Information Centrality" = function(x)infocent(y), "Harary Centrality" = function(x)graphcent(y, gmode="graph", diag=T, cmode="directed"), "Dangalchev Closeness Centrality"= function(x)dangalchev_closeness_centrality(x, vids = V(x), mode = "all", weights = NULL), "Group Centrality"= function(x)group_centrality(x, vids = V(x)), "Harmonic Centrality"= function(x)harmonic_centrality(x, vids = V(x), mode = "all", weights = NULL), "Local Bridging Centrality"= function(x)local_bridging_centrality(x, vids = V(x)), "Wiener Index Centrality"= function(x)wiener_index_centrality(x, vids = V(x), mode ="all", weights = NULL) ) if (!is.null(include)){ centrality_funcs <- centrality_funcs[intersect(names(centrality_funcs), include)] n <- names(centrality_funcs) warningsText <- "" result <- lapply(setNames(n, n), function(functionName, x) { f <- centrality_funcs[[functionName]] tryCatch(f(x), error = function(e) { warningsText <- paste0(warningsText, "\nError in ", functionName, ":\n", e$message) return(NULL) }) }, x) if (nchar(warningsText) > 0) warning(warningsText) return(result) } else{ centrality_funcs <- centrality_funcs[setdiff(names(centrality_funcs), except)] n <- names(centrality_funcs) warningsText <- "" result <- lapply(setNames(n, n), function(functionName, x) { f <- centrality_funcs[[functionName]] tryCatch(f(x), error = function(e) { warningsText <- paste0(warningsText, "\nError in ", functionName, ":\n", e$message) return(NULL) }) }, x) if (nchar(warningsText) > 0) warning(warningsText) return(result) } } if(is_directed(x) && !is_weighted(x) ) { centrality_funcs <- list( "Alpha Centrality" = function(x) alpha.centrality(x, weights = NULL), "Bonacich power centralities of positions" = function(x)bonpow(x), "Page Rank" = function(x)page_rank(x)$vector, "Average Distance" = function(x)averagedis(x, weights = NULL), "Barycenter Centrality" = function(x)barycenter(x, weights = NULL), "BottleNeck Centrality" = function(x)bottleneck(x), "Centroid value" = function(x)centroid(x, weights = NULL), "Closeness Centrality (Freeman)" = function(x)closeness.freeman(x, weights = NULL), "ClusterRank" = function(x)clusterrank(x), "Decay Centrality" = function(x)decay(x, weights = NULL), "Degree Centrality" = function(x)centr_degree(x)$res, "Diffusion Degree" = function(x)diffusion.degree(x), "DMNC - Density of Maximum Neighborhood Component" = function(x)dmnc(x), "Eccentricity Centrality" = function(x)eccentricity(x), "eigenvector centralities" = function(x)eigen_centrality(x, weights = NULL)$vector, "K-core Decomposition" = function(x)coreness(x), "Geodesic K-Path Centrality" = function(x)geokpath(x, weights = NULL), "Katz Centrality (Katz Status Index)" = function(x)katzcent(x), "Kleinberg's authority centrality scores" = function(x)authority_score(x, weights = NULL)$vector, "Kleinberg's hub centrality scores" = function(x)hub_score(x, weights = NULL)$vector, "clustering coefficient" = function(x)transitivity(x, weights = NULL,type="local"), "Lin Centrality" = function(x)lincent(x, weights = NULL), "Lobby Index (Centrality)" = function(x)lobby(x), "Markov Centrality" = function(x)markovcent(x), "Radiality Centrality" = function(x)radiality(x, weights = NULL), "Shortest-Paths Betweenness Centrality" = function(x)betweenness(x), "Current-Flow Closeness Centrality" = function(x)closeness.currentflow(x, weights = NULL), "Closeness centrality (Latora)" = function(x)closeness.latora(x, weights = NULL), "Communicability Betweenness Centrality" = function(x)communibet(x), "Community Centrality" = function(x)communitycent(x), "Cross-Clique Connectivity" = function(x)crossclique(x), "Entropy Centrality" = function(x)entropy(x, weights = NULL), "EPC - Edge Percolated Component" = function(x)epc(x), "Laplacian Centrality" = function(x)laplacian(x), "Leverage Centrality" = function(x)leverage(x), "MNC - Maximum Neighborhood Component" = function(x)mnc(x), "Hubbell Index" = function(x)hubbell(x, weights = NULL), "Semi Local Centrality" = function(x)semilocal(x), "Closeness Vitality" = function(x)closeness.vitality(x, weights = NULL), "Residual Closeness Centrality" = function(x)closeness.residual(x, weights = NULL), "Stress Centrality" = function(x)stresscent(y), "Load Centrality" = function(x)loadcent(y), "Flow Betweenness Centrality" = function(x)flowbet(y), "Information Centrality" = function(x)infocent(y), "Harary Centrality" = function(x)graphcent(y, gmode="graph", diag=T, cmode="directed"), "Dangalchev Closeness Centrality"= function(x)dangalchev_closeness_centrality(x, vids = V(x), mode = "all", weights = NULL), "Group Centrality"= function(x)group_centrality(x, vids = V(x)), "Harmonic Centrality"= function(x)harmonic_centrality(x, vids = V(x), mode = "all", weights = NULL), "Local Bridging Centrality"= function(x)local_bridging_centrality(x, vids = V(x)), "Wiener Index Centrality"= function(x)wiener_index_centrality(x, vids = V(x), mode ="all", weights = NULL) ) if (!is.null(include)){ centrality_funcs <- centrality_funcs[intersect(names(centrality_funcs), include)] n <- names(centrality_funcs) warningsText <- "" result <- lapply(setNames(n, n), function(functionName, x) { f <- centrality_funcs[[functionName]] tryCatch(f(x), error = function(e) { warningsText <- paste0(warningsText, "\nError in ", functionName, ":\n", e$message) return(NULL) }) }, x) if (nchar(warningsText) > 0) warning(warningsText) return(result) } else{ centrality_funcs <- centrality_funcs[setdiff(names(centrality_funcs), except)] n <- names(centrality_funcs) warningsText <- "" result <- lapply(setNames(n, n), function(functionName, x) { f <- centrality_funcs[[functionName]] tryCatch(f(x), error = function(e) { warningsText <- paste0(warningsText, "\nError in ", functionName, ":\n", e$message) return(NULL) }) }, x) if (nchar(warningsText) > 0) warning(warningsText) return(result) } } } #' @title PCA Centrality Measures #' #' @description This function performs Principal Component Analysis (PCA) on centrality measures. #' It computes the contributions of variables to the principal components and visualizes them. #' #' @param x a list containing the computed centrality values #' @param scale.unit a boolean constant indicating whether data should be scaled to unit variance (default = TRUE) #' @param cut.off The intensity that must be exceeded in cumulative percentage of variance of eigen values (default = 80) #' @param ncp number of dimensions in the final results (default = 5) #' @param graph a boolean constant indicating whether the graph should be displayed (default = FALSE) #' @param axes a length 2 vector describing the number of components to plot (default = c(1, 2)) #' #' @return A plot illustrating the contributions of variables to the principal components. #' The x-axis represents the centrality measures, and the y-axis represents the contribution. #' The higher the contribution value, the more important the centrality measure is in the ranking. #' The plot helps in identifying the most influential centrality measures. #' #' @importFrom FactoMineR PCA #' @importFrom factoextra fviz_contrib #' @importFrom ggplot2 labs theme_grey theme element_text element_rect #' @importFrom stats na.omit #' #' @examples #' # Create a data frame with multiple observations #' centralities <- data.frame( #' Betweenness = c(0.2, 0.3, 0.5), #' Closeness = c(0.4, 0.2, 0.6), #' Degree = c(0.3, 0.1, 0.4), #' Eigenvector = c(0.1, 0.5, 0.2) #' ) #' pca_centralities(centralities) #' #' @export pca_centralities <- function(x, scale.unit = TRUE, cut.off = 80, ncp = 2, graph = FALSE, axes = c(1, 2)) { requireNamespace("FactoMineR", quietly = TRUE) requireNamespace("factoextra", quietly = TRUE) requireNamespace("ggplot2", quietly = TRUE) requireNamespace("utils", quietly = TRUE) x <- x[!sapply(x, is.null)] x <- as.data.frame(x) x <- na.omit(x) res_pca <- FactoMineR::PCA(x, scale.unit = scale.unit, ncp = ncp, graph = graph, axes = axes) PCs <- table(res_pca$eig[,"cumulative percentage of variance"] > cut.off)["FALSE"] + 1 if (is.na(PCs)) PCs <- 1 factoextra::fviz_contrib(res_pca, choice = "var", axes = 1:PCs, color = "black", fill = "turquoise") + ggplot2::labs(x = "\nCentrality measures", y = "Contributions\n") + ggplot2::theme_grey() + ggplot2::ggtitle("Contribution of variables via PCA") + ggplot2::theme(axis.text.x = ggplot2::element_text(angle = 45, vjust = 0.5), plot.title = ggplot2::element_text(hjust = 0.5), # Adjust line size here line = ggplot2::element_line(color = "black", size = 1.5) ) } #' @title Graph visualization based on a specific centrality measure #' #' @description This function demonstrates the input graph in which the size of nodes #' indicates calculated centrality value. #' @param x an igraph object #' @param computed_centrality_value A vector containing the values of calculated centrality measure for each node. #' @param centrality.type The type of centrality which should be calculated. #' @details #' This function represents the graph in which size of nodes are based on computed centrality value. If the values of wanted centrality #' measure were computed then by placing them in computed_centrality_value argument to use it for drawing the plot. Otherwise, by only giving the #' name of favorite centrality measure in centrality.type argument, this function will calculate it and then demonstrates the corresponding graph. #' @return A plot illustrating the input graph, where the size of nodes represents the calculated centrality values. #' The function takes an igraph object as input and either a vector of precomputed centrality values or the name of the desired centrality measure. #' If precomputed centrality values are provided in the computed_centrality_value argument, the graph will be plotted based on those values. #' If only the name of the desired centrality measure is provided in the centrality.type argument, the function will calculate the centrality values #' and then plot the graph. #' The plot shows the nodes of the graph, with their sizes indicating the centrality values. The larger the node, the higher the centrality value. #' This plot helps visualize the distribution of centrality values across the nodes of the graph. #' The function returns the plot and does not modify the input graph. #' #' @author Minoo Ashtiani, Mehdi Mirzaie, Mohieddin Jafari #' #' @export #' #' @importFrom igraph is.directed #' @importFrom igraph alpha.centrality #' @importFrom igraph bonpow #' @importFrom igraph constraint #' @importFrom igraph centr_degree #' @importFrom igraph eccentricity #' @importFrom igraph eigen_centrality #' @importFrom igraph coreness #' @importFrom igraph authority_score #' @importFrom igraph hub_score #' @importFrom igraph transitivity #' @importFrom igraph page_rank #' @importFrom igraph betweenness #' @importFrom igraph subgraph.centrality #' @importFrom igraph strength #' @importFrom sna flowbet #' @importFrom sna infocent #' @importFrom sna loadcent #' @importFrom sna stresscent #' @importFrom sna graphcent #' @importFrom centiserve topocoefficient #' @importFrom centiserve closeness.currentflow #' @importFrom centiserve closeness.latora #' @importFrom centiserve communibet #' @importFrom centiserve communitycent #' @importFrom centiserve crossclique #' @importFrom centiserve entropy #' @importFrom centiserve epc #' @importFrom centiserve laplacian #' @importFrom centiserve leverage #' @importFrom centiserve mnc #' @importFrom centiserve hubbell #' @importFrom centiserve semilocal #' @importFrom centiserve closeness.vitality #' @importFrom centiserve closeness.residual #' @importFrom centiserve lobby #' @importFrom centiserve markovcent #' @importFrom centiserve radiality #' @importFrom centiserve lincent #' @importFrom centiserve geokpath #' @importFrom centiserve katzcent #' @importFrom centiserve diffusion.degree #' @importFrom centiserve dmnc #' @importFrom centiserve centroid #' @importFrom centiserve closeness.freeman #' @importFrom centiserve clusterrank #' @importFrom centiserve decay #' @importFrom centiserve barycenter #' @importFrom centiserve bottleneck #' @importFrom centiserve averagedis #' @importFrom igraph layout_in_circle #' @importFrom graphics plot #' @importFrom igraph strength visualize_graph <- function( x , computed_centrality_value=NULL , centrality.type="Degree Centrality"){ if (is.null(computed_centrality_value)){ if (!("igraph" %in% class(x) && is_connected(x) )) stop("The input is not an igraph object or may not be connected.") y <- as_edgelist(x) y <- network(y) centrality_funcs <- list( "subgraph centrality scores"=function(x)subgraph.centrality(x), "Topological Coefficient"=function(x)topocoefficient(x), "Alpha Centrality"=function(x) alpha.centrality(x), "Bonacich power centralities of positions"=function(x)bonpow(x), "Burt's Constraint"=function(x)constraint(x), "Page Rank"=function(x)page_rank(x)$vector, "Average Distance"=function(x)averagedis(x), "Barycenter Centrality"=function(x)barycenter(x), "BottleNeck Centrality"=function(x)bottleneck(x), "Centroid value"=function(x)centroid(x), "Closeness Centrality (Freeman)"=function(x)closeness.freeman(x), "ClusterRank"=function(x)clusterrank(x), "Decay Centrality"=function(x)decay(x), "Degree Centrality"=function(x)centr_degree(x)$res, "Diffusion Degree"=function(x)diffusion.degree(x), "DMNC - Density of Maximum Neighborhood Component"=function(x)dmnc(x), "Eccentricity Centrality"=function(x)eccentricity(x), "eigenvector centralities"=function(x)eigen_centrality(x)$vector, "K-core Decomposition"=function(x)coreness(x), "Geodesic K-Path Centrality"=function(x)geokpath(x), "Katz Centrality (Katz Status Index)"=function(x)katzcent(x), "Kleinberg's authority centrality scores"=function(x)authority_score(x)$vector, "Kleinberg's hub centrality scores"=function(x)hub_score(x)$vector, "clustering coefficient"=function(x)transitivity(x,type="local"), "Lin Centrality"=function(x)lincent(x), "Lobby Index (Centrality)"=function(x)lobby(x), "Markov Centrality"=function(x)markovcent(x), "Radiality Centrality"=function(x)radiality(x), "Shortest-Paths Betweenness Centrality"=function(x)betweenness(x), "Current-Flow Closeness Centrality"=function(x)closeness.currentflow(x), "Closeness centrality (Latora)"=function(x)closeness.latora(x), "Communicability Betweenness Centrality"=function(x)communibet(x), "Community Centrality"=function(x)communitycent(x), "Cross-Clique Connectivity"=function(x)crossclique(x), "Entropy Centrality"=function(x)entropy(x), "EPC - Edge Percolated Component"=function(x)epc(x), "Laplacian Centrality"=function(x)laplacian(x), "Leverage Centrality"=function(x)leverage(x), "MNC - Maximum Neighborhood Component"=function(x)mnc(x), "Hubbell Index"=function(x)hubbell(x), "Semi Local Centrality"=function(x)semilocal(x), "Closeness Vitality"=function(x)closeness.vitality(x), "Residual Closeness Centrality"=function(x)closeness.residual(x), "Stress Centrality"=function(x)stresscent(y), "Load Centrality"=function(x)loadcent(y), "Flow Betweenness Centrality"=function(x)flowbet(y), "Information Centrality"=function(x)infocent(y), "Harary Centrality" = function(x)graphcent(y, gmode="graph", diag=T, cmode="directed"), "Dangalchev Closeness Centrality"= function(x)dangalchev_closeness_centrality(x, vids = V(x), mode = "all", weights = NULL), "Group Centrality"= function(x)group_centrality(x, vids = V(x)), "Harmonic Centrality"= function(x)harmonic_centrality(x, vids = V(x), mode = "all", weights = NULL), "Local Bridging Centrality"= function(x)local_bridging_centrality(x, vids = V(x)), "Wiener Index Centrality"= function(x)wiener_index_centrality(x, vids = V(x), mode ="all", weights = NULL), "Weighted Vertex Degree" = function(x)strength(x, vids = V(x), mode ="all", weights = NULL) ) centrality_funcs <- centrality_funcs[intersect(names(centrality_funcs), centrality.type)] n <- names(centrality_funcs) warningsText <- "" result <- lapply(setNames(n, n), function(functionName, x) { f <- centrality_funcs[[functionName]] tryCatch(f(x), error = function(e) { warningsText <- paste0(warningsText, "\nError in ", functionName, ":\n", e$message) return(NULL) }) }, x) if (nchar(warningsText) > 0) warning(warningsText) result <- result[!sapply(result,is.null)] result <- as.data.frame(result) result <- scale(result, center = FALSE, scale = TRUE) plot(x, vertex.size=result*10, layout= layout_in_circle(x,order(result*10) ) , vertex.color="turquoise",vertex.frame.color="orange2") } else{ computed_centrality_value<-scale(computed_centrality_value, center = FALSE, scale = TRUE) plot(x, vertex.size=computed_centrality_value*10, layout= layout_in_circle(x,order(computed_centrality_value*10) ) , vertex.color="turquoise",vertex.frame.color="orange2") } } #' @title Pairwise association plot between centrality measures #' #' @description This function computes regression between pair of centrality measures #' to show more details of association among them. #' @param x a vector containing a centrality measure as independent variable #' @param y a vector containing a centrality measure as dependent variable #' @param scale Whether the centrality values should be scaled or not #' @details #' This function applies regression analysis on two different centrality values in order to find out the corresponding association #' between them. Regression analysis is a kind of statitiscal method for approximation the association #' between variables.It asserts that the value of dependent variable changes when the #' value of independent variable varies. #' @return The function returns a regression plot and the results of the regression analysis between two centrality measures. #' The function takes two vectors, `x` and `y`, which represent the independent and dependent centrality measures, respectively. #' If the `scale` parameter is set to `TRUE`, the centrality values will be scaled before performing the regression analysis. #' The function applies regression analysis to estimate the association between the two centrality measures. #' It creates a scatter plot of the centrality values, with a regression line representing the relationship between the variables. #' Additionally, the plot includes confidence intervals around the regression line to show the uncertainty of the estimates. #' The function returns the regression plot and the computed regression results. #' #' @author Minoo Ashtiani, Mehdi Mirzaie, Mohieddin Jafari #' #' @references #' Chambers, J. M. (1992). Statistical Models in S. Wadsworth. Pacific Grove, California. Retrieved from #' [Link to the reference] #' #' Wilkinson, G. N., & Rogers, C. E. (1973). Symbolic Description of Factorial Models for Analysis of Variance. Applied Statistics, 22(3), 392. #' #' @export #' #' @importFrom ggplot2 ggplot #' @importFrom ggplot2 stat_summary #' @importFrom ggplot2 geom_smooth #' @importFrom ggplot2 mean_cl_normal #' @importFrom ggplot2 aes #' @importFrom ggplot2 xlab #' @importFrom ggplot2 ylab #' @importFrom ggplot2 geom_point #' @importFrom stats lm visualize_association <- function( x , y, scale=TRUE){ xname <- substitute(x) yname <- substitute(y) df <- as.data.frame(cbind(x,y)) names(df) <- c(xname, yname) if (scale%in%TRUE){ df <- scale(df, center = TRUE, scale = scale) df <- as.data.frame(df) visualization <- ggplot(data=df,aes(x,y)) + stat_summary(fun.data=mean_cl_normal,geom="point",fill="skyblue3",shape=21,colour="black", size = 3) + geom_smooth(method='lm',colour = 'red') + xlab(xname) + ylab(yname)+geom_point(shape=21, fill="blue", color="darkred", size=3) linear.regression <- lm(df[,2]~df[,1]) return (list(linear.regression=linear.regression, visualization=visualization)) } else {visualization <- ggplot(data=df,aes(x,y)) + stat_summary(fun.data=mean_cl_normal,geom="point",fill="skyblue3",shape=21,colour="black", size = 3) + geom_smooth(method='lm',colour = 'red') + xlab(xname) + ylab(yname)+geom_point(shape=21, fill="blue", color="darkred", size=3) linear.regression <- lm(y~x) return (list(linear.regression=linear.regression, visualization=visualization))} } #' @title Pairwise correlation plot between two centrality measures #' #' @description This function computes and plots correlation between pair of centrality #' measures and histogram plots. #' @param x a vector containing a centrality measure #' @param y a vector containing another centrality measure #' @param scale Whether the centrality values should be scaled or not #' @details #' This function illustrates the correlation value between two centrality measures and their #' corresponding scatterplot and histograms. #' @seealso \code{\link[GGally]{ggpairs}} #' @return The function computes and plots the correlation between two centrality measures. #' The function takes two vectors, `x` and `y`, representing the centrality measures to be correlated. #' If the `scale` parameter is set to `TRUE`, the centrality values will be scaled before computing the correlation. #' The function creates a correlation plot, which includes a scatterplot of the centrality values and histograms of each measure. #' The correlation coefficient between the two measures is displayed on the plot. #' The function returns the correlation plot. #' #' @author Minoo Ashtiani, Mehdi Mirzaie, Mohieddin Jafari #' #' @references #' Emerson, J. W., Green, W. A., Schloerke, B., Crowley, J., Cook, D., Hofmann, H., & Wickham, H. (2013). The Generalized Pairs Plot. Journal of Computational and Graphical Statistics, 22(1), 79–91. #' #' @export #' #' @importFrom GGally ggpairs visualize_pair_correlation <- function( x , y, scale=TRUE){ xname <- substitute(x) yname <- substitute(y) df <- as.data.frame(cbind(x,y)) names(df) <- c(xname, yname) if (scale%in%TRUE){ df <- scale(df, center = TRUE, scale = scale) df <- as.data.frame(df) ggpairs(df, columns=1:2) } else ggpairs(df, columns=1:2) } #' @title Heatmap plot between centrality measures #' #' @description This function draws heatmap between pair of centrality measures #' @param x a list indicating calculated centrality measures #' @param scale Whether the centrality values should be scaled or not #' @details #' This function illustrates the heatmap plot of computed centrality measures. #' @return The function generates a heatmap plot between pairs of centrality measures. #' The function takes a list x as input, which contains the computed centrality measures. #' If the scale parameter is set to TRUE, the centrality values will be scaled before plotting the heatmap. #' The function creates a heatmap plot, where each cell represents the correlation between a pair of centrality measures. #' The color of each cell indicates the strength and direction of the correlation. #' The function returns the heatmap plot. #' #' @author Minoo Ashtiani, Mehdi Mirzaie, Mohieddin Jafari #' #' @export #' #' @importFrom pheatmap pheatmap visualize_heatmap <- function( x, scale = TRUE ){ if(scale%in%TRUE){ x <- x[!sapply(x,is.null)] d <- as.data.frame(x) x <- scale(d, center = TRUE, scale = scale) rownames(x)<- rownames(d) pheatmap(x, legend = TRUE, cluster_rows = TRUE, cluster_cols = TRUE, fontsize = 8) } else{ pheatmap(x, legend = TRUE, cluster_rows = TRUE, cluster_cols = TRUE, fontsize = 8) } } #' @title Correlation plot between centrality measures #' #' @description This function draw correlation plot between pair of centrality measures #' @param x a list indicating calculated centrality measures #' @param scale Whether the centrality values should be scaled or not(default=TRUE) #' @param method a character string describing the type of correlation coefficient (or covariance) #' to be computed. The proper values are "pearson", "kendall", or "spearman". (default="pearson") #' @details #' This function illustrates pairwise correlation plot of computed centrality measures. #' The names of centralities shown in the result plot is abbreviated and compelete names #' can be seen in "proper_centralities" function. #' Colors from red to blue indicate the intensity of correlation value. If two centrality #' measures have an inverse relationship then their correspnding color in plot have to be red #' and vice versa. #' #' @seealso \code{\link[GGally]{ggpairs}} #' @return The function generates a correlation plot between pairs of centrality measures. #' The function takes a list x as input, which contains the computed centrality measures. #' If the scale parameter is set to TRUE, the centrality values will be scaled before computing the correlations. #' The method parameter specifies the type of correlation coefficient to be computed: "pearson" (default), "kendall", or "spearman". #' The function creates a pairwise correlation plot, where each cell represents the correlation between a pair of centrality measures. #' The color of each cell indicates the strength and direction of the correlation, ranging from red (negative correlation) to blue (positive correlation). #' The function returns the pairwise correlation plot. #' #' @author Minoo Ashtiani, Mehdi Mirzaie, Mohieddin Jafari #' #' @export #' #' @importFrom corrplot corrplot.mixed #' @importFrom stats cor visualize_correlations <- function(x, scale=TRUE,method = "pearson"){ if (scale%in%TRUE){ x <- x[!sapply(x,is.null)] d <- as.data.frame(x) x <- scale(d, center = TRUE, scale = scale) name <- unlist(lapply(strsplit(colnames(x), '.', fixed = TRUE), '[', 1)) colnames(x) <- name M <- cor(x,method = method) corrplot.mixed(M,tl.cex =0.75) } else{ x <- x[!sapply(x,is.null)] d <- as.data.frame(x) x <- as.matrix(d) name <- unlist(lapply(strsplit(colnames(x), '.', fixed = TRUE), '[', 1)) colnames(x) <- name M <- cor(x,method = method) corrplot.mixed(M,tl.cex =0.75) } } #' @title Dendrogram plot among centrality measures #' #' @description This function demonstrates the vertice dendrogram of a graph based #' on a centrality type. #' @param x an igraph object #' @param centrality.type The type of centrality which should be considered.(default="Degree Centrality") #' @param computed_centrality_value A vector containing the values of calculated centrality measure for each node.(default=NULL) #' @param k number of clusters(default=4) #' @return The function generates a dendrogram plot of a graph's vertices based on a centrality measure. #' The function takes an igraph object `x` as input, representing the graph. #' The `centrality.type` parameter specifies the type of centrality measure to be considered (default is "Degree Centrality"). #' If the `computed_centrality_value` parameter is provided, it should be a vector containing the computed centrality values for each node. #' Otherwise, the function will compute the specified centrality measure for the graph. #' The `k` parameter specifies the number of clusters to be formed from the dendrogram (default is 4). #' The function creates a dendrogram plot of the vertices, where the branching structure represents the hierarchical clustering based on the centrality measure. #' The function returns the dendrogram plot. #' #' @author Minoo Ashtiani, Mehdi Mirzaie, Mohieddin Jafari #' #' @references #' Galili, T. (2015). dendextend: an R package for visualizing, adjusting and comparing trees of hierarchical clustering. Bioinformatics, 31(22), 3718–3720. #' #' @export #' #' @importFrom igraph alpha.centrality #' @importFrom igraph bonpow #' @importFrom igraph constraint #' @importFrom igraph centr_degree #' @importFrom igraph eccentricity #' @importFrom igraph eigen_centrality #' @importFrom igraph coreness #' @importFrom igraph authority_score #' @importFrom igraph hub_score #' @importFrom igraph transitivity #' @importFrom igraph page_rank #' @importFrom igraph betweenness #' @importFrom igraph subgraph.centrality #' @importFrom igraph strength #' @importFrom sna flowbet #' @importFrom sna infocent #' @importFrom sna loadcent #' @importFrom sna stresscent #' @importFrom sna graphcent #' @importFrom centiserve topocoefficient #' @importFrom centiserve closeness.currentflow #' @importFrom centiserve closeness.latora #' @importFrom centiserve communibet #' @importFrom centiserve communitycent #' @importFrom centiserve crossclique #' @importFrom centiserve entropy #' @importFrom centiserve epc #' @importFrom centiserve laplacian #' @importFrom centiserve leverage #' @importFrom centiserve mnc #' @importFrom centiserve hubbell #' @importFrom centiserve semilocal #' @importFrom centiserve closeness.vitality #' @importFrom centiserve closeness.residual #' @importFrom centiserve lobby #' @importFrom centiserve markovcent #' @importFrom centiserve radiality #' @importFrom centiserve lincent #' @importFrom centiserve geokpath #' @importFrom centiserve katzcent #' @importFrom centiserve diffusion.degree #' @importFrom centiserve dmnc #' @importFrom centiserve centroid #' @importFrom centiserve closeness.freeman #' @importFrom centiserve clusterrank #' @importFrom centiserve decay #' @importFrom centiserve barycenter #' @importFrom centiserve bottleneck #' @importFrom centiserve averagedis #' @importFrom dendextend circlize_dendrogram #' @importFrom dendextend set #' @importFrom dendextend highlight_branches_col #' @importFrom viridis viridis #' @importFrom stats dist #' @importFrom stats hclust #' @importFrom stats as.dendrogram visualize_dendrogram <- function( x, centrality.type="Degree Centrality", computed_centrality_value=NULL , k=4){ if (is.null(computed_centrality_value)){ if (!("igraph" %in% class(x) && is_connected(x) )) stop("The input is not an igraph object or may not be connected.") y <- as_edgelist(x) y <- network(y) centrality_funcs <- list( "subgraph centrality scores"=function(x)subgraph.centrality(x), "Topological Coefficient"=function(x)topocoefficient(x), "Alpha Centrality"=function(x) alpha.centrality(x), "Bonacich power centralities of positions"=function(x)bonpow(x), "Burt's Constraint"=function(x)constraint(x), "Page Rank"=function(x)page_rank(x)$vector, "Average Distance"=function(x)averagedis(x), "Barycenter Centrality"=function(x)barycenter(x), "BottleNeck Centrality"=function(x)bottleneck(x), "Centroid value"=function(x)centroid(x), "Closeness Centrality (Freeman)"=function(x)closeness.freeman(x), "ClusterRank"=function(x)clusterrank(x), "Decay Centrality"=function(x)decay(x), "Degree Centrality"=function(x)centr_degree(x)$res, "Diffusion Degree"=function(x)diffusion.degree(x), "DMNC - Density of Maximum Neighborhood Component"=function(x)dmnc(x), "Eccentricity Centrality"=function(x)eccentricity(x), "eigenvector centralities"=function(x)eigen_centrality(x)$vector, "K-core Decomposition"=function(x)coreness(x), "Geodesic K-Path Centrality"=function(x)geokpath(x), "Katz Centrality (Katz Status Index)"=function(x)katzcent(x), "Kleinberg's authority centrality scores"=function(x)authority_score(x)$vector, "Kleinberg's hub centrality scores"=function(x)hub_score(x)$vector, "clustering coefficient"=function(x)transitivity(x,type="local"), "Lin Centrality"=function(x)lincent(x), "Lobby Index (Centrality)"=function(x)lobby(x), "Markov Centrality"=function(x)markovcent(x), "Radiality Centrality"=function(x)radiality(x), "Shortest-Paths Betweenness Centrality"=function(x)betweenness(x), "Current-Flow Closeness Centrality"=function(x)closeness.currentflow(x), "Closeness centrality (Latora)"=function(x)closeness.latora(x), "Communicability Betweenness Centrality"=function(x)communibet(x), "Community Centrality"=function(x)communitycent(x), "Cross-Clique Connectivity"=function(x)crossclique(x), "Entropy Centrality"=function(x)entropy(x), "EPC - Edge Percolated Component"=function(x)epc(x), "Laplacian Centrality"=function(x)laplacian(x), "Leverage Centrality"=function(x)leverage(x), "MNC - Maximum Neighborhood Component"=function(x)mnc(x), "Hubbell Index"=function(x)hubbell(x), "Semi Local Centrality"=function(x)semilocal(x), "Closeness Vitality"=function(x)closeness.vitality(x), "Residual Closeness Centrality"=function(x)closeness.residual(x), "Stress Centrality"=function(x)stresscent(y), "Load Centrality"=function(x)loadcent(y), "Flow Betweenness Centrality"=function(x)flowbet(y), "Information Centrality"=function(x)infocent(y), "Harary Centrality" = function(x)graphcent(y, gmode="graph", diag=T, cmode="directed"), "Dangalchev Closeness Centrality"= function(x)dangalchev_closeness_centrality(x, vids = V(x), mode = "all", weights = NULL), "Group Centrality"= function(x)group_centrality(x, vids = V(x)), "Harmonic Centrality"= function(x)harmonic_centrality(x, vids = V(x), mode = "all", weights = NULL), "Local Bridging Centrality"= function(x)local_bridging_centrality(x, vids = V(x)), "Wiener Index Centrality"= function(x)wiener_index_centrality(x, vids = V(x), mode ="all", weights = NULL), "Weighted Vertex Degree" = function(x)strength(x, vids = V(x), mode ="all", weights = NULL) ) centrality_funcs <- centrality_funcs[intersect(names(centrality_funcs), centrality.type)] n <- names(centrality_funcs) warningsText <- "" result <- lapply(setNames(n, n), function(functionName, x) { f <- centrality_funcs[[functionName]] tryCatch(f(x), error = function(e) { warningsText <- paste0(warningsText, "\nError in ", functionName, ":\n", e$message) return(NULL) }) }, x) if (nchar(warningsText) > 0) warning(warningsText) result <-result[!sapply(result,is.null)] result <- as.data.frame(result) rownames(result) = V(x)$name result <- scale(result, center = TRUE, scale = TRUE) dend <- result%>% dist %>% hclust %>% as.dendrogram %>% highlight_branches_col(viridis(100)) %>% set("branches_k_color", k=3)%>% set("labels_colors")%>%set("nodes_pch", 20) circlize_dendrogram(dend, labels_track_height = NA, dend_track_height = .4) } else{ computed_centrality_value <- scale(computed_centrality_value, center = FALSE, scale = TRUE) names(computed_centrality_value) = V(x)$name dend <- computed_centrality_value%>% dist %>% hclust %>% as.dendrogram %>% highlight_branches_col(viridis(100)) %>% set("branches_k_color", k=3)%>% set("labels_colors")%>%set("nodes_pch", 20) circlize_dendrogram(dend, labels_track_height = NA, dend_track_height = .4) } } #' @title Summarize PCA result related to centrality measures #' #' @description This function summarizes the PCA result related to centrality measures. #' @param x A list containing the computed centrality values. #' @param scale.unit A boolean value indicating whether the data should be scaled to unit variance (default = TRUE). #' @param ncp The number of dimensions in the final results (default = 5). #' @return The result of the \code{pca_centralities} function, which includes the PCA analysis results such as eigenvalues, variance explained, and scores. #' The returned value is an object of class "PCA" from the FactoMineR package. It contains the following components: #' \item{eig}{A numeric vector of eigenvalues, indicating the amount of variance explained by each principal component.} #' \item{var}{A numeric vector of proportions of variance explained by each principal component.} #' \item{ind}{A data frame of individual scores, where each row represents an individual and each column represents a principal component.} #' \item{call}{The function call used to create the PCA object.} #' \item{call2}{The call used to compute the PCA analysis.} #' \item{call3}{The call used to project the individuals.} #' \item{svd}{The singular value decomposition of the data matrix.} #' \item{cor}{The correlation matrix of the variables.} #' \item{cos2}{The squared cosines of the variables.} #' \item{contrib}{The contributions of the variables to the principal components.} #' \item{proj}{The projected coordinates of the individuals on the principal components.} #' \item{quali.sup}{The results of the supplementary qualitative variables analysis.} #' \item{quali.sup.ind}{The results of the supplementary individuals analysis.} #' \item{quanti.sup}{The results of the supplementary quantitative variables analysis.} #' \item{quanti.sup.var}{The results of the supplementary variables analysis.} #' @author Minoo Ashtiani, Mehdi Mirzaie, Mohieddin Jafari #' @export #' @importFrom FactoMineR PCA #' @importFrom stats na.omit summary_pca_centralities <- function( x , scale.unit = TRUE,ncp = 5){ x <- x[!sapply(x,is.null)] x <- as.data.frame(x) x <- na.omit(x) res_pca <- PCA(x, scale.unit = scale.unit, ncp = ncp, graph = FALSE) l <- list(eigen= res_pca$eig, contribution= res_pca$var$contrib) print(l) } #' @title Summarize component extraction of a graph #' #' @description This function summarizes all components of the input which can be an "igraph" object or a "network" object. #' @param x An igraph or a network object. #' @param directed A boolean value indicating whether to create a directed graph (default = TRUE). #' @param bipartite_proj A boolean value indicating whether the bipartite network should be projected (default = FALSE). #' @param num_proj A number indicating the number of projects specifically for bipartite graphs (default = 1). #' @return A list of igraph objects representing the extracted components of the graph. #' Each element in the list corresponds to a component, and each component is represented by an igraph object. #' The components are extracted based on the connectivity of the graph and can include single nodes, disconnected subgraphs, or connected subgraphs. #' If the graph is directed and the \code{directed} parameter is set to FALSE, the function returns the weakly connected components. #' If the graph is bipartite and the \code{bipartite_proj} parameter is set to TRUE, the function returns the projected graph components. #' If the graph is neither directed nor bipartite, the function returns the connected components. #' @author Minoo Ashtiani, Mehdi Mirzaie, Mohieddin Jafari #' @export #' @importFrom igraph is_igraph #' @importFrom igraph is_bipartite #' @importFrom igraph bipartite.projection #' @importFrom igraph is_simple #' @importFrom igraph simplify #' @importFrom igraph clusters #' @importFrom igraph induced.subgraph #' @importFrom igraph graph_from_edgelist #' @importFrom network is.network #' @importFrom network as.edgelist #' @importFrom network is.network #' @importFrom network network #' @importFrom stats na.omit summary_graph_extract_components <- function( x, directed = TRUE, bipartite_proj = FALSE , num_proj = 1){ if (!("igraph" %in% class(x) || ("network" %in% class(x) ))) stop("The input is not an igraph or a network object") if (is_igraph(x)) { if (bipartite_proj){ if (is_bipartite(x)){ x <- bipartite.projection(x)[[num_proj]] if (!is_simple(x)) x<-simplify(x) cl <- clusters(x) graph_splitting <- function(k, x, cl){ induced.subgraph(x, cl$membership == k) } components <- sapply(1:max(cl$membership), graph_splitting, x = x, cl = cl, simplify = FALSE) } } else{ if (!is_simple(x)) x<-simplify(x) cl <- clusters(x) graph_splitting <- function(k, x, cl){ induced.subgraph(x, cl$membership == k) } components <- sapply(1:max(cl$membership), graph_splitting, x = x, cl = cl, simplify = FALSE) } } if( is.network(x)){ edgelist <- as.edgelist(x) x <- graph_from_edgelist(edgelist, directed = directed) if (!is_simple(x)) gr <- simplify(x) cl <- clusters(x) graph_splitting <- function(k, x, cl){ induced.subgraph(x, cl$membership == k) } components <- sapply(1:max(cl$membership), graph_splitting, x = x, cl = cl, simplify = FALSE) } summary.list <- lapply(components, function(x) summary(x)) } #' @title Summarize centrality measure calculation results #' @description This function computes the minimum, first quartile, median, #' mean, third quartile, and maximum values of the computed centrality measures. #' @param x Centrality measure calculation results, typically a numeric vector. #' @return A list summarizing the computed centrality measures. The list includes the following elements: #' - "minimum": The minimum value of the centrality measures. #' - "first_quartile": The first quartile (25th percentile) value of the centrality measures. #' - "median": The median (50th percentile) value of the centrality measures. #' - "mean": The mean value of the centrality measures. #' - "third_quartile": The third quartile (75th percentile) value of the centrality measures. #' - "maximum": The maximum value of the centrality measures. #' @author Minoo Ashtiani, Mehdi Mirzaie, Mohieddin Jafari #' @export #' @importFrom stats na.omit summary_calculate_centralities <- function(x){ x <- x[!sapply(x, is.null)] x <- na.omit(x) summary_list <- lapply(x, function(x) summary(x)) return(summary_list) } #' @title Summarize t-Distributed Stochastic Neighbor Embedding (t-SNE) on centrality measures #' #' @description This function summarizes the t-SNE analysis results on centrality measures. #' @param x A list containing the computed centrality values. #' @param dims An integer specifying the number of output dimensions (default = 2). #' @param perplexity A numeric value representing a flexible measure of the efficient number of neighbors. #' The performance of t-SNE is fairly robust to changes in perplexity, and typical values are between 5 and 50 (default = 5). #' @param scale A logical value indicating whether the centrality values should be scaled or not (default = TRUE). #' @seealso \code{\link[Rtsne]{Rtsne}} #' @return A list containing the following elements: #' - "Y": A matrix containing the new representations for the objects after t-SNE. #' - "costs": The cost for every object after the final iteration of t-SNE. #' The "costs" provide information about the optimization process. #' @author Minoo Ashtiani, Mehdi Mirzaie, Mohieddin Jafari #' @export #' @importFrom Rtsne Rtsne #' @importFrom stats na.omit summary_tsne_centralities<-function( x , dims = 2, perplexity = 5, scale = TRUE){ x <- x[!sapply(x, is.null)] x <- as.data.frame(x) x <- na.omit(x) if (scale%in%TRUE){ x <- scale(x, center = TRUE, scale = scale) x <- x[!duplicated(x), ] tsne.Y <- Rtsne(t(x), dims = dims, perplexity = perplexity, check_duplicates = FALSE)$Y rownames(tsne.Y)<-colnames(x) cost <- Rtsne(t(x), dims = dims, perplexity = perplexity ,check_duplicates = FALSE)$cost names(cost) <- colnames(x) tsne_cost <- sort(cost) res_tsne <- list(tsne.Y = tsne.Y, tsne_cost = tsne_cost) return(res_tsne) } else{ x <- x[!duplicated(x), ] tsne.Y <- Rtsne(t(x), dims = dims, perplexity = perplexity,check_duplicates = FALSE)$Y rownames(tsne.Y) <- colnames(x) cost <- Rtsne(t(x), dims = dims, perplexity = perplexity,check_duplicates = FALSE)$cost names(cost) <- colnames(x) tsne_cost <- sort(cost) res_tsne <- list(tsne.Y = tsne.Y,tsne_cost = tsne_cost) return(res_tsne) } } #' @title t-Distributed Stochastic Neighbor Embedding (t-SNE) on centrality measures #' #' @description This function applies t-SNE, a dimensionality reduction algorithm, to centrality measures. #' @param x A list containing the computed centrality values. #' @param dims An integer specifying the number of output dimensions (default = 2). #' @param perplexity A numeric value representing a flexible measure of the efficient number of neighbors. #' The performance of t-SNE is fairly robust to changes in perplexity, and typical values are between 5 and 50 (default = 5). #' @param scale A logical value indicating whether the centrality values should be scaled or not (default = TRUE). #' @details t-SNE is a non-linear dimensionality reduction algorithm used for exploring high-dimensional data. It maps multi-dimensional centrality measure data to a lower-dimensional space suitable for analysis and visualization. #' @seealso \code{\link[Rtsne]{Rtsne}} #' @return A cost plot of t-SNE results, which displays centralities in order of their corresponding costs. #' The cost plot provides information about the optimization process and the quality of the embedding. #' @author Minoo Ashtiani, Mehdi Mirzaie, Mohieddin Jafari #' @references #' van der Maaten, L. (2014). Accelerating t-SNE using Tree-Based Algorithms. Journal of Machine Learning Research, 15, 3221–3245. #' Van Der Maaten, L. J. P., & Hinton, G. E. (2008). Visualizing High-Dimensional Data Using t-SNE. Journal of Machine Learning Research, 9, 2579–2605. #' @export #' @importFrom Rtsne Rtsne #' @importFrom ggplot2 geom_bar #' @importFrom ggplot2 guides #' @importFrom ggplot2 xlab #' @importFrom ggplot2 ylab #' @importFrom ggplot2 ggtitle #' @importFrom ggplot2 theme #' @importFrom stats na.omit #' @importFrom stats reorder #' @return A cost plot of t-SNE results, which displays centralities in order of their corresponding costs. #' The cost plot is a ggplot object that represents the optimization process and the quality of the embedding. #' The x-axis represents the iterations of the t-SNE algorithm, and the y-axis represents the cost associated with each iteration. #' The cost measures the discrepancy between the original high-dimensional space and the low-dimensional embedding. #' By examining the cost plot, you can assess the convergence and stability of the t-SNE algorithm and evaluate the quality of the embedding. tsne_centralities <- function( x , dims = 2, perplexity = 5, scale = TRUE){ x <- x[!sapply(x,is.null)] x <- as.data.frame(x) x <- na.omit(x) if (scale%in%TRUE){ x <- scale(x, center = TRUE, scale = scale) x <- x[!duplicated(x), ] cost <- Rtsne(t(x), dims = dims, perplexity = perplexity,check_duplicates = FALSE)$cost names(cost) <- colnames(x) df <- data.frame(sort(cost)) ggplot(data=df, aes(x=reorder(rownames(df), -cost), y=cost, fill=rownames(df))) + geom_bar(colour="black", fill="turquoise", width=.8, stat="identity") + guides(fill=FALSE) + xlab("Centrality measures") + ylab("tsne costs") + ggtitle("tsne cost results")+ theme(axis.text.x=element_text(angle=45, vjust=0.5),plot.title = element_text(hjust = 0.5) ,panel.border = element_rect(colour = "black", fill=NA, size=1.5)) } else{ x <- x[!duplicated(x), ] cost <- Rtsne(t(x), dims = dims, perplexity = perplexity,check_duplicates = FALSE)$cost names(cost) <- colnames(x) df <- data.frame(sort(cost)) ggplot(data=df, aes(x=reorder(rownames(df), -cost), y=cost, fill=rownames(df))) + geom_bar(colour="black", fill="turquoise", width=.8, stat="identity") + guides(fill=FALSE) + xlab("Centrality measures") + ylab("tsne costs") + ggtitle("tsne cost results")+ theme(axis.text.x=element_text(angle=45, vjust=0.5), plot.title = element_text(hjust = 0.5) ,panel.border = element_rect(colour = "black", fill=NA, size=1.5)) } } #' @title Dangalchev Closeness Centrality #' #' @description This function computes the Dangalchev Closeness Centrality for nodes in a network. #' The Dangalchev Closeness Centrality measures closeness by removing nodes and edges, allowing for easier evaluation and handling of unconnected graphs. #' #' @param x An igraph or a network object. #' @param vids Nodes to be considered in the calculation. #' @param mode A character value indicating whether the shortest paths "in" or "out" of the nodes in directed graphs should be considered. For undirected graphs, use "all". #' @param weights A numeric vector indicating the weights of the edges. #' #' @seealso \code{\link[centiserve]{closeness.residual}} #' @return A numeric vector including the centrality values for each node. #' The centrality values represent the Dangalchev Closeness Centrality measure for each node in the network. #' @author Minoo Ashtiani, Mehdi Mirzaie, Mohieddin Jafari #' @references #' Dangalchev, C. (2006). Residual closeness in networks. Physica A: Statistical Mechanics and its Applications, 365, 556-564. DOI: 10.1016/j.physa.2005.12.020 #' #' @examples #' #' data(zachary) #' #' dangalchev_closeness_centrality(zachary) #' #' @export #' @importFrom igraph distances #' @importFrom igraph V #' @importFrom igraph is_igraph #' @importFrom igraph is_named #' @importFrom igraph getIgraphOpt #' @importFrom intergraph asIgraph dangalchev_closeness_centrality<-function (x, vids = V(x), mode = c("all", "out", "in"), weights = NULL){ if (!("igraph" %in% class(x) || "network" %in% class(x))) stop("The input is not an igraph or a network object") if (is_igraph(x)){ distMat<-1/2^distances(x) res <- rowSums(distMat) - diag(distMat) if (getIgraphOpt("add.vertex.names") && is_named(x)) { names(res) <- V(x)$name[vids] } } else{ x<-asIgraph(x) distMat<-1/2^distances(x) res <- rowSums(distMat) - diag(distMat) if (getIgraphOpt("add.vertex.names") && is_named(x)) { names(res) <- V(x)$name[vids] } } return(res) } #' @title Local Bridging Centrality #' #' @description This function computes the Local Bridging Centrality for nodes in a network. The Local Bridging Centrality classifies nodes based on their structural links among the dense components. #' #' @param x An igraph or a network object. #' @param vids Nodes to be considered in the calculation. #' #' @seealso \code{\link[igraph]{betweenness}} #' @return A numeric vector including the centrality values for each node. #' The centrality values represent the Local Bridging Centrality measure for each node in the network. #' @author Minoo Ashtiani, Mehdi Mirzaie, Mohieddin Jafari #' @references #' Macker, J.P. (2016). An improved local bridging centrality model for distributed network analytics. In Military Communications Conference, MILCOM 2016-2016 IEEE (pp. 600-605). IEEE. DOI: 10.1109/MILCOM.2016.7795393 #' #' @examples #' #' data(zachary) #' #' local_bridging_centrality(zachary) #' #' @export #' @importFrom igraph degree #' @importFrom igraph neighbors #' @importFrom igraph V #' @importFrom igraph is_igraph #' @importFrom igraph is_named #' @importFrom igraph getIgraphOpt #' @importFrom intergraph asIgraph local_bridging_centrality<-function (x, vids = V(x)){ if (!("igraph" %in% class(x)|| "network" %in% class(x))) stop("The input is not an igraph or a network object") f <- function(v){ (1/degree(x,v))/sum(1/degree(x,neighbors(x,v,'all')))} if (is_igraph(x)){ results <- sapply(V(x),f) if (getIgraphOpt("add.vertex.names") && is_named(x)) { names(results) <- V(x)$name[vids] } } else{ x<-asIgraph(x) results <- sapply(V(x),f) if (getIgraphOpt("add.vertex.names") && is_named(x)) { names(results) <- V(x)$name[vids] } } return(results) } #' @title Wiener Index Centrality #' #' @description This function computes the Wiener Index Centrality for nodes in a network. The Wiener index is a measure of centrality that computes the sum of all shortest paths between a node and all other related nodes in the graph. In essence, it is similar to closeness centrality, but without taking the reciprocal, resulting in a measure with the opposite meaning. #' #' @param x An igraph or a network object. #' @param vids Nodes to be considered in the calculation. #' @param mode A character value indicating whether the shortest paths "in" or "out" of the nodes in directed graphs should be considered. For undirected graphs, "all" is used. #' @param weights Numeric vector indicating weights of the edges. #' #' @return A numeric vector including the centrality values for each node. #' The centrality values represent the Wiener Index Centrality measure for each node in the network. #' @author Minoo Ashtiani, Mehdi Mirzaie, Mohieddin Jafari #' @references #' Scardoni, G. and Carlo Laudanna, C.B.M.C. (2011). Network centralities for Cytoscape. University of Verona. #' #' @examples #' #' data(zachary) #' #' wiener_index_centrality(zachary) #' #' @export #' @importFrom igraph shortest.paths #' @importFrom igraph V #' @importFrom igraph is_igraph #' @importFrom igraph is_named #' @importFrom igraph getIgraphOpt #' @importFrom intergraph asIgraph wiener_index_centrality<-function (x, vids = V(x), mode = c("all", "out", "in"), weights = NULL){ if (!("igraph" %in% class(x)||"network" %in% class(x))) stop("The input is not an igraph or a network object") if (is_igraph(x)){ distMat<- shortest.paths(x , mode = mode[1], weights = weights) diag(distMat)<-0 res <- rowSums(distMat) - diag(distMat) if (getIgraphOpt("add.vertex.names") && is_named(x)) { names(res) <- V(x)$name[vids] } } else{ x<-asIgraph(x) distMat<- shortest.paths(x , mode = mode[1], weights = weights) diag(distMat)<-0 res <- rowSums(distMat) - diag(distMat) if (getIgraphOpt("add.vertex.names") && is_named(x)) { names(res) <- V(x)$name[vids] } } return(res=res) } #' @title Harmonic Centrality #' #' @description This function computes the Harmonic Centrality for nodes in a network. The harmonic centrality metric is defined as the denormalized reciprocal of the harmonic mean of all distances. #' #' @param x An igraph or a network object. #' @param vids Nodes to be considered in the calculation. #' @param mode A character value, indicating the type of degree to consider ("out" for out-degree, "in" for in-degree, "total" for the sum of the two). For undirected graphs, this argument is ignored. The default value is "total". #' @param weights Numeric vector indicating weights of the edges. #' #' @return A numeric vector of centrality values for each node. The length of the vector is equal to the number of nodes in the network. #' #' @author Minoo Ashtiani, Mehdi Mirzaie, Mohieddin Jafari #' #' @references #' BOLDI, P. & VIGNA, S. 2014. Axioms for centrality. Internet Mathematics, 00-00. #' #' MARCHIORI, M. & LATORA, V. 2000. Harmony in the small-world. Physica A: Statistical Mechanics and its Applications, 285, 539-546. #' #' OPSAHL, T., AGNEESSENS, F. & SKVORETZ, J. 2010. Node centrality in weighted networks: Generalizing degree and shortest paths. Social Networks, 32, 245-251. #' #' OPSAHL, T. 2010. Closeness centrality in networks with disconnected components (http://toreopsahl.com/2010/03/20/closeness-centrality-in-networks-with-disconnected-components/) #' #' @examples #' #' data(zachary) #' #' harmonic_centrality(zachary) #' #' @export #' @importFrom igraph distances #' @importFrom igraph vcount #' @importFrom intergraph asIgraph #' @importFrom igraph degree #' @importFrom igraph neighbors #' @importFrom igraph V #' @importFrom igraph is_igraph #' @importFrom igraph is_named #' @importFrom igraph getIgraphOpt harmonic_centrality <- function (x, vids = V(x), mode = c("all", "out", "in"), weights = NULL){ if (!("igraph" %in% class(x) || "network" %in% class(x))) stop("The input is not an igraph or a network object") if (is_igraph(x)){ distMat<-1/distances(x, mode = mode[1], weights = weights) diag(distMat)<-0 res <- rowSums(distMat) - diag(distMat) if (getIgraphOpt("add.vertex.names") && is_named(x)) { names(res) <- V(x)$name[vids] } } else{ x<-asIgraph(x) distMat<-1/distances(x, mode = mode[1], weights = weights) diag(distMat)<-0 res <- rowSums(distMat) - diag(distMat) if (getIgraphOpt("add.vertex.names") && is_named(x)) { names(res) <- V(x)$name[vids] } } return(res) } #' @title Group Centrality #' #' @description This function computes the Group Centrality for nodes in a network. Group centrality considers a consistent ranking of each node to be calculated, taking into account the diverse possible synergies among possible groups of vertices. #' #' @param x An igraph or a network object. #' @param vids Nodes to be considered in the calculation. #' #' @return A numeric vector of centrality values for each node. The length of the vector is equal to the number of nodes in the network. #' #' @author Minoo Ashtiani, Mehdi Mirzaie, Mohieddin Jafari #' #' @references #' Michalak, T.P., Aadithya, K.V., Szczepanski, P.L., Ravindran, B. and Jennings, N.R., 2013. Efficient computation of the Shapley value for game-theoretic network centrality. Journal of Artificial Intelligence Research, 46, pp.607-650. #' #' https://www.civilica.com/Paper-IBIS07-IBIS07_127.html #' #' @examples #' #' data(zachary) #' #' group_centrality(zachary) #' #' @export #' @importFrom igraph neighbors #' @importFrom igraph degree #' @importFrom igraph V #' @importFrom igraph is_igraph #' @importFrom igraph is_named #' @importFrom igraph getIgraphOpt group_centrality<-function (x, vids = V(x)){ if (!("igraph" %in% class(x)|| "network" %in% class(x))) stop("The input is not an igraph or a network object") f <- function(v){ 1/(1 + degree(x,v)) + sum(1/(1+degree(x,neighbors(x,v,'all'))))} if (is_igraph(x)){ results <- sapply(V(x),f) if (getIgraphOpt("add.vertex.names") && is_named(x)) { names(results) <- V(x)$name[vids] } } else{ x<-asIgraph(x) results <- sapply(V(x),f) if (getIgraphOpt("add.vertex.names") && is_named(x)) { names(results) <- V(x)$name[vids] } } return(results) }
/scratch/gouwar.j/cran-all/cranData/CINNA/R/CINNA.R
#' @title Macaque Visual Cortex Network #' #' @description A graph describing the macaque visual cortex network. #' Nodes are neocortical areas, 25 of them are participated in visual function in the macaque, #' and 7 of which are associated with them #' @name cortex #' @docType data #' @usage data("cortex") #' @format an igraph object with "gml" format #' @references D.J. Felleman and D.C. van Essen, "Distributed hierarchical processing in the primate cerebral cortex." Cerebral Cortex 1(1), 1-47 (1991). #' @keywords datasets #' @examples #' data("cortex") #' print(cortex) NULL
/scratch/gouwar.j/cran-all/cranData/CINNA/R/Cortex.R
#' @title Drug Target Network #' #' @description A bipartite graph extracted from DrugBank 1.0 database. The network includes two set of nodes #' including Food and Drug Administration (FDA)-approved drugs and their corresponding protein targets designated by their Uniprot ID. #' The 1080 drugs and their 519 target proteins nodes are connected via 3766 interactions. #' Please note that it is a shrunken network in which metabolizing enzymes, #' carriers and transporters associated with drug metabolism are filtered and solely #' targets directly related to their pharmacological effects are included. #' It is also an example of unconnected graphs. #' @name drugTarget #' @docType data #' @usage drugTarget #' @format an igraph object with "gml" format #' @references Barneh, F., Jafari, M., & Mirzaie, M. (2015). Updates on drug–target network; facilitating polypharmacology and data integration by growth of DrugBank database. Briefings in Bioinformatics, bbv094. https://doi.org/10.1093/bib/bbv094 #' @keywords datasets #' @examples #' data("drugTarget") #' print(drugTarget) NULL
/scratch/gouwar.j/cran-all/cranData/CINNA/R/Drugtarget.R
#' @title Kangaroo Network #' #' @description An undirected graph based on interactions between free-ranging grey kangaroos. #' A node displays a kangaroo and an edge between two kangaroos demonstrates an interaction. #' The weights indicate the total count of interactions. #' @name kangaroo #' @docType data #' @usage kangaroo #' @format an igraph object with "gml" format #' @references Kangaroo network dataset -- KONECT, October 2016. #' #' TR Grant. Dominance and association among members of a captive and a free-ranging group of grey kangaroos (Macropus giganteus). Animal Behaviour, 21(3):449--456, 1973. #' @keywords datasets #' @examples #' data("kangaroo") #' print(kangaroo) NULL
/scratch/gouwar.j/cran-all/cranData/CINNA/R/Kangaroo.R
#' @title Moreno Rhesus Network #' #' @description A directed graph including observed grooming episodes between #' free ranging rhesus macaques (Macaca mulatta) in Cayo Santiago #' during a two month period in 1963. Cayo Santiago is an island off the coast of Puerto Rico, #' which also is named as Isla de los monos (Island of the monkeys). #' A node indicates a monkey and a directed edge in which #' a rhesus macaque groomed another rhesus macaque. #' The weights of edges demonstrates how often this behaviour #' was seen. #' @name rhesus #' @docType data #' @usage rhesus #' @format an igraph object with "gml" format #' @references Rhesus network dataset -- KONECT, October 2016. #' #' DS Sade. Sociometrics of macaca mulatta I. linkages and cliques in grooming matrices. Folia Primatologica, 18(3-4):196--223, 1972. #' @keywords datasets #' @examples #' data("rhesus") #' print(rhesus) NULL
/scratch/gouwar.j/cran-all/cranData/CINNA/R/Rhesus.R
#' @title Zachary Karate Club Network #' #' @description A graph describing friendships among members of a university #' karate club. Includes metadata for faction membership after a social #' partition. #' @name zachary #' @docType data #' @usage zachary #' @format an igraph object with "gml" format #' @references W. W. Zachary, "An information flow model for conflict and fission in small groups." Journal of Anthropological Research 33, 452-473 (1977). #' @keywords datasets #' @examples #' data("zachary") #' print(zachary) NULL
/scratch/gouwar.j/cran-all/cranData/CINNA/R/Zachary.R
## ---- eval=F, echo=T---------------------------------------------------------- # # install.packages("CINNA") # ## ----------------------------------------------------------------------------- library(CINNA) ## ----warning=FALSE,message=FALSE---------------------------------------------- data("zachary") zachary ## ----warning=FALSE,message=FALSE---------------------------------------------- graph_extract_components(zachary) ## ----------------------------------------------------------------------------- data("drugTarget") drug_comp <- graph_extract_components( drugTarget, directed = TRUE, bipartite_proj = TRUE, num_proj = 1) head(drug_comp) ## ----warning=FALSE,message=FALSE---------------------------------------------- library(igraph) zachary_edgelist <- as_edgelist(zachary) misc_extract_components(zachary_edgelist) ## ----warning=FALSE,message=FALSE---------------------------------------------- giant_component_extract(zachary) ## ----warning=FALSE,message=FALSE---------------------------------------------- proper_centralities(zachary) ## ----warning=FALSE, message=FALSE--------------------------------------------- calculate_centralities(zachary, include = "Degree Centrality") ## ----warning=FALSE,message=FALSE---------------------------------------------- pr_cent <- proper_centralities(zachary) calc_cent <- calculate_centralities(zachary, include = pr_cent[1:10]) ## ----fig.width=7, fig.height=6,message=FALSE, fig.cap = "A display of most informative centrality measures based on principal component analysis. The red line indicates the random threshold of contribution. This barplot represents contribution of variable values based on the number of dimensions."---- pca_centralities( calc_cent ) ## ----fig.width=7, fig.height=6,message=FALSE, fig.cap = "A representation of most informative centrality measures based on principal component analysis between unscaled(not normalized) centrality values."---- pca_centralities( calc_cent , scale.unit = FALSE ) ## ----fig.width=7, fig.height=6,message=FALSE, fig.cap = "A display of most informative centrality measures based on t-Distributed Stochastic Neighbor Embedding analysis among scaled(not normalized) centrality values."---- tsne_centralities( calc_cent, dims = 2, perplexity = 1, scale=TRUE) ## ----fig.width=7, fig.height=6,message=FALSE, fig.cap = " Graph illustration based on centrality measure. The size of nodes represent the degree centrality values."---- visualize_graph( zachary , centrality.type="Degree Centrality") ## ----fig.width=7, fig.height=6,message=FALSE, fig.cap = "Observed centrality measure heatmap. The colors from blue to red displays scaled centrality values."---- visualize_heatmap( calc_cent , scale = TRUE ) ## ----fig.width=7, fig.height=6,message=FALSE, fig.cap = "A display of correlation among computed centrality measures. The red to blue highlighted circles represent the top to bottom Pearson correlation coefficients[@Benesty2009] which differ from -1 to 1. The higher the value becomes larger, circles' sizes get larger too."---- visualize_correlations(calc_cent,"pearson") ## ----fig.width=7, fig.height=6,message=FALSE, fig.cap = "Circular dendrogram plot of vertices based on specified centrality measure. Each color represents a cluster."---- visualize_dendrogram(zachary, k=4) ## ----fig.width=7, fig.height=6, warning=FALSE, message=FALSE, fig.cap = "Association plot between two centrality variables. The red line is an indicator of linear regression line among them."---- subgraph_cent <- calc_cent[[1]] Topological_coef <- calc_cent[[2]] visualize_association( subgraph_cent , Topological_coef) ## ----fig.width=7, fig.height=6,message=FALSE, fig.cap = "Pairwise Pearson correlation between two centrality values."---- visualize_pair_correlation( subgraph_cent , Topological_coef)
/scratch/gouwar.j/cran-all/cranData/CINNA/inst/doc/CINNA.R
--- title: "CINNA" author: "Minoo Ashtiani, Mehdi Mirzaie, Mohieddin Jafari" date: "`r Sys.Date()`" output: rmarkdown::html_vignette: toc: true toc_depth: 3 bibliography: bibliography.bib vignette: > %\VignetteIndexEntry{CINNA} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ## 1 Introduction `CINNA` is an R package submitted on CRAN repository which has been written for centrality analysis in network science. It can be useful for assembling, comparing, evaluating and visualizing several types of centrality measures. This document is an introduction to the usage of this package and includes some user interface examples. Centrality is defined as a measure for identifying the most important vertices within a network in graph theory. Several centrality types have been provided to compute central nodes by different formulas, while some analysis are needed to evaluate the most informative ones. In this package, we have prepared these resolutions and some examples of real networks. For the examples in the following sections, we assume that the `CINNA` package has been properly installed into the R environment. This can be done by typing ```{r, eval=F, echo=T} install.packages("CINNA") ``` into the R console. The `igraph`[@Csardi2006] ,`network`[@Butts2015;@Butts2008],`sna`[@ButtsCT2008;@Butts2007] and `centiserve`[@Jalili2015] packages are required and must be installed in your R environment as well. These are analogous to installing `CINNA` and for more other calculations, packages such as `FactoMineR`[@Sebastien2008], `plyr`[@Wickham2011] `qdapTools`[@Rinker2015], `Rtsne`[@Krijthe2015] are necessary. For some plots, `factoextra`[@Kassambara2015], `GGally`[@Barret2016], `pheatmap`[@kolde2015], `corrplot`[@Taiyun2016], `dendextend`[@Galili2015], `circlize`[@Gu2014], `viridis`[@Garnier2017] and `ggplot2`[@Wickham2016] packages must be installed too. After installations, the `CINNA` package can be loaded via ```{r} library(CINNA) ``` ## 2 Some real network examples We collected five graphs instances based on factual datasets and natural networks. In order to develop some instructions for using this package, we prepared you a brief introduction about the topological of these networks as is described below: | Name | Type | Description | Nodes | Edges | References | |:----------:|:----------------------:|:------------------------------------------------:|:-----:|:------:|:---------------:| | zachary | unweighted, undirected | friendships between members of a club | 34 | 78 | [@Zachary1977] | | cortex | unweighted, directed | pathways among cortical region in Macaque | 30 | 311 | [@Felleman1991] | | kangaroo | weighted, undirected | interactions between kangaroos | 17 | 90 | [@Kangaroo2016] | | rhesus | weighted, directed | grooming occurred among monkeys of an area | 16 | 110 | [@Rhesus2016] | | drugTarget | bipartite,directed |interactions among drugs and their protein targets| 1599 | 3766 | [@Barneh2015] | ### 2.1 Undirected & unweighted network `zachary`[@Zachary1977] is an example of undirected and unweighted network in this package. This data set illustrates friendships between members of a university karate club. It is based on a faction membership after a social portion. The summary of important properties of this network is described below: Edge Type: Friendship Node Type: People Avg Edges: 77.50 Avg Nodes: 34.00 Graph properties: Unweighted, Undirected This data set can be easily accessed by using data() function: ```{r warning=FALSE,message=FALSE} data("zachary") zachary ``` The result would have a class of "igraph" object. ### 2.2 Undirected & weighted network `kangaroo`[@Kangaroo2016] is a sample of undirected and weighted network which indicates interactions among free-ranging grey kangaroos. The edge between two nodes shows a dominance interaction between two kangaroos. The positive weight of each edge represents number of interaction between them. A brief explanation of it's properties is clarified below: Edge Type: Interaction Node Type: Kangaroo Avg Edges: 91 Nodes: 17 Graph properties: Weighted, Undirected Edge weights: Positive weights ### 2.3 Directed & unweighted network `cortex`[@Felleman1991] is a sample of macaque visual cortex network which is collected in 1991. In this data set, vertices represents neocortical areas which involved in visual functions in Macaques. The direction displays the progress of synapses from one to another. A summary of this can be as follows: Edge Type: Pathway Node Type: Cortical region Avg Edges: 315.50 Nodes: 31.00 Graph properties: Directed, Unweighted Edge weights: Positive weights ### 2.4 Directed & weighted network `rhesus`[@Rhesus2016] is a directed and weighted network which describes grooming between free ranging rhesus macaques (Macaca mulatta) in Cayo Santiago during a two month period in 1963. In this data set a vertex is identified as a monkey and the directed edge among them means grooming between them. The weights of the edges demonstrates how often this manner happened. The network summary is as follows: Edge Type: Grooming Node Type: Monkey Avg Edges: 111 Nodes: 16 Graph properties: Directed, Weighted Edge weights: Positive weights ### 2.5 Bipartite & directed network `drugTarget`[@Barneh2015] is a bipartite, unconnected and directed network demonstrating interactions among Food and Drug Administration (FDA)-approved drugs and their corresponding protein targets. This network is a shrunken one in which metabolizing enzymes, carriers and transporters associated with drug metabolism are filtered and solely targets directly related to their pharmacological effects are included. A summary of this can be like: Edge Type: interaction Node Type: drug, protein target Avg Edges: 3766 Nodes: 1599 Graph properties: Bipartite, unconnected, directed ## 3 Network component analysis In order to apply several centrality analysis, it is recommended to have a connected graph. Therefore, approaching the connected components of a network is needed. In order to extract components of a graph and use them for centrality analysis, we prepared some functions as below. ### 3.1 The segregation of "igraph" and "network" objects "graph.extract.components" function is able to read `igraph` and `network` objects and returns their components as a list of `igraph` objects. This function also has this ability to recognized bipartite graphs and user can decide that which project is suitable for his analysis. In order to use this function, we use zachary data set and develop it in all of our functions. ```{r warning=FALSE,message=FALSE} graph_extract_components(zachary) ``` This results the only component of the zachary graph. This function is also applicable for bipartite networks. Using the `num_proj` argument, user can decide on which projection is interested to work on. As an example of bipartite graphs, we use `drugTarget` network as follows: ```{r} data("drugTarget") drug_comp <- graph_extract_components( drugTarget, directed = TRUE, bipartite_proj = TRUE, num_proj = 1) head(drug_comp) ``` It will return all components of the second projection of the network. ### 3.2 The segregation of other graph formats If you had an edge list, an adjacency matrix or a grapnel format of a network, the `misc_extract_components` can be useful. This function extracts the components of other formats of graph. For illustration, we convert `zachary` graph to an edge list to be able to use it for this function. ```{r warning=FALSE,message=FALSE} library(igraph) zachary_edgelist <- as_edgelist(zachary) misc_extract_components(zachary_edgelist) ``` ### 3.3 Giant component extraction In the most of research topics of network analysis, network features are related to the largest connected component of a graph[@Newman2010]. In order to get that for an `igraph` or a `network` object, `giant_component_extract` function is specified. For using this function we can do: ```{r warning=FALSE,message=FALSE} giant_component_extract(zachary) ``` This function extracts the strongest components of the input network as `igraph` objects. ## 4 Centrality measure analysis This section particularly is specified for centrality analysis in network science. ### 4.1 Suggestion of proper centralities All of the introduced centrality measures are not appropriate for all types of networks. So, to figure out which of them is suitable, `proper_centralities` is specified. This function distinguishes proper centrality types based on network topology. To use this, we can do: ```{r warning=FALSE,message=FALSE} proper_centralities(zachary) ``` It returns the full names of suitable centrality types for the input graph. The input must have a class of `igraph` object. ### 4.2 Centrality computations In the next step, proper centralities and those which are looking for can be chosen. In order to compute proper centrality types resulted from the `proper_centralities`, you can use `calculate_centralities` function as below. ```{r warning=FALSE, message=FALSE} calculate_centralities(zachary, include = "Degree Centrality") ``` In this function, you have the ability to specify some centrality types that is not your favor to calculate by the `conclude` argument. Here, we will select first ten centrality measures for an illustration: ```{r warning=FALSE,message=FALSE} pr_cent <- proper_centralities(zachary) calc_cent <- calculate_centralities(zachary, include = pr_cent[1:10]) ``` The result would be a list of computed centralities. ### 4.3 Recognition of most informative measures In order to figure out the order of most important centrality types based on your graph structure, `pca_centralities` function can be used. This applies principal component analysis on the computed centrality values[@Husson2010]. For this, the result of `calculate_centralities` method is needed: ```{r fig.width=7, fig.height=6,message=FALSE, fig.cap = "A display of most informative centrality measures based on principal component analysis. The red line indicates the random threshold of contribution. This barplot represents contribution of variable values based on the number of dimensions."} pca_centralities( calc_cent ) ``` For choosing the number of principal components, we considered cumulative percentage of variance values which are more than 80 as the cut off which can be edited using `cut.off` argument. It returns a plot for visualizing contribution values of the computed centrality measures due to the number of principal components. The `scale.unit` argument gives the ability to whether it should normalize the input or not. ```{r fig.width=7, fig.height=6,message=FALSE, fig.cap = "A representation of most informative centrality measures based on principal component analysis between unscaled(not normalized) centrality values."} pca_centralities( calc_cent , scale.unit = FALSE ) ``` Another method for distinguishing which centrality measure has more information or in another words has more costs is using (t-SNE) t-Distributed Stochastic Neighbor Embedding analysis[@VanDerMaaten2014]. This is a non-linear dimensional reduction algorithm used for high-dimensional data. `tsne_centralities` function applies t-sne on centrality measure values like below: ```{r fig.width=7, fig.height=6,message=FALSE, fig.cap = "A display of most informative centrality measures based on t-Distributed Stochastic Neighbor Embedding analysis among scaled(not normalized) centrality values."} tsne_centralities( calc_cent, dims = 2, perplexity = 1, scale=TRUE) ``` This returns the bar plot of computed cost values of each centrality measure on a plot. In order to access only computed values of PCA and t-sne methods, `summary_pca_centralities` and `tsne_centralities` functions can be helpful. ## 5 visualization of centrality analysis To visualize the results of network centrality analysis some convenient functions have been developed as it described below. ### 5.1 Graph visualization regarding to the centrality type After evaluating centrality measures, demonstrating high values of centralities in some nodes gives an overall insight about the network to the researcher. By using `visualize_graph` function, you will be able to illustrate the input graph based on the specified centrality value. If the centrality measure values were computed, `computed.centrality.value` argument is recommended. Otherwise, using `centrality.type` argument, the function will compute centrality based on the input name of centrality type. For practice, we specifies `Degree Centrality`. Here, ```{r fig.width=7, fig.height=6,message=FALSE, fig.cap = " Graph illustration based on centrality measure. The size of nodes represent the degree centrality values."} visualize_graph( zachary , centrality.type="Degree Centrality") ``` ### 5.2 Heatmap of centrality measure values On of the way of complex large network visualizations(more than 100 nodes and 200 edges) is using heat map[@Pryke2007]. `visualize_heatmap` function demonstrates a heat map plot between the centrality values. The input is a list containing the computed values. ```{r fig.width=7, fig.height=6,message=FALSE, fig.cap = "Observed centrality measure heatmap. The colors from blue to red displays scaled centrality values."} visualize_heatmap( calc_cent , scale = TRUE ) ``` ### 5.3 Correlation between computed centrality measures Comprehending pair correlation among centralities is a popular analysis for researchers[@Dwyer2006]. In order to that, `visualize_correlations` method is appropriate. In this you are able to specify the type of correlation which you are enthusiastic to obtain. ```{r fig.width=7, fig.height=6,message=FALSE, fig.cap = "A display of correlation among computed centrality measures. The red to blue highlighted circles represent the top to bottom Pearson correlation coefficients[@Benesty2009] which differ from -1 to 1. The higher the value becomes larger, circles' sizes get larger too."} visualize_correlations(calc_cent,"pearson") ``` ### 5.4 Node dendrogram based on a centrality type In order to visualize a simple clustering across the nodes of a graph based on a specific centrality measure, we can use the `visualize_dendrogram` function. This function draw a dendrogram plot in which colors indicate the clusters. ```{r fig.width=7, fig.height=6,message=FALSE, fig.cap = "Circular dendrogram plot of vertices based on specified centrality measure. Each color represents a cluster."} visualize_dendrogram(zachary, k=4) ``` ### 5.5 Regression across centrality measures In this package additionally to correlation calculation, ability to apply linear regression for each pair of centralities has been prepared to realize the association between centralities. For visualization, `visualize_association` method is an appropriate function to use: ```{r fig.width=7, fig.height=6, warning=FALSE, message=FALSE, fig.cap = "Association plot between two centrality variables. The red line is an indicator of linear regression line among them."} subgraph_cent <- calc_cent[[1]] Topological_coef <- calc_cent[[2]] visualize_association( subgraph_cent , Topological_coef) ``` ### 5.6 Pairwise correlation between centrality types To access the distribution of centrality values and their corresponding pair correlation value, `visualize_pair_correlation` would be helpful. The Pearson correlation[@Benesty2009] has been used for this method. ```{r fig.width=7, fig.height=6,message=FALSE, fig.cap = "Pairwise Pearson correlation between two centrality values."} visualize_pair_correlation( subgraph_cent , Topological_coef) ``` The result is a scatter plot visualizing correlation values. # References
/scratch/gouwar.j/cran-all/cranData/CINNA/inst/doc/CINNA.Rmd
--- title: "CINNA" author: "Minoo Ashtiani, Mehdi Mirzaie, Mohieddin Jafari" date: "`r Sys.Date()`" output: rmarkdown::html_vignette: toc: true toc_depth: 3 bibliography: bibliography.bib vignette: > %\VignetteIndexEntry{CINNA} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ## 1 Introduction `CINNA` is an R package submitted on CRAN repository which has been written for centrality analysis in network science. It can be useful for assembling, comparing, evaluating and visualizing several types of centrality measures. This document is an introduction to the usage of this package and includes some user interface examples. Centrality is defined as a measure for identifying the most important vertices within a network in graph theory. Several centrality types have been provided to compute central nodes by different formulas, while some analysis are needed to evaluate the most informative ones. In this package, we have prepared these resolutions and some examples of real networks. For the examples in the following sections, we assume that the `CINNA` package has been properly installed into the R environment. This can be done by typing ```{r, eval=F, echo=T} install.packages("CINNA") ``` into the R console. The `igraph`[@Csardi2006] ,`network`[@Butts2015;@Butts2008],`sna`[@ButtsCT2008;@Butts2007] and `centiserve`[@Jalili2015] packages are required and must be installed in your R environment as well. These are analogous to installing `CINNA` and for more other calculations, packages such as `FactoMineR`[@Sebastien2008], `plyr`[@Wickham2011] `qdapTools`[@Rinker2015], `Rtsne`[@Krijthe2015] are necessary. For some plots, `factoextra`[@Kassambara2015], `GGally`[@Barret2016], `pheatmap`[@kolde2015], `corrplot`[@Taiyun2016], `dendextend`[@Galili2015], `circlize`[@Gu2014], `viridis`[@Garnier2017] and `ggplot2`[@Wickham2016] packages must be installed too. After installations, the `CINNA` package can be loaded via ```{r} library(CINNA) ``` ## 2 Some real network examples We collected five graphs instances based on factual datasets and natural networks. In order to develop some instructions for using this package, we prepared you a brief introduction about the topological of these networks as is described below: | Name | Type | Description | Nodes | Edges | References | |:----------:|:----------------------:|:------------------------------------------------:|:-----:|:------:|:---------------:| | zachary | unweighted, undirected | friendships between members of a club | 34 | 78 | [@Zachary1977] | | cortex | unweighted, directed | pathways among cortical region in Macaque | 30 | 311 | [@Felleman1991] | | kangaroo | weighted, undirected | interactions between kangaroos | 17 | 90 | [@Kangaroo2016] | | rhesus | weighted, directed | grooming occurred among monkeys of an area | 16 | 110 | [@Rhesus2016] | | drugTarget | bipartite,directed |interactions among drugs and their protein targets| 1599 | 3766 | [@Barneh2015] | ### 2.1 Undirected & unweighted network `zachary`[@Zachary1977] is an example of undirected and unweighted network in this package. This data set illustrates friendships between members of a university karate club. It is based on a faction membership after a social portion. The summary of important properties of this network is described below: Edge Type: Friendship Node Type: People Avg Edges: 77.50 Avg Nodes: 34.00 Graph properties: Unweighted, Undirected This data set can be easily accessed by using data() function: ```{r warning=FALSE,message=FALSE} data("zachary") zachary ``` The result would have a class of "igraph" object. ### 2.2 Undirected & weighted network `kangaroo`[@Kangaroo2016] is a sample of undirected and weighted network which indicates interactions among free-ranging grey kangaroos. The edge between two nodes shows a dominance interaction between two kangaroos. The positive weight of each edge represents number of interaction between them. A brief explanation of it's properties is clarified below: Edge Type: Interaction Node Type: Kangaroo Avg Edges: 91 Nodes: 17 Graph properties: Weighted, Undirected Edge weights: Positive weights ### 2.3 Directed & unweighted network `cortex`[@Felleman1991] is a sample of macaque visual cortex network which is collected in 1991. In this data set, vertices represents neocortical areas which involved in visual functions in Macaques. The direction displays the progress of synapses from one to another. A summary of this can be as follows: Edge Type: Pathway Node Type: Cortical region Avg Edges: 315.50 Nodes: 31.00 Graph properties: Directed, Unweighted Edge weights: Positive weights ### 2.4 Directed & weighted network `rhesus`[@Rhesus2016] is a directed and weighted network which describes grooming between free ranging rhesus macaques (Macaca mulatta) in Cayo Santiago during a two month period in 1963. In this data set a vertex is identified as a monkey and the directed edge among them means grooming between them. The weights of the edges demonstrates how often this manner happened. The network summary is as follows: Edge Type: Grooming Node Type: Monkey Avg Edges: 111 Nodes: 16 Graph properties: Directed, Weighted Edge weights: Positive weights ### 2.5 Bipartite & directed network `drugTarget`[@Barneh2015] is a bipartite, unconnected and directed network demonstrating interactions among Food and Drug Administration (FDA)-approved drugs and their corresponding protein targets. This network is a shrunken one in which metabolizing enzymes, carriers and transporters associated with drug metabolism are filtered and solely targets directly related to their pharmacological effects are included. A summary of this can be like: Edge Type: interaction Node Type: drug, protein target Avg Edges: 3766 Nodes: 1599 Graph properties: Bipartite, unconnected, directed ## 3 Network component analysis In order to apply several centrality analysis, it is recommended to have a connected graph. Therefore, approaching the connected components of a network is needed. In order to extract components of a graph and use them for centrality analysis, we prepared some functions as below. ### 3.1 The segregation of "igraph" and "network" objects "graph.extract.components" function is able to read `igraph` and `network` objects and returns their components as a list of `igraph` objects. This function also has this ability to recognized bipartite graphs and user can decide that which project is suitable for his analysis. In order to use this function, we use zachary data set and develop it in all of our functions. ```{r warning=FALSE,message=FALSE} graph_extract_components(zachary) ``` This results the only component of the zachary graph. This function is also applicable for bipartite networks. Using the `num_proj` argument, user can decide on which projection is interested to work on. As an example of bipartite graphs, we use `drugTarget` network as follows: ```{r} data("drugTarget") drug_comp <- graph_extract_components( drugTarget, directed = TRUE, bipartite_proj = TRUE, num_proj = 1) head(drug_comp) ``` It will return all components of the second projection of the network. ### 3.2 The segregation of other graph formats If you had an edge list, an adjacency matrix or a grapnel format of a network, the `misc_extract_components` can be useful. This function extracts the components of other formats of graph. For illustration, we convert `zachary` graph to an edge list to be able to use it for this function. ```{r warning=FALSE,message=FALSE} library(igraph) zachary_edgelist <- as_edgelist(zachary) misc_extract_components(zachary_edgelist) ``` ### 3.3 Giant component extraction In the most of research topics of network analysis, network features are related to the largest connected component of a graph[@Newman2010]. In order to get that for an `igraph` or a `network` object, `giant_component_extract` function is specified. For using this function we can do: ```{r warning=FALSE,message=FALSE} giant_component_extract(zachary) ``` This function extracts the strongest components of the input network as `igraph` objects. ## 4 Centrality measure analysis This section particularly is specified for centrality analysis in network science. ### 4.1 Suggestion of proper centralities All of the introduced centrality measures are not appropriate for all types of networks. So, to figure out which of them is suitable, `proper_centralities` is specified. This function distinguishes proper centrality types based on network topology. To use this, we can do: ```{r warning=FALSE,message=FALSE} proper_centralities(zachary) ``` It returns the full names of suitable centrality types for the input graph. The input must have a class of `igraph` object. ### 4.2 Centrality computations In the next step, proper centralities and those which are looking for can be chosen. In order to compute proper centrality types resulted from the `proper_centralities`, you can use `calculate_centralities` function as below. ```{r warning=FALSE, message=FALSE} calculate_centralities(zachary, include = "Degree Centrality") ``` In this function, you have the ability to specify some centrality types that is not your favor to calculate by the `conclude` argument. Here, we will select first ten centrality measures for an illustration: ```{r warning=FALSE,message=FALSE} pr_cent <- proper_centralities(zachary) calc_cent <- calculate_centralities(zachary, include = pr_cent[1:10]) ``` The result would be a list of computed centralities. ### 4.3 Recognition of most informative measures In order to figure out the order of most important centrality types based on your graph structure, `pca_centralities` function can be used. This applies principal component analysis on the computed centrality values[@Husson2010]. For this, the result of `calculate_centralities` method is needed: ```{r fig.width=7, fig.height=6,message=FALSE, fig.cap = "A display of most informative centrality measures based on principal component analysis. The red line indicates the random threshold of contribution. This barplot represents contribution of variable values based on the number of dimensions."} pca_centralities( calc_cent ) ``` For choosing the number of principal components, we considered cumulative percentage of variance values which are more than 80 as the cut off which can be edited using `cut.off` argument. It returns a plot for visualizing contribution values of the computed centrality measures due to the number of principal components. The `scale.unit` argument gives the ability to whether it should normalize the input or not. ```{r fig.width=7, fig.height=6,message=FALSE, fig.cap = "A representation of most informative centrality measures based on principal component analysis between unscaled(not normalized) centrality values."} pca_centralities( calc_cent , scale.unit = FALSE ) ``` Another method for distinguishing which centrality measure has more information or in another words has more costs is using (t-SNE) t-Distributed Stochastic Neighbor Embedding analysis[@VanDerMaaten2014]. This is a non-linear dimensional reduction algorithm used for high-dimensional data. `tsne_centralities` function applies t-sne on centrality measure values like below: ```{r fig.width=7, fig.height=6,message=FALSE, fig.cap = "A display of most informative centrality measures based on t-Distributed Stochastic Neighbor Embedding analysis among scaled(not normalized) centrality values."} tsne_centralities( calc_cent, dims = 2, perplexity = 1, scale=TRUE) ``` This returns the bar plot of computed cost values of each centrality measure on a plot. In order to access only computed values of PCA and t-sne methods, `summary_pca_centralities` and `tsne_centralities` functions can be helpful. ## 5 visualization of centrality analysis To visualize the results of network centrality analysis some convenient functions have been developed as it described below. ### 5.1 Graph visualization regarding to the centrality type After evaluating centrality measures, demonstrating high values of centralities in some nodes gives an overall insight about the network to the researcher. By using `visualize_graph` function, you will be able to illustrate the input graph based on the specified centrality value. If the centrality measure values were computed, `computed.centrality.value` argument is recommended. Otherwise, using `centrality.type` argument, the function will compute centrality based on the input name of centrality type. For practice, we specifies `Degree Centrality`. Here, ```{r fig.width=7, fig.height=6,message=FALSE, fig.cap = " Graph illustration based on centrality measure. The size of nodes represent the degree centrality values."} visualize_graph( zachary , centrality.type="Degree Centrality") ``` ### 5.2 Heatmap of centrality measure values On of the way of complex large network visualizations(more than 100 nodes and 200 edges) is using heat map[@Pryke2007]. `visualize_heatmap` function demonstrates a heat map plot between the centrality values. The input is a list containing the computed values. ```{r fig.width=7, fig.height=6,message=FALSE, fig.cap = "Observed centrality measure heatmap. The colors from blue to red displays scaled centrality values."} visualize_heatmap( calc_cent , scale = TRUE ) ``` ### 5.3 Correlation between computed centrality measures Comprehending pair correlation among centralities is a popular analysis for researchers[@Dwyer2006]. In order to that, `visualize_correlations` method is appropriate. In this you are able to specify the type of correlation which you are enthusiastic to obtain. ```{r fig.width=7, fig.height=6,message=FALSE, fig.cap = "A display of correlation among computed centrality measures. The red to blue highlighted circles represent the top to bottom Pearson correlation coefficients[@Benesty2009] which differ from -1 to 1. The higher the value becomes larger, circles' sizes get larger too."} visualize_correlations(calc_cent,"pearson") ``` ### 5.4 Node dendrogram based on a centrality type In order to visualize a simple clustering across the nodes of a graph based on a specific centrality measure, we can use the `visualize_dendrogram` function. This function draw a dendrogram plot in which colors indicate the clusters. ```{r fig.width=7, fig.height=6,message=FALSE, fig.cap = "Circular dendrogram plot of vertices based on specified centrality measure. Each color represents a cluster."} visualize_dendrogram(zachary, k=4) ``` ### 5.5 Regression across centrality measures In this package additionally to correlation calculation, ability to apply linear regression for each pair of centralities has been prepared to realize the association between centralities. For visualization, `visualize_association` method is an appropriate function to use: ```{r fig.width=7, fig.height=6, warning=FALSE, message=FALSE, fig.cap = "Association plot between two centrality variables. The red line is an indicator of linear regression line among them."} subgraph_cent <- calc_cent[[1]] Topological_coef <- calc_cent[[2]] visualize_association( subgraph_cent , Topological_coef) ``` ### 5.6 Pairwise correlation between centrality types To access the distribution of centrality values and their corresponding pair correlation value, `visualize_pair_correlation` would be helpful. The Pearson correlation[@Benesty2009] has been used for this method. ```{r fig.width=7, fig.height=6,message=FALSE, fig.cap = "Pairwise Pearson correlation between two centrality values."} visualize_pair_correlation( subgraph_cent , Topological_coef) ``` The result is a scatter plot visualizing correlation values. # References
/scratch/gouwar.j/cran-all/cranData/CINNA/vignettes/CINNA.Rmd
#' Total Aberration Index #' #' Total Aberration Index calculation takes the sum of lengths of each segment #' times its segmentation mean for each sample and divides it by the sum of the #' lengths of each sample. #' #' The Total Aberration Index (TAI) \href{https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3553118/}{(Baumbusch LO, et. al.)} is ``a measure of the abundance of genomic size of copy number changes in a tumour". #' It is defined as a weighted sum of the segment means #' \deqn{ #' Total\ Aberration\ Index = #' \frac #' {\sum^{R}_{i = 1} {d_i} \cdot |{\bar{y}_{S_i}}|} #' {\sum^{R}_{i = 1} {d_i}}\ \ #' where |\bar{y}_{S_i}| \ge |\log_2 1.7| #' } #' #' @param cnvData dataframe containing following columns: Sample, Start, End, Num_Probes, Segment_Mean #' @param segmentMean numerical value for the minimum segment_mean cutoff/ threshold. Default is 0.2 #' @param numProbes Number of Probes #' @return Average of lengths weighted by segmentation mean for each unique sample #' @examples tai(cnvData = maskCNV_BRCA) #' @export tai <- function(cnvData, segmentMean = 0.2, numProbes = NA ){ unique_id <- unique(cnvData$Sample) tai.output <- stats::setNames(data.frame(matrix(ncol = 2, nrow = length(unique_id)), stringsAsFactors = FALSE),c("sample_id","tai")) for (i in 1:length(unique_id)){ id <- unique_id[i] subsetSample <- subset(cnvData, cnvData$Sample == id) subsetSample <- subset(subsetSample, abs(subsetSample$Segment_Mean) >= segmentMean) if (!is.na(numProbes)){ subsetSample <- subset(subsetSample, abs(subsetSample$Num_Probes) >= numProbes) } Length <- subsetSample$End - subsetSample$Start num <- Length*abs(subsetSample$Segment_Mean) #num <- Length*abs(subsetSample$Segment_Mean) den <- Length tai.calc <- sum(sum(num)/sum(den)) tai.output$tai[i] <- tai.calc tai.output$sample_id[i] <- id } return(tai.output) } #' Modified Total Aberration Index #' #' Modified Total Aberration Index calculation takes the sum of lengths of each segment #' times its segmentation mean for each sample and divides it by the sum of the #' lengths of each sample. #' #' Modified Total Aberration Index uses all sample values instead of those in aberrant copy number state, thus does not remove the directionality from the score. #' \deqn{ #' Modified\ Total\ Aberration\ Index = #' \frac #' {\sum^{R}_{i = 1} {d_i} \cdot {\bar{y}_{S_i}}} #' {\sum^{R}_{i = 1} {d_i}} #' } #' #' @seealso \code{\link{tai}} #' @param cnvData dataframe containing following columns: Sample, Start, End, Num_Probes, Segment_Mean #' @param segmentMean numerical value for the minimum segment_mean cutoff/ threshold. Default is 0.2 #' @param numProbes Number of Probes #' @return Average of lengths weighted by segmentation mean for each unique sample #' @examples taiModified(cnvData = maskCNV_BRCA) #' @export taiModified <- function(cnvData, segmentMean = 0, numProbes = NA ){ unique_id <- unique(cnvData$Sample) tai.output <- stats::setNames(data.frame(matrix(ncol = 2, nrow = length(unique_id)), stringsAsFactors = FALSE),c("sample_id","modified_tai")) for (i in 1:length(unique_id)){ id <- unique_id[i] subsetSample <- subset(cnvData, cnvData$Sample == id ) subsetSample <- subset(subsetSample, abs(subsetSample$Segment_Mean) >= segmentMean) if (!is.na(numProbes)){ subsetSample<-subset(subsetSample, abs(subsetSample$Num_Probes) >= numProbes) } Length <- subsetSample$End - subsetSample$Start num <- Length*subsetSample$Segment_Mean den <- Length tai.calc <- sum(sum(num)/sum(den)) tai.output$modified_tai[i] <- tai.calc tai.output$sample_id[i] <- id } return(tai.output) } #' Copy Number Aberration #' #' Calculates the number of copy number aberrations #' #' Copy Number Aberrations (CNA) \href{https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0079079}{(Davidson JM, et al)}, are defined as a segment with copy number outside the pre-defined range of 1.7-2.3 \deqn{(\log_2 1.7 -1) \le \bar{y}_{S_i} \le (\log_2 2.3 -1)} that is not contiguous with an adjacent independent CNA of identical copy number. For our purposes, we have adapted the range to be \deqn{|\bar{y}_{S_i}| \ge |\log_2 1.7|}, which is only slightly larger than the original. #' It is nearly identical to countingBreakPoints, except this one calculates breaks as adjacent segments that have a difference in segment means of \eqn{\ge 0.2}. #' \deqn{Total\ Copy\ Number\ Aberration = \sum^{R}_{i = 1} n_i \ where \ #' \bar{y}_{S_i}| \ge |\log_2{1.7}|, \ #' \bar{y}_{S_{i-1}} - \bar{y}_{S_i}| \ge 0.2, \ #' d_i \ge 10} #' #' @seealso \code{\link{countingBreakPoints}} #' @param cnvData dataframe containing following columns: Sample, Start, End, Num_Probes, Segment_Mean #' @param segmentMean numerical value for the minimum segment_mean cutoff/ threshold. Default is 0.2 #' @param numProbes Number of Probes #' @param segmentDistance Segment distance threshold #' @param minSegSize Minimum segment size #' @return Number of copy number aberrations between segments #' @examples cna(cnvData = maskCNV_BRCA) #' @export cna <- function(cnvData, segmentMean = (log(1.7,2)-1), numProbes = NA, segmentDistance = 0.2, minSegSize = 10){ unique_id <- unique(cnvData$Sample) cna.output <- stats::setNames(data.frame(matrix(ncol = 2, nrow = length(unique_id)), stringsAsFactors = FALSE),c("sample_id","cna")) for (i in 1:length(unique_id)){ id <- unique_id[i] exSample <- subset(cnvData, cnvData$Sample == id ) exSample <- subset(exSample, abs(exSample$Segment_Mean) >= abs(segmentMean) & !is.na(exSample$Segment_Mean)) exSample <- subset(exSample, abs(exSample$End - exSample$Start) >= minSegSize) if (!is.na(numProbes)){ exSample<-subset(exSample, abs(exSample$Num_Probes) >= numProbes) } breakpointNumber <- 0 curSig <- NA for (segment in 1:nrow(exSample)){ if (is.na(curSig)){ curSig <- exSample$Segment_Mean[segment] } else { if (!is.na(curSig) & abs(curSig - exSample$Segment_Mean[segment]) >= segmentDistance){ breakpointNumber = breakpointNumber + 1 curSig <- exSample$Segment_Mean[segment] } } } cna.output$cna[i] <- breakpointNumber cna.output$sample_id[i] <- id } return(cna.output) } #' countingBaseSegments #' #' Function for counting altered base segments #' #' The Altered Base Segment calculation takes all the CNV data for a single patient and first filters it for a segmentation mean of > 0.2 and, if specified, the minimum number of probes #' covering that area. Then, it calculates the sums of the lengths of each segment for a particular patient and outputs that. #' \deqn{ #' Number\ of\ Altered\ Bases = \sum^{R}_{i = 1} d_i\ where\ |\bar{y}_{S_i}| \ge 0.2 #' } #' #' @param cnvData dataframe containing following columns: Sample, Start, End, Num_Probes, Segment_Mean #' @param segmentMean numerical value for the minimum segment_mean cutoff/ threshold. Default is 0.2 #' @param numProbes Number of Probes #' @return Number of Base segments for each unique sample #' @examples countingBaseSegments(cnvData = maskCNV_BRCA) #' @export countingBaseSegments <- function(cnvData, segmentMean = 0.2, numProbes = NA ){ unique_id <- unique(cnvData$Sample) NumBases <- stats::setNames(data.frame(matrix(ncol = 2, nrow = length(unique_id)), stringsAsFactors = FALSE),c("sample_id","base_segments")) for (i in 1:length(unique_id)){ id <- unique_id[i] exSample<-subset(cnvData, cnvData$Sample == id ) exSample<-subset(exSample, abs(exSample$Segment_Mean) >= segmentMean) if (!is.na(numProbes)){ exSample<-subset(exSample, abs(exSample$Num_Probes) >= numProbes) } segSizes<-exSample$End - exSample$Start count <- sum(segSizes) NumBases$base_segments[i] <- count NumBases$sample_id[i] <- id } return(NumBases) } #' countingBreakPoints #' #' The Break Point calculation takes all the CNV data for a single patient and first filters it for segmentation mean of > 0.2 and, if specified, the minimum number of probes #' covering that area. Then it counts the number of rows of data and multiplies it by 2. This represents the break points at the 5' and 3' ends of each segment. #' \deqn{ #' Number\ of \ Break\ Points = \sum^{R}_{i = 1} (n_i \cdot 2)\ where\ |\bar{y}_{S_i}| \ge 0.2 #' } #' #' @param cnvData dataframe containing following columns: Sample, Start, End, Num_Probes, Segment_Mean #' @param segmentMean numerical value for the minimum segment_mean cutoff/ threshold. Default is 0.2 #' @param numProbes Number of Probes #' @return Number of Break points for each unique sample #' @example countingBreakPoints(cnvData = maskCNV_BRCA) #' @export countingBreakPoints <- function(cnvData, segmentMean = 0.2, numProbes = NA){ unique_id <- unique(cnvData$Sample) NumBpt <- stats::setNames(data.frame(matrix(ncol = 2, nrow = length(unique_id)), stringsAsFactors = FALSE),c("sample_id","break_points")) for (i in 1:length(unique_id)){ id <- unique_id[i] exSample<-subset(cnvData, cnvData$Sample == id ) exSample<-subset(exSample, abs(exSample$Segment_Mean) >= segmentMean) if (!is.na(numProbes)){ exSample<-subset(exSample, abs(exSample$Num_Probes) >= numProbes) } number <- nrow(exSample) * 2 # Multiplied by 2 because of counting 5' and 3' breakpoints NumBpt$break_points[i] <- number NumBpt$sample_id[i] <- id } return(NumBpt) } #' Fraction Genome Altered #' #' Fraction Genome Altered looks at the fraction of the genome that deviates from a diploid state #' fga calculates the fraction of the genome altered (FGA; [Chin SF, et. al.](https://www.ncbi.nlm.nih.gov/pubmed/17925008)), measured by taking the sum of the number of bases altered and dividing it by the genome length covered ($G$). Genome length covered was calculated by summing the lengths of each probe on the Affeymetrix 6.0 array. This calculation **excludes** sex chromosomes. #' \deqn{ #' Fraction\ Genome\ Altered = #' \frac #' {\sum^{R}_{i = 1} d_i} #' {G} #' \ \ where\ |\bar{y}_{S_i}| \ge 0.2 #' } #' #' @param cnvData dataframe containing following columns: Sample, Start, End, Num_Probes, Segment_Mean #' @param segmentMean numerical value for the minimum segment_mean cutoff/ threshold. Default is 0.2 #' @param numProbes Number of Probes #' @param genomeSize Size of the genome derived from Affymetrix 6.0 array probe. Default is 2873203431 calculated based on hg38 **excluding sex chromosomes** #' @return Fraction of the genome altered #' @examples fga(cnvData = maskCNV_BRCA) #' @export fga <- function(cnvData, segmentMean = 0.2, numProbes = NA, genomeSize = 2873203431){ # genomeSize derived from Affymetrix 6.0 array probe information. The default values is 2873203431 based on hg38 unique_id <- unique(cnvData$Sample) fgaOutput <- stats::setNames(data.frame(matrix(ncol = 2, nrow = length(unique_id)), stringsAsFactors = FALSE),c("sample_id","fga")) for (i in 1:length(unique_id)){ id <- unique_id[i] subsetSample <- subset(cnvData, cnvData$Sample == id ) subsetSample <- subset(subsetSample, subsetSample$Chromosome %in% c(1:22)) subsetSample <- subset(subsetSample, abs(subsetSample$Segment_Mean) >= segmentMean) if (!is.na(numProbes)){ subsetSample<-subset(subsetSample, abs(subsetSample$Num_Probes) >= numProbes) } Length <- subsetSample$End - subsetSample$Start Sum <- sum(Length) fga.calc <- Sum/genomeSize fgaOutput$fga[i] <- fga.calc fgaOutput$sample_id[i] <- id } return(fgaOutput) } #' CINmetrics #' #' Calculate all CINmetrics on a given dataframe #' #' @param cnvData dataframe containing following columns: Sample, Start, End, Num_Probes, Segment_Mean #' @param segmentMean_tai numerical value for the minimum segment_mean cutoff/ threshold for Total Aberration Index calculation. Default is 0.2 #' @param segmentMean_cna numerical value for the minimum segment_mean cutoff/ threshold for Copy Number Aberration calculation. Default is 0.2 #' @param segmentMean_base_segments numerical value for the minimum segment_mean cutoff/ threshold for Base segments calculation. Default is 0.2 #' @param segmentMean_break_points numerical value for the minimum segment_mean cutoff/ threshold for Break points calculation. Default is 0.2 #' @param segmentMean_fga numerical value for the minimum segment_mean cutoff/ threshold for Fraction of genome altered calculation. Default is 0.2 #' @param numProbes Number of Probes #' @param segmentDistance_cna Segment distance threshold #' @param minSegSize_cna Minimum segment size #' @param genomeSize_fga Size of the genome derived from Affymetrix 6.0 array probe. Default is 2873203431 calculated based on hg38 **excluding sex chromosomes** #' @return All Chromosomal INstability metrics #' @examples CINmetrics(cnvData = maskCNV_BRCA) #' @export CINmetrics <- function(cnvData, segmentMean_tai = 0.2, segmentMean_cna = (log(1.7,2)-1), segmentMean_base_segments = 0.2, segmentMean_break_points = 0.2, segmentMean_fga = 0.2, numProbes = NA, segmentDistance_cna = 0.2, minSegSize_cna = 10, genomeSize_fga = 2873203431){ # Calculate all Chromosomal Instability metrics as a single data frame unique_id <- unique(cnvData$Sample) cinmetrics <- data.frame(matrix(ncol = 6, nrow = length(unique_id)), stringsAsFactors = FALSE) tai <- CINmetrics::tai(cnvData = cnvData, segmentMean = segmentMean_tai, numProbes = numProbes) cna <- CINmetrics::cna(cnvData = cnvData, segmentMean = segmentMean_cna, numProbes = numProbes, segmentDistance = segmentDistance_cna, minSegSize = minSegSize_cna) base_segments <- CINmetrics::countingBaseSegments(cnvData = cnvData, segmentMean = segmentMean_base_segments, numProbes = numProbes) break_points <- CINmetrics::countingBreakPoints(cnvData = cnvData, segmentMean = segmentMean_break_points, numProbes = numProbes) fga <- CINmetrics::fga(cnvData = cnvData, segmentMean = segmentMean_fga, numProbes = numProbes, genomeSize = genomeSize_fga) cinmetrics <- merge(merge(merge(merge(tai, cna, by="sample_id"), base_segments, by="sample_id"), break_points, by="sample_id"), fga, by="sample_id") return(cinmetrics) }
/scratch/gouwar.j/cran-all/cranData/CINmetrics/R/cin_metrics.R
#' Breast Cancer Data from TCGA #' Data Release 25.0 #' GDC Product: Data #' Release Date: July 22, 2020 #' Masked Copy Number variation data for Breast Cancer for 10 unique samples selected randomly from TCGA #' @docType data #' @usage data(maskCNV_BRCA) #' @format An object of class dataframe #' @keywords dataset #' @references Koboldt, D., Fulton, R., McLellan, M. et al. (2012) Nature 490, 61–70 #' \url{https://www.nature.com/articles/nature11412} #' @source \url{https://portal.gdc.cancer.gov/} #' @examples #' data(maskCNV_BRCA) #' \donttest{tai <- tai(maskCNV_BRCA)} "maskCNV_BRCA"
/scratch/gouwar.j/cran-all/cranData/CINmetrics/R/data.R
## ---- include = FALSE--------------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ## ----setup-------------------------------------------------------------------- library(CINmetrics) ## ----------------------------------------------------------------------------- dim(maskCNV_BRCA) ## ----------------------------------------------------------------------------- ## Not run: #library(TCGAbiolinks) #query.maskCNV.hg39.BRCA <- GDCquery(project = "TCGA-BRCA", # data.category = "Copy Number Variation", # data.type = "Masked Copy Number Segment", legacy=FALSE) #GDCdownload(query = query.maskCNV.hg39.BRCA) #maskCNV.BRCA <- GDCprepare(query = query.maskCNV.hg39.BRCA, summarizedExperiment = FALSE) #maskCNV.BRCA <- data.frame(maskCNV.BRCA, stringsAsFactors = FALSE) #tai.test <- tai(cnvData = maskCNV.BRCA) ## End(Not run) ## ----------------------------------------------------------------------------- tai.test <- tai(cnvData = maskCNV_BRCA) head(tai.test) ## ----------------------------------------------------------------------------- modified.tai.test <- taiModified(cnvData = maskCNV_BRCA) head(modified.tai.test) ## ----------------------------------------------------------------------------- cna.test <- cna(cnvData = maskCNV_BRCA) head(cna.test) ## ----------------------------------------------------------------------------- base.seg.test <- countingBaseSegments(cnvData = maskCNV_BRCA) head(base.seg.test) ## ----------------------------------------------------------------------------- break.points.test <- countingBreakPoints(cnvData = maskCNV_BRCA) head(break.points.test) ## ----------------------------------------------------------------------------- fraction.genome.test <- fga(cnvData = maskCNV_BRCA) head(fraction.genome.test) ## ----------------------------------------------------------------------------- cinmetrics.test <- CINmetrics(cnvData = maskCNV_BRCA) head(cinmetrics.test)
/scratch/gouwar.j/cran-all/cranData/CINmetrics/inst/doc/CINmetrics.R
--- title: "CINmetrics" author: "Vishal H. Oza" date: "2-Dec-2020" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{CINmetrics} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` # CINmetrics The goal of CINmetrics package is to provide different methods of calculating Chromosomal Instability (CIN) metrics from the literature that can be applied to any cancer data set including The Cancer Genome Atlas. ```{r setup} library(CINmetrics) ``` The dataset provided with CINmetrics package is masked Copy Number variation data for Breast Cancer for 10 unique samples selected randomly from TCGA. ```{r} dim(maskCNV_BRCA) ``` Alternatively, you can download the entire dataset from TCGA using TCGAbiolinks package ```{r} ## Not run: #library(TCGAbiolinks) #query.maskCNV.hg39.BRCA <- GDCquery(project = "TCGA-BRCA", # data.category = "Copy Number Variation", # data.type = "Masked Copy Number Segment", legacy=FALSE) #GDCdownload(query = query.maskCNV.hg39.BRCA) #maskCNV.BRCA <- GDCprepare(query = query.maskCNV.hg39.BRCA, summarizedExperiment = FALSE) #maskCNV.BRCA <- data.frame(maskCNV.BRCA, stringsAsFactors = FALSE) #tai.test <- tai(cnvData = maskCNV.BRCA) ## End(Not run) ``` ## Total Aberration Index *tai* calculates the Total Aberration Index (TAI; [Baumbusch LO, et. al.](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3553118/)), "a measure of the abundance of genomic size of copy number changes in a tumour". It is defined as a weighted sum of the segment means ($|\bar{y}_{S_i}|$). Biologically, it can also be interpreted as the absolute deviation from the normal copy number state averaged over all genomic locations. $$ Total\ Aberration\ Index = \frac {\sum^{R}_{i = 1} {d_i} \cdot |{\bar{y}_{S_i}}|} {\sum^{R}_{i = 1} {d_i}}\ \ where |\bar{y}_{S_i}| \ge |\log_2 1.7| $$ ```{r} tai.test <- tai(cnvData = maskCNV_BRCA) head(tai.test) ``` ## Modified Total Aberration Index *taiModified* calculates a modified Total Aberration Index using all sample values instead of those in aberrant copy number state, thus does not remove the directionality from the score. $$ Modified\ Total\ Aberration\ Index = \frac {\sum^{R}_{i = 1} {d_i} \cdot {\bar{y}_{S_i}}} {\sum^{R}_{i = 1} {d_i}} $$ ```{r} modified.tai.test <- taiModified(cnvData = maskCNV_BRCA) head(modified.tai.test) ``` ## Copy Number Aberration *cna* calculates the total number of copy number aberrations (CNA; [Davidson JM, et. al.](https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0079079)), defined as a segment with copy number outside the pre-defined range of 1.7-2.3 ($(\log_2 1.7 -1) \le \bar{y}_{S_i} \le (\log_2 2.3 -1)$) that is not contiguous with an adjacent independent CNA of identical copy number. For our purposes, we have adapted the range to be $|\bar{y}_{S_i}| \ge |\log_2 1.7|$, which is only slightly larger than the original. This metric is very similar to the number of break points, but it comes with the caveat that adjacent segments need to have a difference in segmentation mean values. $$ Total\ Copy\ Number\ Aberration = \sum^{R}_{i = 1} n_i \ \ where\ \ \begin{align} |\bar{y}_{S_i}| \ge |\log_2{1.7}|, \\ |\bar{y}_{S_{i-1}} - \bar{y}_{S_i}| \ge 0.2, \\ d_i \ge 10 \end{align} $$ ```{r} cna.test <- cna(cnvData = maskCNV_BRCA) head(cna.test) ``` ## Counting Altered Base segments *countingBaseSegments* calculates the number of altered bases defined as the sums of the lengths of segments ($d_i$) with an absolute segment mean ($|\bar{y}_{S_i}|$) of greater than 0.2. Biologically, this value can be thought to quantify numerical chromosomal instability. This is also a simpler representation of how much of the genome has been altered, and it does not run into the issue of sequencing coverage affecting the fraction of the genome altered. $$ Number\ of\ Altered\ Bases = \sum^{R}_{i = 1} d_i\ where\ |\bar{y}_{S_i}| \ge 0.2 $$ ```{r} base.seg.test <- countingBaseSegments(cnvData = maskCNV_BRCA) head(base.seg.test) ``` ## Counting Number of Break Points *countingBreakPoints* calculates the number of break points defined as the number of segments ($n_i$) with an absolute segment mean greater than 0.2. This is then doubled to account for the 5' and 3' break points. Biologically, this value can be thought to quantify structural chromosomal instability. $$ Number\ of \ Break\ Points = \sum^{R}_{i = 1} (n_i \cdot 2)\ where\ |\bar{y}_{S_i}| \ge 0.2 $$ ```{r} break.points.test <- countingBreakPoints(cnvData = maskCNV_BRCA) head(break.points.test) ``` ## Fraction of Genome Altered *fga* calculates the fraction of the genome altered (FGA; [Chin SF, et. al.](https://pubmed.ncbi.nlm.nih.gov/17925008/)), measured by taking the sum of the number of bases altered and dividing it by the genome length covered ($G$). Genome length covered was calculated by summing the lengths of each probe on the Affeymetrix 6.0 array. This calculation **excludes** sex chromosomes. $$ Fraction\ Genome\ Altered = \frac {\sum^{R}_{i = 1} d_i} {G} \ \ where\ |\bar{y}_{S_i}| \ge 0.2 $$ ```{r} fraction.genome.test <- fga(cnvData = maskCNV_BRCA) head(fraction.genome.test) ``` ## CINmetrics *CINmetrics* calculates tai, cna, number of altered base segments, number of break points, and fraction of genome altered and returns them as a single data frame. ```{r} cinmetrics.test <- CINmetrics(cnvData = maskCNV_BRCA) head(cinmetrics.test) ```
/scratch/gouwar.j/cran-all/cranData/CINmetrics/inst/doc/CINmetrics.Rmd
--- title: "CINmetrics" author: "Vishal H. Oza" date: "2-Dec-2020" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{CINmetrics} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` # CINmetrics The goal of CINmetrics package is to provide different methods of calculating Chromosomal Instability (CIN) metrics from the literature that can be applied to any cancer data set including The Cancer Genome Atlas. ```{r setup} library(CINmetrics) ``` The dataset provided with CINmetrics package is masked Copy Number variation data for Breast Cancer for 10 unique samples selected randomly from TCGA. ```{r} dim(maskCNV_BRCA) ``` Alternatively, you can download the entire dataset from TCGA using TCGAbiolinks package ```{r} ## Not run: #library(TCGAbiolinks) #query.maskCNV.hg39.BRCA <- GDCquery(project = "TCGA-BRCA", # data.category = "Copy Number Variation", # data.type = "Masked Copy Number Segment", legacy=FALSE) #GDCdownload(query = query.maskCNV.hg39.BRCA) #maskCNV.BRCA <- GDCprepare(query = query.maskCNV.hg39.BRCA, summarizedExperiment = FALSE) #maskCNV.BRCA <- data.frame(maskCNV.BRCA, stringsAsFactors = FALSE) #tai.test <- tai(cnvData = maskCNV.BRCA) ## End(Not run) ``` ## Total Aberration Index *tai* calculates the Total Aberration Index (TAI; [Baumbusch LO, et. al.](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3553118/)), "a measure of the abundance of genomic size of copy number changes in a tumour". It is defined as a weighted sum of the segment means ($|\bar{y}_{S_i}|$). Biologically, it can also be interpreted as the absolute deviation from the normal copy number state averaged over all genomic locations. $$ Total\ Aberration\ Index = \frac {\sum^{R}_{i = 1} {d_i} \cdot |{\bar{y}_{S_i}}|} {\sum^{R}_{i = 1} {d_i}}\ \ where |\bar{y}_{S_i}| \ge |\log_2 1.7| $$ ```{r} tai.test <- tai(cnvData = maskCNV_BRCA) head(tai.test) ``` ## Modified Total Aberration Index *taiModified* calculates a modified Total Aberration Index using all sample values instead of those in aberrant copy number state, thus does not remove the directionality from the score. $$ Modified\ Total\ Aberration\ Index = \frac {\sum^{R}_{i = 1} {d_i} \cdot {\bar{y}_{S_i}}} {\sum^{R}_{i = 1} {d_i}} $$ ```{r} modified.tai.test <- taiModified(cnvData = maskCNV_BRCA) head(modified.tai.test) ``` ## Copy Number Aberration *cna* calculates the total number of copy number aberrations (CNA; [Davidson JM, et. al.](https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0079079)), defined as a segment with copy number outside the pre-defined range of 1.7-2.3 ($(\log_2 1.7 -1) \le \bar{y}_{S_i} \le (\log_2 2.3 -1)$) that is not contiguous with an adjacent independent CNA of identical copy number. For our purposes, we have adapted the range to be $|\bar{y}_{S_i}| \ge |\log_2 1.7|$, which is only slightly larger than the original. This metric is very similar to the number of break points, but it comes with the caveat that adjacent segments need to have a difference in segmentation mean values. $$ Total\ Copy\ Number\ Aberration = \sum^{R}_{i = 1} n_i \ \ where\ \ \begin{align} |\bar{y}_{S_i}| \ge |\log_2{1.7}|, \\ |\bar{y}_{S_{i-1}} - \bar{y}_{S_i}| \ge 0.2, \\ d_i \ge 10 \end{align} $$ ```{r} cna.test <- cna(cnvData = maskCNV_BRCA) head(cna.test) ``` ## Counting Altered Base segments *countingBaseSegments* calculates the number of altered bases defined as the sums of the lengths of segments ($d_i$) with an absolute segment mean ($|\bar{y}_{S_i}|$) of greater than 0.2. Biologically, this value can be thought to quantify numerical chromosomal instability. This is also a simpler representation of how much of the genome has been altered, and it does not run into the issue of sequencing coverage affecting the fraction of the genome altered. $$ Number\ of\ Altered\ Bases = \sum^{R}_{i = 1} d_i\ where\ |\bar{y}_{S_i}| \ge 0.2 $$ ```{r} base.seg.test <- countingBaseSegments(cnvData = maskCNV_BRCA) head(base.seg.test) ``` ## Counting Number of Break Points *countingBreakPoints* calculates the number of break points defined as the number of segments ($n_i$) with an absolute segment mean greater than 0.2. This is then doubled to account for the 5' and 3' break points. Biologically, this value can be thought to quantify structural chromosomal instability. $$ Number\ of \ Break\ Points = \sum^{R}_{i = 1} (n_i \cdot 2)\ where\ |\bar{y}_{S_i}| \ge 0.2 $$ ```{r} break.points.test <- countingBreakPoints(cnvData = maskCNV_BRCA) head(break.points.test) ``` ## Fraction of Genome Altered *fga* calculates the fraction of the genome altered (FGA; [Chin SF, et. al.](https://pubmed.ncbi.nlm.nih.gov/17925008/)), measured by taking the sum of the number of bases altered and dividing it by the genome length covered ($G$). Genome length covered was calculated by summing the lengths of each probe on the Affeymetrix 6.0 array. This calculation **excludes** sex chromosomes. $$ Fraction\ Genome\ Altered = \frac {\sum^{R}_{i = 1} d_i} {G} \ \ where\ |\bar{y}_{S_i}| \ge 0.2 $$ ```{r} fraction.genome.test <- fga(cnvData = maskCNV_BRCA) head(fraction.genome.test) ``` ## CINmetrics *CINmetrics* calculates tai, cna, number of altered base segments, number of break points, and fraction of genome altered and returns them as a single data frame. ```{r} cinmetrics.test <- CINmetrics(cnvData = maskCNV_BRCA) head(cinmetrics.test) ```
/scratch/gouwar.j/cran-all/cranData/CINmetrics/vignettes/CINmetrics.Rmd
#' CIPerm: Computationally-Efficient Confidence Intervals for Mean Shift from Permutation Methods #' #' Implements computationally-efficient construction of #' confidence intervals from permutation tests or randomization tests #' for simple differences in means. #' The method is based on Minh D. Nguyen's 2009 MS thesis paper, #' "Nonparametric Inference using Randomization and Permutation #' Reference Distribution and their Monte-Carlo Approximation," #' <\doi{10.15760/etd.7798}> #' See the \code{nguyen} vignette for a brief summary of the method. #' First use \code{\link{dset}} to tabulate summary statistics for each permutation. #' Then pass the results into \code{\link{cint}} to compute a confidence interval, #' or into \code{\link{pval}} to calculate p-values. #' #' Our R function arguments and outputs are structured differently #' than the similarly-named R functions in Nguyen (2009), #' but the results are equivalent. In the \code{nguyen} vignette #' we use our functions to replicate Nguyen's results. #' #' Following Ernst (2004) and Nguyen (2009), we use "permutation methods" #' to include both randomization tests and permutation tests. #' In the simple settings in this R package, #' the randomization and permutation test mechanics are identical, #' but their interpretations may differ. #' #' We say "randomization test" under the model where #' the units are not necessarily a random sample, but the treatment assignment #' was random. The null hypothesis is that the treatment has no effect. #' In this case we can make causal inferences about the #' treatment effect (difference between groups) for this set of individuals, #' but cannot necessarily generalize to other populations. #' #' By contrast, we say "permutation test" under the model where #' the units were randomly sampled from two distinct subpopulations. #' The null hypothesis is that the two groups have identical CDFs. #' In this case we can make inferences about differences between subpopulations, #' but there's not necessarily any "treatment" to speak of #' and causal inferences may not be relevant. #' #' @references Ernst, M.D. (2004). #' "Permutation Methods: A Basis for Exact Inference," #' \emph{Statistical Science}, vol. 19, no. 4, 676-685, #' <\doi{10.1214/088342304000000396}>. #' #' Nguyen, M.D. (2009). #' "Nonparametric Inference using Randomization and Permutation #' Reference Distribution and their Monte-Carlo Approximation" #' [unpublished MS thesis; Mara Tableman, advisor], Portland State University. #' \emph{Dissertations and Theses}. Paper 5927. #' <\doi{10.15760/etd.7798}>. #' @importFrom matrixStats colMedians #' @importFrom stats median #' @importFrom utils combn #' #' @docType package #' @name CIPerm NULL
/scratch/gouwar.j/cran-all/cranData/CIPerm/R/CIPerm.R
#' Permutation-methods confidence interval for difference in means #' #' Calculate confidence interval for a simple difference in means #' from a two-sample permutation or randomization test. #' In other words, we set up a permutation or randomization test to evaluate #' \eqn{H_0: \mu_A - \mu_B = 0}, then use those same permutations to #' construct a CI for the parameter \eqn{\delta = (\mu_A - \mu_B)}. #' #' If the desired \code{conf.level} is not exactly feasible, #' the achieved confidence level will be slightly anti-conservative. #' We use the default numeric tolerance in \code{\link{all.equal}} to check #' if \code{(1-conf.level) * nrow(dset)} is an integer for one-tailed CIs, #' or if \code{(1-conf.level)/2 * nrow(dset)} is an integer for two-tailed CIs. #' If so, \code{conf.level.achieved} will be the desired \code{conf.level}. #' Otherwise, we will use the next feasible integer, #' thus slightly reducing the confidence level. #' For example, in the example below the randomization test has 35 combinations, #' and a two-sided CI must have at least one combination value in each tail, #' so the largest feasible confidence level for a two-sided CI is 1-(2/35) or around 94.3\%. #' If we request a 95\% or 99\% CI, we will have to settle for a 94.3\% CI instead. #' #' @param dset The output of \code{\link{dset}}. #' @param conf.level Confidence level (default 0.95 corresponds to 95\% confidence level). #' @param tail Which tail? Either "Two"- or "Left"- or "Right"-tailed interval. #' @return A list containing the following components:\describe{ #' \item{\code{conf.int}}{Numeric vector with the CI's two endpoints.} #' \item{\code{conf.level.achieved}}{Numeric value of the achieved confidence level.} #' } #' @examples #' x <- c(19, 22, 25, 26) #' y <- c(23, 33, 40) #' demo <- dset(x, y) #' cint(dset = demo, conf.level = .95, tail = "Two") #' @export cint <- function(dset, conf.level = .95, tail = c("Two", "Left", "Right")){ sig <- 1 - conf.level stopifnot(sig > 0 & sig < 1) tail <- match.arg(tail) num <- nrow(dset) w.i <- sort(dset$wkd, decreasing = FALSE, na.last = FALSE) # Keeping an eye on how we use w.i later... # When dset's nmc leads us to use Monte Carlo sims, # we may get some permutations equivalent to orig data # i.e. we may get SEVERAL k=0 and therefore several w.i=NaN. # For this reason, some hardcoded "1"s below # (which used to be correct when we didn't have a Monte Carlo option) # must be replaced with the number of k=0 rows. nk0 <- sum(dset$k == 0) stopifnot(nk0 >= 1) # Our code assumes 1st row is orig data, so k=0 at least once # Below we'll need to take ceiling(siglevel*num) several times. # BUT this has caused problems when siglevel*num "should be" an integer # but was represented as sliiightly more than that integer in floating point... # So here is an internal function which will EITHER # 1. use round(siglevel*num), if siglevel*num is basically an integer, # to within the default numerical tolerance of all.equal(); # 2. or otherwise use ceiling(siglevel*num) instead. roundOrCeiling <- function(x) { ifelse(isTRUE(all.equal(round(x), x)), # is x==round(x) to numerical tolerance? round(x), ceiling(x)) } ## Quick checks: ## ceiling() fails to give 2, but roundOrCeiling() works correctly # > ceiling((1-(1-2/35))*35) ## whoops! # [1] 3 # > roundOrCeiling((1-(1-2/35))*35) # [1] 2 ## Another check: ## ceiling() fails to give 250, but roundOrCeiling() works correctly # > ceiling((1-.95)*5000) ## whoops! # [1] 251 # > roundOrCeiling((1-.95)*5000) # [1] 250 if (tail == "Left"){ siglevel <- sig index <- roundOrCeiling(siglevel*num) - 1 UB <- w.i[(num-index)] LT <- c(-Inf, UB) conf.achieved <- 1-((index+1)/num) message(paste0("Achieved conf. level: 1-(", index+1, "/", num, ")")) return(list(conf.int = LT, conf.level.achieved = conf.achieved)) } else if (tail == "Right"){ siglevel <- sig index <- roundOrCeiling(siglevel*num) - 1 LB <- w.i[1+nk0+index] # starts counting from the (1+nk0)'th element of w.i # (not the first (original) which will always be 'NaN') RT <- c(LB, Inf) conf.achieved <- 1-((index+1)/num) message(paste0("Achieved conf. level: 1-(", index+1, "/", num, ")")) return(list(conf.int = RT, conf.level.achieved = conf.achieved)) } else { # tail == "Two" siglevel <- sig/2 # use half of sig in each tail index <- roundOrCeiling(siglevel*num) - 1 UB <- w.i[(num-index)] LB <- w.i[1+nk0+index] # starts counting from the (1+nk0)'th element of w.i # (not the first (original) which will always be 'NaN') Upper <- if(is.na(UB)) Inf else UB Lower <- if(is.na(LB)) -Inf else LB CI <- c(Lower, Upper) conf.achieved <- 1-(2*(index+1)/num) message(paste0("Achieved conf. level: 1-2*(", index+1, "/", num, ")")) return(list(conf.int = CI, conf.level.achieved = conf.achieved)) } }
/scratch/gouwar.j/cran-all/cranData/CIPerm/R/cint.R
#' Permutation-methods summary statistics #' #' Calculate table of differences in means, medians, etc. for each #' combination (or permutation, if using Monte Carlo approx.), #' as needed in order to compute a confidence interval using \code{\link{cint}} #' and/or a p-value using \code{\link{pval}}. #' #' @param group1 Vector of numeric values for first group. #' @param group2 Vector of numeric values for second group. #' @param nmc Threshold for whether to use Monte Carlo draws or complete #' enumeration. If the number of all possible combinations #' \code{choose(n1+n2, n1) <= nmc}, we use complete enumeration. #' Otherwise, we take a Monte Carlo sample of \code{nmc} permutations. #' You can set \code{nmc = 0} to force complete enumeration regardless of #' how many combinations there are. #' @param returnData Whether the returned dataframe should include columns for #' the permuted data itself (if TRUE), or only the derived columns that are #' needed for confidence intervals and p-values (if FALSE, default). #' @return A data frame ready to be used in \code{cint()} or \code{pval()}. #' @examples #' x <- c(19, 22, 25, 26) #' y <- c(23, 33, 40) #' demo <- dset(x, y, returnData = TRUE) #' knitr::kable(demo, digits = 2) #' @export ###################### #### Old notes-to-self from when we used to have two versions, #### dset() using for-loops vs a vectorized dsetFast(). #### As of 3/22/2022, dsetFast() became the current version of dset() below, #### and the old version was simply removed. #### Look on GitHub for package versions 0.1.0.9004 or earlier #### (March 21, 2022 or earlier) to see old dset() code. ## ## CHECK TIMINGS AND OUTPUTS OF dset() VS dsetFast(): ## ## Skipping the for loop with dsetFast() gives a ~7x speedup over original dset()! # > x <- c(19, 22, 25, 26) # > y <- c(23, 33, 40) # > microbenchmark::microbenchmark(dset(x, y), dsetFast(x, y), times = 1000) # Unit: microseconds # expr min lq mean median uq max neval # dset(x, y) 6276.401 6790.501 7715.261 7210.501 7910.150 51722.501 1000 # dsetFast(x, y) 901.101 1060.551 1215.499 1141.201 1238.651 4548.201 1000 ## ## And it does give the same result! ## # > demo <- dset(x, y) # > demo2 <- dsetFast(x, y) # > all.equal(demo, demo2) # [1] TRUE ## ## Let's check this on other datasets too, ## and let's check Monte Carlo runs with set.seed()... ## ## What about the larger groups of 6+9 obs instead of 4+3 obs? # > wl1 <- c(1.72, 1.64, 1.74, 1.70, 1.82, 1.82, 1.90, 1.82, 2.08) # > wl2 <- c(1.78, 1.86, 1.96, 2.00, 2.00, 1.96) # > microbenchmark::microbenchmark(dset(wl1, wl2), dsetFast(wl1, wl2), times = 50) # Unit: milliseconds # expr min lq mean median uq max neval # dset(wl1, wl2) 1138.0176 1226.140 1278.69760 1278.08755 1327.2168 1438.2427 50 # dsetFast(wl1, wl2) 43.3406 47.194 50.46918 49.85155 52.8262 77.2373 50 ## ## OH WOW, this is 25x faster now. ## Here, plain dset() takes ~1sec each time, while dsetFast() is ~0.05sec. ## I imagine the diffs will only get more extreme for larger datasets. ## ## And they still give same results? # > demo <- dset(wl1, wl2) # > demo2 <- dsetFast(wl1, wl2) # > all.equal(demo, demo2) # [1] TRUE # > demo <- dset(wl1, wl2, returnData = TRUE) # > demo2 <- dsetFast(wl1, wl2, returnData = TRUE) # > all.equal(demo, demo2) # [1] TRUE ## Yes they do! ## ## What about Monte Carlo runs? ## They shouldn't match without set.seed(), and indeed they don't... # > demo <- dset(wl1, wl2, nmc = 5000) # > demo2 <- dsetFast(wl1, wl2, nmc = 5000) # > isTRUE(all.equal(demo, demo2)) # [1] FALSE ## ## But WITH set.seed, they DO match, as they should! # > seed = 20220321 # > set.seed(seed) # > demo <- dset(wl1, wl2, nmc = 5000) # > set.seed(seed) # > demo2 <- dsetFast(wl1, wl2, nmc = 5000) # > all.equal(demo, demo2) # [1] TRUE ## ## So old dset() can be replaced with new dsetFast() ###################### # TODO: in the future, consider switching to RcppAlgos::comboSample(), # which lets you sample *directly* from the set of all possible combinations # without having to generate them all first. # However, that would force us to Require several other packages. # For now, let's start with just using base sample() # (even though it gives permutations, not only unique combinations, # so that we might get multiple perms equivalent to the same combo; # we'll need to handle multiple perms equivalent to original data grouping). dset <- function(group1, group2, nmc = 10000, returnData = FALSE){ stopifnot(nmc >= 0) stopifnot(nmc != 1) stopifnot(is.numeric(group1) & is.numeric(group2)) stopifnot(length(group1) >= 1 & length(group2) >= 1) stopifnot(!any(is.na(c(group1, group2)))) combined <- c(group1, group2) n <- length(group1) m <- length(group2) den <- (1/n + 1/m) N <- n + m num <- choose(N, n) # number of possible combinations # Form a matrix where each column contains indices in new "group1" for that comb or perm if(nmc == 0 | num <= nmc) { # take all possible combinations dcombn1 <- utils::combn(1:N, n) } else { # use Monte Carlo sample of permutations, not all possible combinations dcombn1 <- replicate(nmc, sample(N, n)) dcombn1[,1] <- 1:n # force the 1st "combination" to be original data order num <- nmc } # Form the equivalent matrix for indices in new "group2" dcombn2 <- apply(dcombn1, 2, function(x) setdiff(1:N, x)) # Form the corresponding matrices of data values, not data indices group1_perm <- matrix(combined[dcombn1], nrow = n) group2_perm <- matrix(combined[dcombn2], nrow = m) # For each comb or perm, compute: # difference in group means; sum in group1; difference in group medians; # and sum of *ranks* in group1 (the statistic for the Wilcoxon rank sum test) diffmean <- colMeans(group1_perm) - colMeans(group2_perm) sum1 <- colSums(group1_perm) diffmedian <- matrixStats::colMedians(group1_perm) - matrixStats::colMedians(group2_perm) r <- rank(combined, ties.method = "first") wilsum <- colSums(matrix(r[dcombn1], nrow = n)) # For each comb or perm, compute: # k = how many values swapped from group1 to group2? # wkd = Nguyen (2009) statistic whose quantiles are used for CI endpoints k <- colSums(matrix(dcombn1 %in% ((n+1):N), nrow=n)) wkd <- (diffmean[1] - diffmean) / (k * den) dataframe <- data.frame(diffmean = diffmean, sum1 = sum1, diffmedian = diffmedian, wilsum = wilsum, k = k, wkd = wkd) if(returnData){ # Return the whole table formatted as in Nguyen (2009) # for comparison with his results w.i <- sort(dataframe$wkd, decreasing = FALSE, na.last = FALSE) ID <- c(1:num) dataset <- t(rbind(group1_perm, group2_perm)) datatable <- cbind(ID, dataset, dataframe, w.i) return(datatable) } else { # Just return the fewest columns needed for p-vals and CIs return(dataframe) } }
/scratch/gouwar.j/cran-all/cranData/CIPerm/R/dset.R
#' Permutations-methods p-values for difference in means, medians, or Wilcoxon rank sum test #' #' Calculate p-values for a two-sample permutation or randomization test. #' In other words, we set up a permutation or randomization test to evaluate #' the null hypothesis that groups A and B have the same distribution, #' then calculate p-values for several alternatives: #' a difference in means (\code{value="m"}), #' a difference in medians (\code{value="d"}), #' or the Wilcoxon rank sum test (\code{value="w"}). #' #' @param dset The output of \code{\link{dset}}. #' @param tail Which tail? Either "Two"- or "Left"- or "Right"-tailed test. #' @param value Either "m" for difference in means (default); #' "s" for sum of Group 1 values #' [equivalent to "m" and included only for sake of checking results against #' Nguyen (2009) and Ernst (2004)]; #' "d" for difference in medians; #' or "w" for Wilcoxon rank sum statistic; #' or "a" for a named vector of all four p-values. #' @return Numeric p-value for the selected type of test, #' or a named vector of all four p-values if \code{value="a"}. #' @examples #' x <- c(19, 22, 25, 26) #' y <- c(23, 33, 40) #' demo <- dset(x, y) #' pval(dset = demo, tail = "Left", value = "s") #' pval(dset = demo, tail = "Left", value = "a") #' @export # TODO: Should two-tailed tests be for |x-median| and not |x-mean| ??? # The p-value involves finding how much of null distr # is further away from the 50th percentile, right?... # However, Ernst (2004) paper in *Statistical Science* uses |x-mean|, # so let's stick with that for now. pval <- function(dset, tail = c("Two", "Left", "Right"), value = c("m", "s", "d", "w", "a")){ tail <- match.arg(tail) value <- match.arg(value) num <- nrow(dset) if (tail == "Left"){ pvalmean <- sum(dset$diffmean <= dset$diffmean[1])/num pvalsum <- sum(dset$sum1 <= dset$sum1[1])/num pvalmedian <- sum(dset$diffmedian <= dset$diffmedian[1])/num pvalwilsum <- sum(dset$wilsum <= dset$wilsum[1])/num } else if (tail == "Right") { pvalmean <- sum(dset$diffmean >= dset$diffmean[1])/num pvalsum <- sum(dset$sum1 >= dset$sum1[1])/num pvalmedian <- sum(dset$diffmedian >= dset$diffmedian[1])/num pvalwilsum <- sum(dset$wilsum >= dset$wilsum[1])/num } else { # tail == "Two" pvalmean <- sum(abs(dset$diffmean - mean(dset$diffmean)) >= abs(dset$diffmean[1] - mean(dset$diffmean)))/num pvalsum <- sum(abs(dset$sum1 - mean(dset$sum1)) >= abs(dset$sum1[1] - mean(dset$sum1)))/num pvalmedian <- sum(abs(dset$diffmedian - mean(dset$diffmedian)) >= abs(dset$diffmedian[1] - mean(dset$diffmedian)))/num pvalwilsum <- sum(abs(dset$wilsum - mean(dset$wilsum)) >= abs(dset$wilsum[1] - mean(dset$wilsum)))/num } if (value == "m"){ return(pvalmean) } else if (value == "s"){ return(pvalsum) } else if (value == "d"){ return(pvalmedian) } else if (value == "w"){ return(pvalwilsum) } else { # value == "a" return(c(m = pvalmean, s = pvalsum, d = pvalmedian, w = pvalwilsum)) } }
/scratch/gouwar.j/cran-all/cranData/CIPerm/R/pval.R
## ---- include = FALSE--------------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ## ----function-nguyen---------------------------------------------------------- #### Define a streamlined function for Nguyen approach #### # 1. use round(siglevel*num), if siglevel*num is basically an integer, # to within the default numerical tolerance of all.equal(); # 2. or otherwise use ceiling(siglevel*num) instead. roundOrCeiling <- function(x) { ifelse(isTRUE(all.equal(round(x), x)), # is x==round(x) to numerical tolerance? round(x), ceiling(x)) } cint.nguyen <- function(x, y, nmc = 10000, conf.level = 0.95) { # Two-tailed CIs only, for now sig <- 1 - conf.level # Code copied/modified from within CIPerm::dset() n <- length(x) m <- length(y) N <- n + m num <- choose(N, n) # number of possible combinations # Form a matrix where each column contains indices in new "group1" for that comb or perm if(nmc == 0 | num <= nmc) { # take all possible combinations dcombn1 <- utils::combn(1:N, n) } else { # use Monte Carlo sample of permutations, not all possible combinations dcombn1 <- replicate(nmc, sample(N, n)) dcombn1[,1] <- 1:n # force the 1st "combination" to be original data order num <- nmc } # Form the equivalent matrix for indices in new "group2" dcombn2 <- apply(dcombn1, 2, function(x) setdiff(1:N, x)) # Form the corresponding matrices of data values, not data indices combined <- c(x, y) group1_perm <- matrix(combined[dcombn1], nrow = n) group2_perm <- matrix(combined[dcombn2], nrow = m) # For each comb or perm, compute difference in group means, k, and w_{k,d} diffmean <- colMeans(group1_perm) - colMeans(group2_perm) k <- colSums(matrix(dcombn1 %in% ((n+1):N), nrow = n)) wkd <- (diffmean[1] - diffmean) / (k * (1/n + 1/m)) # Code copied/modified from within CIPerm::cint() # Sort wkd values and find desired quantiles w.i <- sort(wkd, decreasing = FALSE, na.last = FALSE) siglevel <- (1 - conf.level)/2 index <- roundOrCeiling(siglevel*num) - 1 # When dset's nmc leads us to use Monte Carlo sims, # we may get some permutations equivalent to orig data # i.e. we may get SEVERAL k=0 and therefore several w.i=NaN. nk0 <- sum(k == 0) # Start counting from (1+nk0)'th element of w.i # (not the 1st, which will always be 'NaN' since k[1] is 0) LB <- w.i[1 + nk0 + index] UB <- w.i[(num - index)] CI <- c(LB, UB) conf.achieved <- 1 - (2*(index+1) / num) message(paste0("Achieved conf. level: 1-2*(", index+1, "/", num, ")")) return(list(conf.int = CI, conf.level.achieved = conf.achieved)) } ## ----function-forloop--------------------------------------------------------- #### Define a function for "naive" approach with for-loop #### cint.naive.forloop <- function(x, y, deltas, nmc = 10000, conf.level = 0.95) { # Two-tailed CIs only, for now sig <- 1 - conf.level pvalmeans <- rep(1, length(deltas)) # Code copied/modified from within CIPerm::dset() n <- length(x) m <- length(y) N <- n + m num <- choose(N, n) # number of possible combinations # Form a matrix where each column contains indices in new "group1" for that comb or perm if(nmc == 0 | num <= nmc) { # take all possible combinations dcombn1 <- utils::combn(1:N, n) } else { # use Monte Carlo sample of permutations, not all possible combinations dcombn1 <- replicate(nmc, sample(N, n)) dcombn1[,1] <- 1:n # force the 1st "combination" to be original data order num <- nmc } # Form the equivalent matrix for indices in new "group2" dcombn2 <- apply(dcombn1, 2, function(x) setdiff(1:N, x)) for(dd in 1:length(deltas)) { xtmp <- x - deltas[dd] # Code copied/modified from within CIPerm::dset() combined <- c(xtmp, y) # Form the corresponding matrices of data values, not data indices group1_perm <- matrix(combined[dcombn1], nrow = n) group2_perm <- matrix(combined[dcombn2], nrow = m) # For each comb or perm, compute difference in group means diffmean <- colMeans(group1_perm) - colMeans(group2_perm) # Code copied/modified from within CIPerm::pval() pvalmeans[dd] <- sum(abs(diffmean - mean(diffmean)) >= abs(diffmean[1] - mean(diffmean)))/length(diffmean) } print( range(deltas[which(pvalmeans >= sig)]) ) return(list(cint = range(deltas[which(pvalmeans >= sig)]), pvalmeans = pvalmeans, deltas = deltas)) } ## ----function-array, echo=FALSE, eval=FALSE----------------------------------- # ## THIS FUNCTION ALSO WORKS, # ## BUT REQUIRES SUBSTANTIALLY MORE MEMORY THAN THE PREVIOUS ONE # ## AND IS SLOWER FOR LARGE DATASETS, # ## SO WE LEFT IT OUT OF THE COMPARISONS # # # Possible speedup: # # Could we replace for-loop with something like manipulating a 3D array? # # e.g., where we say # ### group1_perm <- matrix(combined[dcombn1], nrow = n) # # could we first make `combined` into a 2D matrix # # where each col is like it is now, # # but each row is for a different value of delta; # # and then group1_perm would be a 3D array, # # where each 1st+2nd dims matrix is like it is now, # # but 3rd dim indexes over deltas; # # and then `diffmean` and `pvalmeans` # # would be colMeans or similar over an array # # so the output would be right # # cint.naive.array <- function(x, y, deltas, # nmc = 10000, # conf.level = 0.95) { # # Two-tailed CIs only, for now # sig <- 1 - conf.level # # # New version where xtmp is a matrix, not a vector; # # and some stuff below will be arrays, not matrices... # xtmp <- matrix(x, nrow = length(x), ncol = length(deltas)) # xtmp <- xtmp - deltas[col(xtmp)] # combined <- rbind(xtmp, # matrix(y, nrow = length(y), ncol = length(deltas))) # # # Code copied/modified from within CIPerm::dset() # n <- length(x) # m <- length(y) # N <- n + m # num <- choose(N, n) # number of possible combinations # # Form a matrix where each column contains indices in new "group1" for that comb or perm # if(nmc == 0 | num <= nmc) { # take all possible combinations # dcombn1 <- utils::combn(1:N, n) # } else { # use Monte Carlo sample of permutations, not all possible combinations # dcombn1 <- replicate(nmc, sample(N, n)) # dcombn1[,1] <- 1:n # force the 1st "combination" to be original data order # num <- nmc # } # # Form the equivalent matrix for indices in new "group2" # dcombn2 <- apply(dcombn1, 2, function(x) setdiff(1:N, x)) # # # ARRAYS of data indices, where 3rd dim indexes over deltas # dcombn1_arr <- outer(dcombn1, N * (0:(length(deltas)-1)), FUN = "+") # dcombn2_arr <- outer(dcombn2, N * (0:(length(deltas)-1)), FUN = "+") # # # Form the corresponding ARRAYS of data values, not data indices # group1_perm <- array(combined[dcombn1_arr], dim = dim(dcombn1_arr)) # group2_perm <- array(combined[dcombn2_arr], dim = dim(dcombn2_arr)) # # # For each comb or perm, compute difference in group means # # diffmean <- matrix(colMeans(group1_perm, dim=1), nrow = num) - # # matrix(colMeans(group2_perm, dim=1), nrow = num) # diffmean <- colMeans(group1_perm, dim=1) - colMeans(group2_perm, dim=1) # # # Code copied/modified from within CIPerm::pval() # pvalmeans <- colSums(abs(diffmean - colMeans(diffmean)[col(diffmean)]) >= abs(diffmean[1,] - colMeans(diffmean))[col(diffmean)])/nrow(diffmean) # # plot(deltas, pvalmeans) # # print( range(deltas[which(pvalmeans >= sig)]) ) # return(list(cint = range(deltas[which(pvalmeans >= sig)]), # pvalmeans = pvalmeans, # deltas = deltas)) # } ## ----tests-tiny--------------------------------------------------------------- #### Speed tests on Nguyen's tiny dataset #### # Use 1st tiny dataset from Nguyen's paper library(CIPerm) x <- c(19, 22, 25, 26) y <- c(23, 33, 40) # Actual CIPerm package's approach: system.time({ print( cint(dset(x, y), conf.level = 0.95, tail = "Two") ) }) # Streamlined version of CIPerm approach: system.time({ print( cint.nguyen(x, y, conf.level = 0.95) ) }) # Naive approach with for-loops: deltas <- ((-22):4) system.time({ pvalmeans <- cint.naive.forloop(x, y, deltas)$pvalmeans }) # Sanity check to debug `cint.naive`: # are the p-vals always higher when closer to middle of CI? # Are they always above 0.05 inside and below it outside CI? cbind(deltas, pvalmeans) plot(deltas, pvalmeans) abline(h = 0.05) abline(v = c(-21, 3), lty = 2) # Yes, it's as it should be :) ## ----test-tiny-array, echo=FALSE, eval=FALSE---------------------------------- # # Naive approach with arrays: # system.time({ # pvalmeans <- cint.naive.array(x, y, deltas)$pvalmeans # }) # # # Sanity check again: # cbind(deltas, pvalmeans) # plot(deltas, pvalmeans) # abline(h = 0.05) # abline(v = c(-21, 3), lty = 2) # # Yep, still same results. OK. # # So this "array" version IS faster, # # and nearly as fast as Nguyen # # (though harder to debug... # # but the same could be said of Nguyen's approach...) # # # WAIT WAIT WAIT # # I changed the for-loop approach to stop creating dcombn1 & dcombn2 # # inside each step of the loop # # since we can reuse the same ones for every value of deltas... # # AND NOW it's FASTER than the array version, # # even for tiny datasets! # # And later we'll see that array version is unbearably slow # # for large datasets where it takes forever # # to create & store these massive arrays... # # So it's not worth reporting in the final vignette :( ## ----tests-larger------------------------------------------------------------- choose(18, 9) ## 48620 set.seed(20220528) x <- rnorm(9, mean = 0, sd = 1) y <- rnorm(9, mean = 1, sd = 1) # Actual CIPerm approach # (with nmc = 0, # so that we use ALL of the choose(N,n) combinations # instead of a MC sample of permutations) system.time({ print( cint(dset(x, y, nmc = 0), conf.level = 0.95, tail = "Two") ) }) # Streamlined version of CIPerm approach: system.time({ print( cint.nguyen(x, y, nmc = 0, conf.level = 0.95) ) }) # Coarser grid deltas <- ((-21):(1))/10 # grid steps of 0.1 # Naive with for-loops: system.time({ pvalmeans <- cint.naive.forloop(x, y, deltas, nmc = 0)$pvalmeans }) # Finer grid deltas <- ((-21*2):(1*2))/20 # grid steps of 0.05 # Naive with for-loops: system.time({ pvalmeans <- cint.naive.forloop(x, y, deltas, nmc = 0)$pvalmeans }) ## ----tests-larger-array, echo=FALSE, eval=FALSE------------------------------- # # Coarser grid # deltas <- ((-21):(1))/10 # grid steps of 0.1 # # # Naive with arrays: # system.time({ # pvalmeans <- cint.naive.array(x, y, deltas, nmc = 1e6)$pvalmeans # }) # # # !!! Indeed it looks like naive.forloop # # is FASTER than naive.array # # now that I've removed the slow dcombn1 & dcombn2 creating from the loop. # # # # Finer grid # deltas <- ((-21*2):(1*2))/20 # grid steps of 0.05 # # # Naive with arrays: # system.time({ # pvalmeans <- cint.naive.array(x, y, deltas, nmc = 1e6)$pvalmeans # }) ## ----tests-largest------------------------------------------------------------ #### Speed tests on much larger dataset #### set.seed(20220528) x <- rnorm(5e3, mean = 0, sd = 1) y <- rnorm(5e3, mean = 1, sd = 1) # Actual CIPerm approach # (with nmc = 2000 << choose(N,n), # so it only takes a MC sample of permutations # instead of running all possible combinations) system.time({ print( cint(dset(x, y, nmc = 2e3), conf.level = 0.95, tail = "Two") ) }) # Streamlined version of CIPerm approach: system.time({ print( cint.nguyen(x, y, nmc = 2e3, conf.level = 0.95) ) }) # Grid of around 20ish steps deltas <- ((-11*10):(-9*10))/100 # grid steps of 0.01 # Naive with for-loops: system.time({ pvalmeans <- cint.naive.forloop(x, y, deltas, nmc = 2e3)$pvalmeans }) ## ----tests-largest-array, echo=FALSE, eval=FALSE------------------------------ # # Naive with arrays: # system.time({ # pvalmeans <- cint.naive.array(x, y, deltas, nmc = 2e3)$pvalmeans # }) ## ----tests-largest-benchmark-------------------------------------------------- # bench::mark(cint.nguyen(x, y, nmc = 2e3), # cint.naive.forloop(x, y, deltas, nmc = 2e3), # check = FALSE, min_iterations = 10) #> # A tibble: 2 × 13 #> expression min median `itr/sec` mem_alloc `gc/sec` n_itr n_gc total_time result memory time gc #> <bch:expr> <bch:tm> <bch:tm> <dbl> <bch:byt> <dbl> <int> <dbl> <bch:tm> <list> <list> <list> <list> #> 1 cint.nguyen(x, y, nmc = 2000) 2.5s 2.71s 0.364 1.58GB 2.92 10 80 27.44s <NULL> <Rprofmem [32,057 × 3]> <bench_tm [10]> <tibble [10 × 3]> #> 2 cint.naive.forloop(x, y, deltas, nmc = 2000) 7.87s 8.07s 0.120 7.4GB 4.64 10 388 1.39m <NULL> <Rprofmem [32,256 × 3]> <bench_tm [10]> <tibble [10 × 3]> ## ----tests-largest-profvis---------------------------------------------------- # profvis::profvis(cint.nguyen(x, y, nmc = 2e3)) # profvis::profvis(cint.naive.forloop(x, y, deltas, nmc = 2e3))
/scratch/gouwar.j/cran-all/cranData/CIPerm/inst/doc/naive.R
--- title: "Comparing `CIPerm` with 'naive' approach" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{naive} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` We run simple timing comparisons to show how our package's approach with Nguyen (2009) compares against a "naive" grid-based search approach to confidence intervals from permutation methods. # Defining streamlined functions We can use `CIPerm`'s `cint(dset(x, y))` directly, and it already wins against the naive for-loop or array-based approaches. But since `dset` and `cint` both have extra cruft built into them, for an even "fairer" comparison we recreate the core of `cint(dset())` here without all the extra variables and without passing copies of dataframes. First we re-define the internal function `roundOrCeiling()`, then we define a streamlined `cint.nguyen()`: ```{r function-nguyen} #### Define a streamlined function for Nguyen approach #### # 1. use round(siglevel*num), if siglevel*num is basically an integer, # to within the default numerical tolerance of all.equal(); # 2. or otherwise use ceiling(siglevel*num) instead. roundOrCeiling <- function(x) { ifelse(isTRUE(all.equal(round(x), x)), # is x==round(x) to numerical tolerance? round(x), ceiling(x)) } cint.nguyen <- function(x, y, nmc = 10000, conf.level = 0.95) { # Two-tailed CIs only, for now sig <- 1 - conf.level # Code copied/modified from within CIPerm::dset() n <- length(x) m <- length(y) N <- n + m num <- choose(N, n) # number of possible combinations # Form a matrix where each column contains indices in new "group1" for that comb or perm if(nmc == 0 | num <= nmc) { # take all possible combinations dcombn1 <- utils::combn(1:N, n) } else { # use Monte Carlo sample of permutations, not all possible combinations dcombn1 <- replicate(nmc, sample(N, n)) dcombn1[,1] <- 1:n # force the 1st "combination" to be original data order num <- nmc } # Form the equivalent matrix for indices in new "group2" dcombn2 <- apply(dcombn1, 2, function(x) setdiff(1:N, x)) # Form the corresponding matrices of data values, not data indices combined <- c(x, y) group1_perm <- matrix(combined[dcombn1], nrow = n) group2_perm <- matrix(combined[dcombn2], nrow = m) # For each comb or perm, compute difference in group means, k, and w_{k,d} diffmean <- colMeans(group1_perm) - colMeans(group2_perm) k <- colSums(matrix(dcombn1 %in% ((n+1):N), nrow = n)) wkd <- (diffmean[1] - diffmean) / (k * (1/n + 1/m)) # Code copied/modified from within CIPerm::cint() # Sort wkd values and find desired quantiles w.i <- sort(wkd, decreasing = FALSE, na.last = FALSE) siglevel <- (1 - conf.level)/2 index <- roundOrCeiling(siglevel*num) - 1 # When dset's nmc leads us to use Monte Carlo sims, # we may get some permutations equivalent to orig data # i.e. we may get SEVERAL k=0 and therefore several w.i=NaN. nk0 <- sum(k == 0) # Start counting from (1+nk0)'th element of w.i # (not the 1st, which will always be 'NaN' since k[1] is 0) LB <- w.i[1 + nk0 + index] UB <- w.i[(num - index)] CI <- c(LB, UB) conf.achieved <- 1 - (2*(index+1) / num) message(paste0("Achieved conf. level: 1-2*(", index+1, "/", num, ")")) return(list(conf.int = CI, conf.level.achieved = conf.achieved)) } ``` Next, we define an equivalent function to implement the "naive" approach: * Choose a grid of possible values of delta = mu_X-mu_Y to try * For each delta... - subtract delta off of the x's, - and carry out a test of H_0: mu_X=mu_Y on the resulting data * Our confidence interval consists of the range of delta values for which H_0 is NOT rejected ```{r function-forloop} #### Define a function for "naive" approach with for-loop #### cint.naive.forloop <- function(x, y, deltas, nmc = 10000, conf.level = 0.95) { # Two-tailed CIs only, for now sig <- 1 - conf.level pvalmeans <- rep(1, length(deltas)) # Code copied/modified from within CIPerm::dset() n <- length(x) m <- length(y) N <- n + m num <- choose(N, n) # number of possible combinations # Form a matrix where each column contains indices in new "group1" for that comb or perm if(nmc == 0 | num <= nmc) { # take all possible combinations dcombn1 <- utils::combn(1:N, n) } else { # use Monte Carlo sample of permutations, not all possible combinations dcombn1 <- replicate(nmc, sample(N, n)) dcombn1[,1] <- 1:n # force the 1st "combination" to be original data order num <- nmc } # Form the equivalent matrix for indices in new "group2" dcombn2 <- apply(dcombn1, 2, function(x) setdiff(1:N, x)) for(dd in 1:length(deltas)) { xtmp <- x - deltas[dd] # Code copied/modified from within CIPerm::dset() combined <- c(xtmp, y) # Form the corresponding matrices of data values, not data indices group1_perm <- matrix(combined[dcombn1], nrow = n) group2_perm <- matrix(combined[dcombn2], nrow = m) # For each comb or perm, compute difference in group means diffmean <- colMeans(group1_perm) - colMeans(group2_perm) # Code copied/modified from within CIPerm::pval() pvalmeans[dd] <- sum(abs(diffmean - mean(diffmean)) >= abs(diffmean[1] - mean(diffmean)))/length(diffmean) } print( range(deltas[which(pvalmeans >= sig)]) ) return(list(cint = range(deltas[which(pvalmeans >= sig)]), pvalmeans = pvalmeans, deltas = deltas)) } ``` We also wrote another "naive" function that avoids for-loops and takes a "vectorized" approach instead. We created large arrays: each permutation requires a matrix, and the 3rd array dimension is over permutations. Then `apply` and `colSums` work very quickly to carry out all the per-permutations steps on this array at once. However, we found that unless datasets were trivially small, creating and storing the array took a lot of time and memory, and it ended up far slower than the for-loop approach. Consequently we do not report this function or its results here, although curious readers can find it hidden in the vignette's .Rmd file. ```{r function-array, echo=FALSE, eval=FALSE} ## THIS FUNCTION ALSO WORKS, ## BUT REQUIRES SUBSTANTIALLY MORE MEMORY THAN THE PREVIOUS ONE ## AND IS SLOWER FOR LARGE DATASETS, ## SO WE LEFT IT OUT OF THE COMPARISONS # Possible speedup: # Could we replace for-loop with something like manipulating a 3D array? # e.g., where we say ### group1_perm <- matrix(combined[dcombn1], nrow = n) # could we first make `combined` into a 2D matrix # where each col is like it is now, # but each row is for a different value of delta; # and then group1_perm would be a 3D array, # where each 1st+2nd dims matrix is like it is now, # but 3rd dim indexes over deltas; # and then `diffmean` and `pvalmeans` # would be colMeans or similar over an array # so the output would be right cint.naive.array <- function(x, y, deltas, nmc = 10000, conf.level = 0.95) { # Two-tailed CIs only, for now sig <- 1 - conf.level # New version where xtmp is a matrix, not a vector; # and some stuff below will be arrays, not matrices... xtmp <- matrix(x, nrow = length(x), ncol = length(deltas)) xtmp <- xtmp - deltas[col(xtmp)] combined <- rbind(xtmp, matrix(y, nrow = length(y), ncol = length(deltas))) # Code copied/modified from within CIPerm::dset() n <- length(x) m <- length(y) N <- n + m num <- choose(N, n) # number of possible combinations # Form a matrix where each column contains indices in new "group1" for that comb or perm if(nmc == 0 | num <= nmc) { # take all possible combinations dcombn1 <- utils::combn(1:N, n) } else { # use Monte Carlo sample of permutations, not all possible combinations dcombn1 <- replicate(nmc, sample(N, n)) dcombn1[,1] <- 1:n # force the 1st "combination" to be original data order num <- nmc } # Form the equivalent matrix for indices in new "group2" dcombn2 <- apply(dcombn1, 2, function(x) setdiff(1:N, x)) # ARRAYS of data indices, where 3rd dim indexes over deltas dcombn1_arr <- outer(dcombn1, N * (0:(length(deltas)-1)), FUN = "+") dcombn2_arr <- outer(dcombn2, N * (0:(length(deltas)-1)), FUN = "+") # Form the corresponding ARRAYS of data values, not data indices group1_perm <- array(combined[dcombn1_arr], dim = dim(dcombn1_arr)) group2_perm <- array(combined[dcombn2_arr], dim = dim(dcombn2_arr)) # For each comb or perm, compute difference in group means # diffmean <- matrix(colMeans(group1_perm, dim=1), nrow = num) - # matrix(colMeans(group2_perm, dim=1), nrow = num) diffmean <- colMeans(group1_perm, dim=1) - colMeans(group2_perm, dim=1) # Code copied/modified from within CIPerm::pval() pvalmeans <- colSums(abs(diffmean - colMeans(diffmean)[col(diffmean)]) >= abs(diffmean[1,] - colMeans(diffmean))[col(diffmean)])/nrow(diffmean) # plot(deltas, pvalmeans) print( range(deltas[which(pvalmeans >= sig)]) ) return(list(cint = range(deltas[which(pvalmeans >= sig)]), pvalmeans = pvalmeans, deltas = deltas)) } ``` # Speed tests ## Tiny dataset When we compare the timings, `cint.naive()` will need to have a reasonable search grid for values of `delta`. On this problem, we happen to know the correct CI endpoints are the integers `(-21, 3)`, so we "cheat" by using `(-22):4` as the grid for `cint.naive()`. Of course in practice, if you had only the naive approach, you would probably have to try a wider grid, since you wouldn't already know the answer. ```{r tests-tiny} #### Speed tests on Nguyen's tiny dataset #### # Use 1st tiny dataset from Nguyen's paper library(CIPerm) x <- c(19, 22, 25, 26) y <- c(23, 33, 40) # Actual CIPerm package's approach: system.time({ print( cint(dset(x, y), conf.level = 0.95, tail = "Two") ) }) # Streamlined version of CIPerm approach: system.time({ print( cint.nguyen(x, y, conf.level = 0.95) ) }) # Naive approach with for-loops: deltas <- ((-22):4) system.time({ pvalmeans <- cint.naive.forloop(x, y, deltas)$pvalmeans }) # Sanity check to debug `cint.naive`: # are the p-vals always higher when closer to middle of CI? # Are they always above 0.05 inside and below it outside CI? cbind(deltas, pvalmeans) plot(deltas, pvalmeans) abline(h = 0.05) abline(v = c(-21, 3), lty = 2) # Yes, it's as it should be :) ``` Above we see timings for the original `CIPerm::cint(dset))`, its streamlined version`cint.nguyen()`, and the naive equivalent `cint.naive()`. In the case of a tiny dataset like this, all 3 approaches take almost no time. So it can be a tossup as to which one is fastest on this example. ```{r test-tiny-array, echo=FALSE, eval=FALSE} # Naive approach with arrays: system.time({ pvalmeans <- cint.naive.array(x, y, deltas)$pvalmeans }) # Sanity check again: cbind(deltas, pvalmeans) plot(deltas, pvalmeans) abline(h = 0.05) abline(v = c(-21, 3), lty = 2) # Yep, still same results. OK. # So this "array" version IS faster, # and nearly as fast as Nguyen # (though harder to debug... # but the same could be said of Nguyen's approach...) # WAIT WAIT WAIT # I changed the for-loop approach to stop creating dcombn1 & dcombn2 # inside each step of the loop # since we can reuse the same ones for every value of deltas... # AND NOW it's FASTER than the array version, # even for tiny datasets! # And later we'll see that array version is unbearably slow # for large datasets where it takes forever # to create & store these massive arrays... # So it's not worth reporting in the final vignette :( ``` ## Larger dataset Try a slightly larger dataset, where the total number of permutations is above the default `nmc=10000` but still manageable on a laptop. Again, `cint.naive()` will need to have a reasonable search grid for values of `delta`. This time again we will set up a grid that just barely covers the correct endpoints from `cint.nguyen()`, and again we'll try to keep it at around 20 to 25 grid points in all. Then we'll try timing it again with a slightly finer grid. ```{r tests-larger} choose(18, 9) ## 48620 set.seed(20220528) x <- rnorm(9, mean = 0, sd = 1) y <- rnorm(9, mean = 1, sd = 1) # Actual CIPerm approach # (with nmc = 0, # so that we use ALL of the choose(N,n) combinations # instead of a MC sample of permutations) system.time({ print( cint(dset(x, y, nmc = 0), conf.level = 0.95, tail = "Two") ) }) # Streamlined version of CIPerm approach: system.time({ print( cint.nguyen(x, y, nmc = 0, conf.level = 0.95) ) }) # Coarser grid deltas <- ((-21):(1))/10 # grid steps of 0.1 # Naive with for-loops: system.time({ pvalmeans <- cint.naive.forloop(x, y, deltas, nmc = 0)$pvalmeans }) # Finer grid deltas <- ((-21*2):(1*2))/20 # grid steps of 0.05 # Naive with for-loops: system.time({ pvalmeans <- cint.naive.forloop(x, y, deltas, nmc = 0)$pvalmeans }) ``` Now, `CIPerm::cint(dset())` and the `cint.nguyen` approach take about the same amount of time, and they are noticeably faster than the `cint.naive` approach. (And even more so when we use a finer search grid.) That happens even with the "cheat" of using `CIPerm` first to find the right CI limits so that our naive search grid isn't too wide, just stepping over the minimal required range with a reasonable grid-coarseness. (For the original data where CI = (-21, 3), we stepped from -22 to 4 in integers. For latest data where CI = (-2.06, 0.08), we stepped from -2.1 to 0.1 in units of 0.1 and then 0.05.) In practice there are probably cleverer ways for the naive method to choose grid discreteness and endpoints... but still, this seems like a more-than-fair chance for the naive approach. ```{r tests-larger-array, echo=FALSE, eval=FALSE} # Coarser grid deltas <- ((-21):(1))/10 # grid steps of 0.1 # Naive with arrays: system.time({ pvalmeans <- cint.naive.array(x, y, deltas, nmc = 1e6)$pvalmeans }) # !!! Indeed it looks like naive.forloop # is FASTER than naive.array # now that I've removed the slow dcombn1 & dcombn2 creating from the loop. # Finer grid deltas <- ((-21*2):(1*2))/20 # grid steps of 0.05 # Naive with arrays: system.time({ pvalmeans <- cint.naive.array(x, y, deltas, nmc = 1e6)$pvalmeans }) ``` ## Largest dataset Try an even larger example, where we're OK with a smallish total number of permutations (eg `nmc=10000`), but the dataset itself is "huge", so that each individual permutation takes a longer time. We still don't make it all that large, since we want this vignette to knit in a reasonable time. But we've seen similar results when we made even-larger datasets that took longer to run. Once again, for `cint.naive()` we will set up a search grid that just barely covers the correct endpoints from `cint.nguyen()`, and again we'll try to keep it at around 20 to 25 grid points in all. ```{r tests-largest} #### Speed tests on much larger dataset #### set.seed(20220528) x <- rnorm(5e3, mean = 0, sd = 1) y <- rnorm(5e3, mean = 1, sd = 1) # Actual CIPerm approach # (with nmc = 2000 << choose(N,n), # so it only takes a MC sample of permutations # instead of running all possible combinations) system.time({ print( cint(dset(x, y, nmc = 2e3), conf.level = 0.95, tail = "Two") ) }) # Streamlined version of CIPerm approach: system.time({ print( cint.nguyen(x, y, nmc = 2e3, conf.level = 0.95) ) }) # Grid of around 20ish steps deltas <- ((-11*10):(-9*10))/100 # grid steps of 0.01 # Naive with for-loops: system.time({ pvalmeans <- cint.naive.forloop(x, y, deltas, nmc = 2e3)$pvalmeans }) ``` ```{r tests-largest-array, echo=FALSE, eval=FALSE} # Naive with arrays: system.time({ pvalmeans <- cint.naive.array(x, y, deltas, nmc = 2e3)$pvalmeans }) ``` Here we finally see that the overhead built into `CIPerm::cint(dset())` makes it slightly slower than the streamlined `cint.nguyen()`. However, both are *substantially* faster than `cint.naive()`---they run in less than half the time of the naive approach. # `bench::mark()` and `profvis` The results above are from one run per method on each example dataset. Using the last ("largest") dataset, we also tried using `bench::mark()` to summarize the distribution of runtimes over many runs, as well as memory usage. *(Not actually run when the vignette knits, in order to avoid needing `bench` as a dependency.)* ```{r tests-largest-benchmark} # bench::mark(cint.nguyen(x, y, nmc = 2e3), # cint.naive.forloop(x, y, deltas, nmc = 2e3), # check = FALSE, min_iterations = 10) #> # A tibble: 2 × 13 #> expression min median `itr/sec` mem_alloc `gc/sec` n_itr n_gc total_time result memory time gc #> <bch:expr> <bch:tm> <bch:tm> <dbl> <bch:byt> <dbl> <int> <dbl> <bch:tm> <list> <list> <list> <list> #> 1 cint.nguyen(x, y, nmc = 2000) 2.5s 2.71s 0.364 1.58GB 2.92 10 80 27.44s <NULL> <Rprofmem [32,057 × 3]> <bench_tm [10]> <tibble [10 × 3]> #> 2 cint.naive.forloop(x, y, deltas, nmc = 2000) 7.87s 8.07s 0.120 7.4GB 4.64 10 388 1.39m <NULL> <Rprofmem [32,256 × 3]> <bench_tm [10]> <tibble [10 × 3]> ``` Finally, we also tried using the `profvis` package to check what steps are taking the longest time. *(Again, not actually run when the vignette knits, in order to avoid needing `profvis` as a dependency; but screenshots are included below.)* ```{r tests-largest-profvis} # profvis::profvis(cint.nguyen(x, y, nmc = 2e3)) # profvis::profvis(cint.naive.forloop(x, y, deltas, nmc = 2e3)) ``` For Nguyen's method, the initial setup with `combn()` or `sample()` followed by `apply(setdiff())` takes about 80% of the time, and the per-permutation calculations only take about 20% of the time: `profvis::profvis(cint.nguyen(x, y, nmc = 2e3))` ![](profvis_nguyen.png) For the naive method, the initial setup is identical, and each round of per-permutation calculations is slightly faster than in Nguyen's method... but because you have to repeat them many times (*unless you already know the CI endpoints, in which case you wouldn't need to run this at all!*), they can add up to substantially more total time than for Nguyen's method. `profvis::profvis(cint.naive.forloop(x, y, deltas, nmc = 2e3))` ![](profvis_naive.png)
/scratch/gouwar.j/cran-all/cranData/CIPerm/inst/doc/naive.Rmd
## ---- include = FALSE--------------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ## ----setup1------------------------------------------------------------------- library(CIPerm) x <- c(19, 22, 25, 26) y <- c(23, 33, 40) ## ----table2------------------------------------------------------------------- demo <- dset(x, y, returnData = TRUE) knitr::kable(demo, digits = 2) ## ----pvals.p6----------------------------------------------------------------- # Difference in means pval(demo, tail = "Left", value = "m") # Sum of treatment group pval(demo, tail = "Left", value = "s") # Difference in medians pval(demo, tail = "Left", value = "d") # Wilcoxon rank sum statistic pval(demo, tail = "Left", value = "w") ## ----cint.p11----------------------------------------------------------------- cint(demo, conf.level = 1-2/35, tail = "Left") ## ----setup2------------------------------------------------------------------- wl1 <- c(1.72, 1.64, 1.74, 1.70, 1.82, 1.82, 1.90, 1.82, 2.08) wl2 <- c(1.78, 1.86, 1.96, 2.00, 2.00, 1.96) wl <- dset(wl1, wl2) al1 <- c(1.24, 1.38, 1.36, 1.40, 1.38, 1.48, 1.38, 1.54, 1.56) al2 <- c(1.14, 1.20, 1.30, 1.26, 1.28, 1.18) al <- dset(al1, al2) ## ----pvals.p14---------------------------------------------------------------- pval(wl, tail = "Two", value = "s") pval(al, tail = "Two", value = "s") ## ----cint.p15----------------------------------------------------------------- cint(wl, conf.level = .95, tail = "Two") cint(al, conf.level = .95, tail = "Two") ## ----montecarlo--------------------------------------------------------------- wl <- dset(wl1, wl2, nmc = 999) al <- dset(al1, al2, nmc = 999) pval(wl, tail = "Two", value = "s") pval(al, tail = "Two", value = "s") cint(wl, conf.level = .95, tail = "Two") cint(al, conf.level = .95, tail = "Two")
/scratch/gouwar.j/cran-all/cranData/CIPerm/inst/doc/nguyen.R
--- title: "Replicating Nguyen (2009) with `CIPerm`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{nguyen} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` We show that our package replicates the analyses in: - Nguyen, M.D. (2009), "Nonparametric Inference using Randomization and Permutation Reference Distribution and their Monte-Carlo Approximation" [unpublished MS thesis; Mara Tableman, advisor], Portland State University. *Dissertations and Theses*. Paper 5927. [DOI:10.15760/etd.7798](https://doi.org/10.15760/etd.7798). Note that our R function arguments and outputs are structured differently than the similarly-named R functions in Nguyen (2009), but the results are equivalent. We also compare our output against related results in: - Ernst, M.D. (2004), "Permutation Methods: A Basis for Exact Inference," *Statistical Science*, vol. 19, no. 4, 676-685, [DOI:10.1214/088342304000000396](https://doi.org/10.1214/088342304000000396). Following Ernst (2004) and Nguyen (2009), we use the phrase "permutation methods" to include both *randomization* tests (where we assume random assignment of 2 treatments) and *permutation* tests (where we assume random sampling from 2 populations). In the simple settings in this R package, the randomization and permutation test mechanics are identical, though their interpretations may differ. # Brief overview of Nguyen (2009)'s method Consider a two-sample testing setup, where $X_1, \ldots, X_m$ are the responses from the control group and $Y_1, \ldots, Y_n$ are the responses from the treatment group. Imagine that lower responses are better (e.g., illness recovery times). With a standard one-sided randomization test or permutation test, we can test $H_0: \mu_Y - \mu_X \geq 0$ against $H_A: \mu_Y - \mu_X < 0$. We could also test for a specific value of $\mu_Y - \mu_X$, e.g. $H_0: \mu_Y - \mu_X \geq \Delta$ against $H_A: \mu_Y - \mu_X < \Delta$. If we assume a constant additive effect, we could carry this out by replacing all the $Y_j$ values with $Y_{j,\Delta} = Y_j-\Delta$ and then running the usual randomization test for a difference of 0. Finally, we can invert the test to get a confidence interval. If we repeat the procedure above for many difference values of $\Delta$ and record the values where the test fails to reject at level $\alpha$, we will have a $1-\alpha$ one-tailed confidence interval for $\Delta$. Doing this naively would require running many new permutations at each of many $\Delta$ values. But Nguyen (2009) derives a shortcut that gives this confidence interval directly from a single set of permutations. ## We don't have to recompute the permutation distribution for each $\Delta$ Each permutation involves swapping $k$ labels: we treat $k$ of the $X_i$ as if they were $Y_j$ and vice versa. Let $t_{k,d}$ be the difference in group means for $d^{th}$ of the permutations with $k$ swaps. For instance, on the original data we have \[t_0 = \frac{\sum_{j=1}^n Y_j}{n} - \frac{\sum_{i=1}^m X_i}{m}\] and other permutations have the form \[t_{k,d} = \frac{\sum_{i=1}^k X_i + \sum_{j=k+1}^n Y_j}{n} - \frac{\sum_{j=1}^k Y_j + \sum_{i=k+1}^m X_i}{m}\] Now if $t_{k,d,\Delta}$ is the same statistic but computed on the dataset where $Y_{j,\Delta}$ replaces $Y_j$, then Nguyen (2009) shows that \[t_{k,d,\Delta} = t_{k,d} - \Delta + k\left(\frac{1}{n}+\frac{1}{m}\right)\Delta\] So if we keep track of $k$ for each permutation, then one run of the randomization test is enough -- we don't need to carry out new runs for new $\Delta$ values. ## We don't have to try every possible $\Delta$ Next, we don't actually have to calculate $t_{k,d,\Delta}$ values directly---only the $t_{k,d}$ values we would usually calculate for a standard test of no difference in means, and the values of $k$ for each permutation. Let $w_{k,d} = \frac{t_0-t_{k,d}}{k\left(\frac{1}{n}+\frac{1}{m}\right)}$. Nguyen (2009) shows that if we compute the $w_{k,d}$ for each permutation and sort them, then their upper $\alpha$ quantile $w_{(\alpha)}$ gives the $1-\alpha$ one-sided CI upper bound for $\Delta$: \[\hat{P}[\Delta \in (-\infty, w_{(\alpha)})] = 1-\alpha\] To get a two-sided CI for $\Delta$, we can do this for both tails at half the nominal alpha. In our R package, `dset()` sets up the usual two-sample randomization or permutation test, but also records $k$ and $w_{k,d}$ for each permutation. Then `cint()` finds the appropriate quantiles of $w_{k,d}$ to return the confidence interval. We also track a few other test statistics, allowing `pval()` to return p-values for a difference in means, a difference in medians, or the Wilcoxon rank sum test. # Recovery times example Input the data from Table 1: ```{r setup1} library(CIPerm) x <- c(19, 22, 25, 26) y <- c(23, 33, 40) ``` Replicate Table 2 along with the three extra columns from Table 3: ```{r table2} demo <- dset(x, y, returnData = TRUE) knitr::kable(demo, digits = 2) ``` Replicate the left-tailed p-values reported on pages 5-6. The first three should be `0.08571429`, and the last should be `0.1142857`. ```{r pvals.p6} # Difference in means pval(demo, tail = "Left", value = "m") # Sum of treatment group pval(demo, tail = "Left", value = "s") # Difference in medians pval(demo, tail = "Left", value = "d") # Wilcoxon rank sum statistic pval(demo, tail = "Left", value = "w") ``` Replicate the confidence interval (left-tailed, with confidence level $(1 - \frac{2}{35})\times 100\% \approx 94.3\%$) reported on page 11. This should be `c(-Inf, 2)`. ```{r cint.p11} cint(demo, conf.level = 1-2/35, tail = "Left") ``` # Wing lengths and antennae lengths example Input and process the data from Table 4: ```{r setup2} wl1 <- c(1.72, 1.64, 1.74, 1.70, 1.82, 1.82, 1.90, 1.82, 2.08) wl2 <- c(1.78, 1.86, 1.96, 2.00, 2.00, 1.96) wl <- dset(wl1, wl2) al1 <- c(1.24, 1.38, 1.36, 1.40, 1.38, 1.48, 1.38, 1.54, 1.56) al2 <- c(1.14, 1.20, 1.30, 1.26, 1.28, 1.18) al <- dset(al1, al2) ``` Replicate the two-sided p-values from page 14, using the sum-of-group-1 test statistic. **NOTE:** Nguyen reports that the p-values as `0.07172827` for wing lengths, and `0.002197802` for antennae lengths. This matches our results. However, Ernst (2004) reports the p-values as `0.0719` and `0.0022`, in which case the first does not match our results after rounding, though they are very close. ```{r pvals.p14} pval(wl, tail = "Two", value = "s") pval(al, tail = "Two", value = "s") ``` Replicate the two-sided ~95\% CIs for the mean difference from page 15. **NOTE:** Nguyen reports these as 94.90\% CIs: `c(-0.246, 0.01)` for wing lengths and `c(0.087, 0.285)` for antennae lengths. However, Ernst (2004) reports a 94.90\% CI for wing lengths as `c(-0.250, 0.010)` and a 94.94\% (NOT 94.90\%!) CI for antennae lengths as `c(0.087, 0.286)`. Neither of these is an exact match for our own results below, though both are very close. ```{r cint.p15} cint(wl, conf.level = .95, tail = "Two") cint(al, conf.level = .95, tail = "Two") ``` The confidence levels in Ernst (2004) and Nguyen (2009) might differ from ours due to typos or rounding, since it is not possible to achieve exactly 94.90\% or 94.94\% confidence with this method. There are ${9+6 \choose 9} = 5005$ combinations. The closest confidence levels would be achieved if we used the 126th, 127th, or 128th lowest and highest $w_{k,d}$ values to get our two-sided CI endpoints. In those cases, the respective confidence levels would be $1-2\times(126/5005)\approx 0.94965$, $1-2\times(127/5005)\approx 0.94925$, or $1-2\times(128/5005)\approx 0.94885$. Also, Ernst (2004) may have different CI endpoints because he used an entirely different, less computationally-efficient method to calculate CIs, based on Garthwaite (1996), "Confidence intervals from randomization tests," *Biometrics* 52, 1387-1393, [DOI:10.2307/2532852](https://doi.org/10.2307/2532852). ## Wing and antennae lengths with Monte Carlo With a modern computer, it takes little time to run all ${9+6 \choose 9} = 5005$ possible combinations. But for larger datasets, where there are far more possible combinations, it can make sense to take a smaller Monte Carlo sample from all possible permutations. In our `dset()` function, the `nmc` argument lets us choose the number of Monte Carlo draws. As in Nguyen (2009), we repeat the above analysis, but this time we use 999 Monte Carlo draws instead of all 5005 possible combinations. Due to the randomness inherent in Monte Carlo sampling, these results will not match the exact results above nor Nguyen (2009)'s own Monte Carlo results; but they should be fairly close. ```{r montecarlo} wl <- dset(wl1, wl2, nmc = 999) al <- dset(al1, al2, nmc = 999) pval(wl, tail = "Two", value = "s") pval(al, tail = "Two", value = "s") cint(wl, conf.level = .95, tail = "Two") cint(al, conf.level = .95, tail = "Two") ```
/scratch/gouwar.j/cran-all/cranData/CIPerm/inst/doc/nguyen.Rmd
--- title: "Comparing `CIPerm` with 'naive' approach" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{naive} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` We run simple timing comparisons to show how our package's approach with Nguyen (2009) compares against a "naive" grid-based search approach to confidence intervals from permutation methods. # Defining streamlined functions We can use `CIPerm`'s `cint(dset(x, y))` directly, and it already wins against the naive for-loop or array-based approaches. But since `dset` and `cint` both have extra cruft built into them, for an even "fairer" comparison we recreate the core of `cint(dset())` here without all the extra variables and without passing copies of dataframes. First we re-define the internal function `roundOrCeiling()`, then we define a streamlined `cint.nguyen()`: ```{r function-nguyen} #### Define a streamlined function for Nguyen approach #### # 1. use round(siglevel*num), if siglevel*num is basically an integer, # to within the default numerical tolerance of all.equal(); # 2. or otherwise use ceiling(siglevel*num) instead. roundOrCeiling <- function(x) { ifelse(isTRUE(all.equal(round(x), x)), # is x==round(x) to numerical tolerance? round(x), ceiling(x)) } cint.nguyen <- function(x, y, nmc = 10000, conf.level = 0.95) { # Two-tailed CIs only, for now sig <- 1 - conf.level # Code copied/modified from within CIPerm::dset() n <- length(x) m <- length(y) N <- n + m num <- choose(N, n) # number of possible combinations # Form a matrix where each column contains indices in new "group1" for that comb or perm if(nmc == 0 | num <= nmc) { # take all possible combinations dcombn1 <- utils::combn(1:N, n) } else { # use Monte Carlo sample of permutations, not all possible combinations dcombn1 <- replicate(nmc, sample(N, n)) dcombn1[,1] <- 1:n # force the 1st "combination" to be original data order num <- nmc } # Form the equivalent matrix for indices in new "group2" dcombn2 <- apply(dcombn1, 2, function(x) setdiff(1:N, x)) # Form the corresponding matrices of data values, not data indices combined <- c(x, y) group1_perm <- matrix(combined[dcombn1], nrow = n) group2_perm <- matrix(combined[dcombn2], nrow = m) # For each comb or perm, compute difference in group means, k, and w_{k,d} diffmean <- colMeans(group1_perm) - colMeans(group2_perm) k <- colSums(matrix(dcombn1 %in% ((n+1):N), nrow = n)) wkd <- (diffmean[1] - diffmean) / (k * (1/n + 1/m)) # Code copied/modified from within CIPerm::cint() # Sort wkd values and find desired quantiles w.i <- sort(wkd, decreasing = FALSE, na.last = FALSE) siglevel <- (1 - conf.level)/2 index <- roundOrCeiling(siglevel*num) - 1 # When dset's nmc leads us to use Monte Carlo sims, # we may get some permutations equivalent to orig data # i.e. we may get SEVERAL k=0 and therefore several w.i=NaN. nk0 <- sum(k == 0) # Start counting from (1+nk0)'th element of w.i # (not the 1st, which will always be 'NaN' since k[1] is 0) LB <- w.i[1 + nk0 + index] UB <- w.i[(num - index)] CI <- c(LB, UB) conf.achieved <- 1 - (2*(index+1) / num) message(paste0("Achieved conf. level: 1-2*(", index+1, "/", num, ")")) return(list(conf.int = CI, conf.level.achieved = conf.achieved)) } ``` Next, we define an equivalent function to implement the "naive" approach: * Choose a grid of possible values of delta = mu_X-mu_Y to try * For each delta... - subtract delta off of the x's, - and carry out a test of H_0: mu_X=mu_Y on the resulting data * Our confidence interval consists of the range of delta values for which H_0 is NOT rejected ```{r function-forloop} #### Define a function for "naive" approach with for-loop #### cint.naive.forloop <- function(x, y, deltas, nmc = 10000, conf.level = 0.95) { # Two-tailed CIs only, for now sig <- 1 - conf.level pvalmeans <- rep(1, length(deltas)) # Code copied/modified from within CIPerm::dset() n <- length(x) m <- length(y) N <- n + m num <- choose(N, n) # number of possible combinations # Form a matrix where each column contains indices in new "group1" for that comb or perm if(nmc == 0 | num <= nmc) { # take all possible combinations dcombn1 <- utils::combn(1:N, n) } else { # use Monte Carlo sample of permutations, not all possible combinations dcombn1 <- replicate(nmc, sample(N, n)) dcombn1[,1] <- 1:n # force the 1st "combination" to be original data order num <- nmc } # Form the equivalent matrix for indices in new "group2" dcombn2 <- apply(dcombn1, 2, function(x) setdiff(1:N, x)) for(dd in 1:length(deltas)) { xtmp <- x - deltas[dd] # Code copied/modified from within CIPerm::dset() combined <- c(xtmp, y) # Form the corresponding matrices of data values, not data indices group1_perm <- matrix(combined[dcombn1], nrow = n) group2_perm <- matrix(combined[dcombn2], nrow = m) # For each comb or perm, compute difference in group means diffmean <- colMeans(group1_perm) - colMeans(group2_perm) # Code copied/modified from within CIPerm::pval() pvalmeans[dd] <- sum(abs(diffmean - mean(diffmean)) >= abs(diffmean[1] - mean(diffmean)))/length(diffmean) } print( range(deltas[which(pvalmeans >= sig)]) ) return(list(cint = range(deltas[which(pvalmeans >= sig)]), pvalmeans = pvalmeans, deltas = deltas)) } ``` We also wrote another "naive" function that avoids for-loops and takes a "vectorized" approach instead. We created large arrays: each permutation requires a matrix, and the 3rd array dimension is over permutations. Then `apply` and `colSums` work very quickly to carry out all the per-permutations steps on this array at once. However, we found that unless datasets were trivially small, creating and storing the array took a lot of time and memory, and it ended up far slower than the for-loop approach. Consequently we do not report this function or its results here, although curious readers can find it hidden in the vignette's .Rmd file. ```{r function-array, echo=FALSE, eval=FALSE} ## THIS FUNCTION ALSO WORKS, ## BUT REQUIRES SUBSTANTIALLY MORE MEMORY THAN THE PREVIOUS ONE ## AND IS SLOWER FOR LARGE DATASETS, ## SO WE LEFT IT OUT OF THE COMPARISONS # Possible speedup: # Could we replace for-loop with something like manipulating a 3D array? # e.g., where we say ### group1_perm <- matrix(combined[dcombn1], nrow = n) # could we first make `combined` into a 2D matrix # where each col is like it is now, # but each row is for a different value of delta; # and then group1_perm would be a 3D array, # where each 1st+2nd dims matrix is like it is now, # but 3rd dim indexes over deltas; # and then `diffmean` and `pvalmeans` # would be colMeans or similar over an array # so the output would be right cint.naive.array <- function(x, y, deltas, nmc = 10000, conf.level = 0.95) { # Two-tailed CIs only, for now sig <- 1 - conf.level # New version where xtmp is a matrix, not a vector; # and some stuff below will be arrays, not matrices... xtmp <- matrix(x, nrow = length(x), ncol = length(deltas)) xtmp <- xtmp - deltas[col(xtmp)] combined <- rbind(xtmp, matrix(y, nrow = length(y), ncol = length(deltas))) # Code copied/modified from within CIPerm::dset() n <- length(x) m <- length(y) N <- n + m num <- choose(N, n) # number of possible combinations # Form a matrix where each column contains indices in new "group1" for that comb or perm if(nmc == 0 | num <= nmc) { # take all possible combinations dcombn1 <- utils::combn(1:N, n) } else { # use Monte Carlo sample of permutations, not all possible combinations dcombn1 <- replicate(nmc, sample(N, n)) dcombn1[,1] <- 1:n # force the 1st "combination" to be original data order num <- nmc } # Form the equivalent matrix for indices in new "group2" dcombn2 <- apply(dcombn1, 2, function(x) setdiff(1:N, x)) # ARRAYS of data indices, where 3rd dim indexes over deltas dcombn1_arr <- outer(dcombn1, N * (0:(length(deltas)-1)), FUN = "+") dcombn2_arr <- outer(dcombn2, N * (0:(length(deltas)-1)), FUN = "+") # Form the corresponding ARRAYS of data values, not data indices group1_perm <- array(combined[dcombn1_arr], dim = dim(dcombn1_arr)) group2_perm <- array(combined[dcombn2_arr], dim = dim(dcombn2_arr)) # For each comb or perm, compute difference in group means # diffmean <- matrix(colMeans(group1_perm, dim=1), nrow = num) - # matrix(colMeans(group2_perm, dim=1), nrow = num) diffmean <- colMeans(group1_perm, dim=1) - colMeans(group2_perm, dim=1) # Code copied/modified from within CIPerm::pval() pvalmeans <- colSums(abs(diffmean - colMeans(diffmean)[col(diffmean)]) >= abs(diffmean[1,] - colMeans(diffmean))[col(diffmean)])/nrow(diffmean) # plot(deltas, pvalmeans) print( range(deltas[which(pvalmeans >= sig)]) ) return(list(cint = range(deltas[which(pvalmeans >= sig)]), pvalmeans = pvalmeans, deltas = deltas)) } ``` # Speed tests ## Tiny dataset When we compare the timings, `cint.naive()` will need to have a reasonable search grid for values of `delta`. On this problem, we happen to know the correct CI endpoints are the integers `(-21, 3)`, so we "cheat" by using `(-22):4` as the grid for `cint.naive()`. Of course in practice, if you had only the naive approach, you would probably have to try a wider grid, since you wouldn't already know the answer. ```{r tests-tiny} #### Speed tests on Nguyen's tiny dataset #### # Use 1st tiny dataset from Nguyen's paper library(CIPerm) x <- c(19, 22, 25, 26) y <- c(23, 33, 40) # Actual CIPerm package's approach: system.time({ print( cint(dset(x, y), conf.level = 0.95, tail = "Two") ) }) # Streamlined version of CIPerm approach: system.time({ print( cint.nguyen(x, y, conf.level = 0.95) ) }) # Naive approach with for-loops: deltas <- ((-22):4) system.time({ pvalmeans <- cint.naive.forloop(x, y, deltas)$pvalmeans }) # Sanity check to debug `cint.naive`: # are the p-vals always higher when closer to middle of CI? # Are they always above 0.05 inside and below it outside CI? cbind(deltas, pvalmeans) plot(deltas, pvalmeans) abline(h = 0.05) abline(v = c(-21, 3), lty = 2) # Yes, it's as it should be :) ``` Above we see timings for the original `CIPerm::cint(dset))`, its streamlined version`cint.nguyen()`, and the naive equivalent `cint.naive()`. In the case of a tiny dataset like this, all 3 approaches take almost no time. So it can be a tossup as to which one is fastest on this example. ```{r test-tiny-array, echo=FALSE, eval=FALSE} # Naive approach with arrays: system.time({ pvalmeans <- cint.naive.array(x, y, deltas)$pvalmeans }) # Sanity check again: cbind(deltas, pvalmeans) plot(deltas, pvalmeans) abline(h = 0.05) abline(v = c(-21, 3), lty = 2) # Yep, still same results. OK. # So this "array" version IS faster, # and nearly as fast as Nguyen # (though harder to debug... # but the same could be said of Nguyen's approach...) # WAIT WAIT WAIT # I changed the for-loop approach to stop creating dcombn1 & dcombn2 # inside each step of the loop # since we can reuse the same ones for every value of deltas... # AND NOW it's FASTER than the array version, # even for tiny datasets! # And later we'll see that array version is unbearably slow # for large datasets where it takes forever # to create & store these massive arrays... # So it's not worth reporting in the final vignette :( ``` ## Larger dataset Try a slightly larger dataset, where the total number of permutations is above the default `nmc=10000` but still manageable on a laptop. Again, `cint.naive()` will need to have a reasonable search grid for values of `delta`. This time again we will set up a grid that just barely covers the correct endpoints from `cint.nguyen()`, and again we'll try to keep it at around 20 to 25 grid points in all. Then we'll try timing it again with a slightly finer grid. ```{r tests-larger} choose(18, 9) ## 48620 set.seed(20220528) x <- rnorm(9, mean = 0, sd = 1) y <- rnorm(9, mean = 1, sd = 1) # Actual CIPerm approach # (with nmc = 0, # so that we use ALL of the choose(N,n) combinations # instead of a MC sample of permutations) system.time({ print( cint(dset(x, y, nmc = 0), conf.level = 0.95, tail = "Two") ) }) # Streamlined version of CIPerm approach: system.time({ print( cint.nguyen(x, y, nmc = 0, conf.level = 0.95) ) }) # Coarser grid deltas <- ((-21):(1))/10 # grid steps of 0.1 # Naive with for-loops: system.time({ pvalmeans <- cint.naive.forloop(x, y, deltas, nmc = 0)$pvalmeans }) # Finer grid deltas <- ((-21*2):(1*2))/20 # grid steps of 0.05 # Naive with for-loops: system.time({ pvalmeans <- cint.naive.forloop(x, y, deltas, nmc = 0)$pvalmeans }) ``` Now, `CIPerm::cint(dset())` and the `cint.nguyen` approach take about the same amount of time, and they are noticeably faster than the `cint.naive` approach. (And even more so when we use a finer search grid.) That happens even with the "cheat" of using `CIPerm` first to find the right CI limits so that our naive search grid isn't too wide, just stepping over the minimal required range with a reasonable grid-coarseness. (For the original data where CI = (-21, 3), we stepped from -22 to 4 in integers. For latest data where CI = (-2.06, 0.08), we stepped from -2.1 to 0.1 in units of 0.1 and then 0.05.) In practice there are probably cleverer ways for the naive method to choose grid discreteness and endpoints... but still, this seems like a more-than-fair chance for the naive approach. ```{r tests-larger-array, echo=FALSE, eval=FALSE} # Coarser grid deltas <- ((-21):(1))/10 # grid steps of 0.1 # Naive with arrays: system.time({ pvalmeans <- cint.naive.array(x, y, deltas, nmc = 1e6)$pvalmeans }) # !!! Indeed it looks like naive.forloop # is FASTER than naive.array # now that I've removed the slow dcombn1 & dcombn2 creating from the loop. # Finer grid deltas <- ((-21*2):(1*2))/20 # grid steps of 0.05 # Naive with arrays: system.time({ pvalmeans <- cint.naive.array(x, y, deltas, nmc = 1e6)$pvalmeans }) ``` ## Largest dataset Try an even larger example, where we're OK with a smallish total number of permutations (eg `nmc=10000`), but the dataset itself is "huge", so that each individual permutation takes a longer time. We still don't make it all that large, since we want this vignette to knit in a reasonable time. But we've seen similar results when we made even-larger datasets that took longer to run. Once again, for `cint.naive()` we will set up a search grid that just barely covers the correct endpoints from `cint.nguyen()`, and again we'll try to keep it at around 20 to 25 grid points in all. ```{r tests-largest} #### Speed tests on much larger dataset #### set.seed(20220528) x <- rnorm(5e3, mean = 0, sd = 1) y <- rnorm(5e3, mean = 1, sd = 1) # Actual CIPerm approach # (with nmc = 2000 << choose(N,n), # so it only takes a MC sample of permutations # instead of running all possible combinations) system.time({ print( cint(dset(x, y, nmc = 2e3), conf.level = 0.95, tail = "Two") ) }) # Streamlined version of CIPerm approach: system.time({ print( cint.nguyen(x, y, nmc = 2e3, conf.level = 0.95) ) }) # Grid of around 20ish steps deltas <- ((-11*10):(-9*10))/100 # grid steps of 0.01 # Naive with for-loops: system.time({ pvalmeans <- cint.naive.forloop(x, y, deltas, nmc = 2e3)$pvalmeans }) ``` ```{r tests-largest-array, echo=FALSE, eval=FALSE} # Naive with arrays: system.time({ pvalmeans <- cint.naive.array(x, y, deltas, nmc = 2e3)$pvalmeans }) ``` Here we finally see that the overhead built into `CIPerm::cint(dset())` makes it slightly slower than the streamlined `cint.nguyen()`. However, both are *substantially* faster than `cint.naive()`---they run in less than half the time of the naive approach. # `bench::mark()` and `profvis` The results above are from one run per method on each example dataset. Using the last ("largest") dataset, we also tried using `bench::mark()` to summarize the distribution of runtimes over many runs, as well as memory usage. *(Not actually run when the vignette knits, in order to avoid needing `bench` as a dependency.)* ```{r tests-largest-benchmark} # bench::mark(cint.nguyen(x, y, nmc = 2e3), # cint.naive.forloop(x, y, deltas, nmc = 2e3), # check = FALSE, min_iterations = 10) #> # A tibble: 2 × 13 #> expression min median `itr/sec` mem_alloc `gc/sec` n_itr n_gc total_time result memory time gc #> <bch:expr> <bch:tm> <bch:tm> <dbl> <bch:byt> <dbl> <int> <dbl> <bch:tm> <list> <list> <list> <list> #> 1 cint.nguyen(x, y, nmc = 2000) 2.5s 2.71s 0.364 1.58GB 2.92 10 80 27.44s <NULL> <Rprofmem [32,057 × 3]> <bench_tm [10]> <tibble [10 × 3]> #> 2 cint.naive.forloop(x, y, deltas, nmc = 2000) 7.87s 8.07s 0.120 7.4GB 4.64 10 388 1.39m <NULL> <Rprofmem [32,256 × 3]> <bench_tm [10]> <tibble [10 × 3]> ``` Finally, we also tried using the `profvis` package to check what steps are taking the longest time. *(Again, not actually run when the vignette knits, in order to avoid needing `profvis` as a dependency; but screenshots are included below.)* ```{r tests-largest-profvis} # profvis::profvis(cint.nguyen(x, y, nmc = 2e3)) # profvis::profvis(cint.naive.forloop(x, y, deltas, nmc = 2e3)) ``` For Nguyen's method, the initial setup with `combn()` or `sample()` followed by `apply(setdiff())` takes about 80% of the time, and the per-permutation calculations only take about 20% of the time: `profvis::profvis(cint.nguyen(x, y, nmc = 2e3))` ![](profvis_nguyen.png) For the naive method, the initial setup is identical, and each round of per-permutation calculations is slightly faster than in Nguyen's method... but because you have to repeat them many times (*unless you already know the CI endpoints, in which case you wouldn't need to run this at all!*), they can add up to substantially more total time than for Nguyen's method. `profvis::profvis(cint.naive.forloop(x, y, deltas, nmc = 2e3))` ![](profvis_naive.png)
/scratch/gouwar.j/cran-all/cranData/CIPerm/vignettes/naive.Rmd
--- title: "Replicating Nguyen (2009) with `CIPerm`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{nguyen} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` We show that our package replicates the analyses in: - Nguyen, M.D. (2009), "Nonparametric Inference using Randomization and Permutation Reference Distribution and their Monte-Carlo Approximation" [unpublished MS thesis; Mara Tableman, advisor], Portland State University. *Dissertations and Theses*. Paper 5927. [DOI:10.15760/etd.7798](https://doi.org/10.15760/etd.7798). Note that our R function arguments and outputs are structured differently than the similarly-named R functions in Nguyen (2009), but the results are equivalent. We also compare our output against related results in: - Ernst, M.D. (2004), "Permutation Methods: A Basis for Exact Inference," *Statistical Science*, vol. 19, no. 4, 676-685, [DOI:10.1214/088342304000000396](https://doi.org/10.1214/088342304000000396). Following Ernst (2004) and Nguyen (2009), we use the phrase "permutation methods" to include both *randomization* tests (where we assume random assignment of 2 treatments) and *permutation* tests (where we assume random sampling from 2 populations). In the simple settings in this R package, the randomization and permutation test mechanics are identical, though their interpretations may differ. # Brief overview of Nguyen (2009)'s method Consider a two-sample testing setup, where $X_1, \ldots, X_m$ are the responses from the control group and $Y_1, \ldots, Y_n$ are the responses from the treatment group. Imagine that lower responses are better (e.g., illness recovery times). With a standard one-sided randomization test or permutation test, we can test $H_0: \mu_Y - \mu_X \geq 0$ against $H_A: \mu_Y - \mu_X < 0$. We could also test for a specific value of $\mu_Y - \mu_X$, e.g. $H_0: \mu_Y - \mu_X \geq \Delta$ against $H_A: \mu_Y - \mu_X < \Delta$. If we assume a constant additive effect, we could carry this out by replacing all the $Y_j$ values with $Y_{j,\Delta} = Y_j-\Delta$ and then running the usual randomization test for a difference of 0. Finally, we can invert the test to get a confidence interval. If we repeat the procedure above for many difference values of $\Delta$ and record the values where the test fails to reject at level $\alpha$, we will have a $1-\alpha$ one-tailed confidence interval for $\Delta$. Doing this naively would require running many new permutations at each of many $\Delta$ values. But Nguyen (2009) derives a shortcut that gives this confidence interval directly from a single set of permutations. ## We don't have to recompute the permutation distribution for each $\Delta$ Each permutation involves swapping $k$ labels: we treat $k$ of the $X_i$ as if they were $Y_j$ and vice versa. Let $t_{k,d}$ be the difference in group means for $d^{th}$ of the permutations with $k$ swaps. For instance, on the original data we have \[t_0 = \frac{\sum_{j=1}^n Y_j}{n} - \frac{\sum_{i=1}^m X_i}{m}\] and other permutations have the form \[t_{k,d} = \frac{\sum_{i=1}^k X_i + \sum_{j=k+1}^n Y_j}{n} - \frac{\sum_{j=1}^k Y_j + \sum_{i=k+1}^m X_i}{m}\] Now if $t_{k,d,\Delta}$ is the same statistic but computed on the dataset where $Y_{j,\Delta}$ replaces $Y_j$, then Nguyen (2009) shows that \[t_{k,d,\Delta} = t_{k,d} - \Delta + k\left(\frac{1}{n}+\frac{1}{m}\right)\Delta\] So if we keep track of $k$ for each permutation, then one run of the randomization test is enough -- we don't need to carry out new runs for new $\Delta$ values. ## We don't have to try every possible $\Delta$ Next, we don't actually have to calculate $t_{k,d,\Delta}$ values directly---only the $t_{k,d}$ values we would usually calculate for a standard test of no difference in means, and the values of $k$ for each permutation. Let $w_{k,d} = \frac{t_0-t_{k,d}}{k\left(\frac{1}{n}+\frac{1}{m}\right)}$. Nguyen (2009) shows that if we compute the $w_{k,d}$ for each permutation and sort them, then their upper $\alpha$ quantile $w_{(\alpha)}$ gives the $1-\alpha$ one-sided CI upper bound for $\Delta$: \[\hat{P}[\Delta \in (-\infty, w_{(\alpha)})] = 1-\alpha\] To get a two-sided CI for $\Delta$, we can do this for both tails at half the nominal alpha. In our R package, `dset()` sets up the usual two-sample randomization or permutation test, but also records $k$ and $w_{k,d}$ for each permutation. Then `cint()` finds the appropriate quantiles of $w_{k,d}$ to return the confidence interval. We also track a few other test statistics, allowing `pval()` to return p-values for a difference in means, a difference in medians, or the Wilcoxon rank sum test. # Recovery times example Input the data from Table 1: ```{r setup1} library(CIPerm) x <- c(19, 22, 25, 26) y <- c(23, 33, 40) ``` Replicate Table 2 along with the three extra columns from Table 3: ```{r table2} demo <- dset(x, y, returnData = TRUE) knitr::kable(demo, digits = 2) ``` Replicate the left-tailed p-values reported on pages 5-6. The first three should be `0.08571429`, and the last should be `0.1142857`. ```{r pvals.p6} # Difference in means pval(demo, tail = "Left", value = "m") # Sum of treatment group pval(demo, tail = "Left", value = "s") # Difference in medians pval(demo, tail = "Left", value = "d") # Wilcoxon rank sum statistic pval(demo, tail = "Left", value = "w") ``` Replicate the confidence interval (left-tailed, with confidence level $(1 - \frac{2}{35})\times 100\% \approx 94.3\%$) reported on page 11. This should be `c(-Inf, 2)`. ```{r cint.p11} cint(demo, conf.level = 1-2/35, tail = "Left") ``` # Wing lengths and antennae lengths example Input and process the data from Table 4: ```{r setup2} wl1 <- c(1.72, 1.64, 1.74, 1.70, 1.82, 1.82, 1.90, 1.82, 2.08) wl2 <- c(1.78, 1.86, 1.96, 2.00, 2.00, 1.96) wl <- dset(wl1, wl2) al1 <- c(1.24, 1.38, 1.36, 1.40, 1.38, 1.48, 1.38, 1.54, 1.56) al2 <- c(1.14, 1.20, 1.30, 1.26, 1.28, 1.18) al <- dset(al1, al2) ``` Replicate the two-sided p-values from page 14, using the sum-of-group-1 test statistic. **NOTE:** Nguyen reports that the p-values as `0.07172827` for wing lengths, and `0.002197802` for antennae lengths. This matches our results. However, Ernst (2004) reports the p-values as `0.0719` and `0.0022`, in which case the first does not match our results after rounding, though they are very close. ```{r pvals.p14} pval(wl, tail = "Two", value = "s") pval(al, tail = "Two", value = "s") ``` Replicate the two-sided ~95\% CIs for the mean difference from page 15. **NOTE:** Nguyen reports these as 94.90\% CIs: `c(-0.246, 0.01)` for wing lengths and `c(0.087, 0.285)` for antennae lengths. However, Ernst (2004) reports a 94.90\% CI for wing lengths as `c(-0.250, 0.010)` and a 94.94\% (NOT 94.90\%!) CI for antennae lengths as `c(0.087, 0.286)`. Neither of these is an exact match for our own results below, though both are very close. ```{r cint.p15} cint(wl, conf.level = .95, tail = "Two") cint(al, conf.level = .95, tail = "Two") ``` The confidence levels in Ernst (2004) and Nguyen (2009) might differ from ours due to typos or rounding, since it is not possible to achieve exactly 94.90\% or 94.94\% confidence with this method. There are ${9+6 \choose 9} = 5005$ combinations. The closest confidence levels would be achieved if we used the 126th, 127th, or 128th lowest and highest $w_{k,d}$ values to get our two-sided CI endpoints. In those cases, the respective confidence levels would be $1-2\times(126/5005)\approx 0.94965$, $1-2\times(127/5005)\approx 0.94925$, or $1-2\times(128/5005)\approx 0.94885$. Also, Ernst (2004) may have different CI endpoints because he used an entirely different, less computationally-efficient method to calculate CIs, based on Garthwaite (1996), "Confidence intervals from randomization tests," *Biometrics* 52, 1387-1393, [DOI:10.2307/2532852](https://doi.org/10.2307/2532852). ## Wing and antennae lengths with Monte Carlo With a modern computer, it takes little time to run all ${9+6 \choose 9} = 5005$ possible combinations. But for larger datasets, where there are far more possible combinations, it can make sense to take a smaller Monte Carlo sample from all possible permutations. In our `dset()` function, the `nmc` argument lets us choose the number of Monte Carlo draws. As in Nguyen (2009), we repeat the above analysis, but this time we use 999 Monte Carlo draws instead of all 5005 possible combinations. Due to the randomness inherent in Monte Carlo sampling, these results will not match the exact results above nor Nguyen (2009)'s own Monte Carlo results; but they should be fairly close. ```{r montecarlo} wl <- dset(wl1, wl2, nmc = 999) al <- dset(al1, al2, nmc = 999) pval(wl, tail = "Two", value = "s") pval(al, tail = "Two", value = "s") cint(wl, conf.level = .95, tail = "Two") cint(al, conf.level = .95, tail = "Two") ```
/scratch/gouwar.j/cran-all/cranData/CIPerm/vignettes/nguyen.Rmd
#' @title Mean Stress #' #' @description This function provides the mean stress among As and Bs, corresponding to different environment levels, for a list of variables. #' #' @param dataset Data set to be utilized. For the purposes of this function, the binary values in each variable are considered to be -1 and 1. #' @param var A list of variables. If using variables from a DGLM, use the variables from the mean model (or, if trying to find intervals for use in the plotting functions draw.crossplots and draw.squareplots, use all variables in both mean and variance models). #' @param stress_variable Name of the variable with the stress values. #' @param output.name Name of the output file to which to save the outputs. Defaults to 'mean_stress.txt'. #' @param use.output A binary variable to indicate whether the output is automatically saved to an external text file. Defaults to TRUE. If FALSE, the output will not be saved to a file. #' @param bin.levels A list that provides the binary values utilized in the dataset. Defaults to c(0,1), indicating that 0 and 1 are used as the binary outcomes; can also be 1, -1. List the value for the "A" environment level first, then the value for the "B" environment level. #' @return Produces a data frame with three columns: var, AvgB, and AvgA. These provide the variable and its corresponding mean stress values for As and Bs, corresponding to different environment levels. #' #' @examples #' test.data <- simu.inter.dat.interboth(n.rep = 2, n.obs.per.rep = 15, ran.seed = 1) #' variables <- colnames(test.data[-1]) #' mean_stress(test.data, variables, 'stress', use.output = FALSE) #' @export mean_stress<-function(dataset,var,stress_variable,output.name='mean_stress.txt',use.output=TRUE, bin.levels=c(0,1)){ if (use.output){ sink(output.name); } out = data.frame(var=character(), AvgB=double(), AvgA=double()) for (i in var){ v.txt<-paste('dataset',i,sep='$') v<-eval(parse(text = v.txt)); v2.txt<-paste('dataset',stress_variable,sep='$') v2<-eval(parse(text = v2.txt)); d = data.frame(v,v2) AvgB = mean((d[d[,'v']==bin.levels[2],'v2'])) # avg stress among Bs (or 1s) AvgA = mean((d[d[,'v']==bin.levels[1],'v2'])) # avg stress among As (or -1s) out[nrow(out)+1,'var'] <- i out[nrow(out),'AvgB'] <- AvgB out[nrow(out),'AvgA'] <- AvgA } #if (use.output){ # sink(); #} return(out) } ### the function above takes the dataset, a list of variables, and the stress variable and produces a data frame with the ### average stress of As and average stress of Bs for each variable listed in var #' @title Standard Deviation Stress #' #' @description This function provides the mean stress among As and Bs, corresponding to different environment levels, for a list of variables. #' #' @param dataset Data set to be utilized. For the purposes of this function, the binary values in each variable are considered to be -1 and 1. #' @param var A list of variables. If using variables from a DGLM, use the variables from the variance model (or, if trying to find intervals for use in the plotting functions draw.crossplots and draw.squareplots, use all variables in both mean and variance models). #' @param stress_variable Name of the variable with the stress values. #' @param output.name Name of the output file to which to save the outputs. Defaults to 'sd_stress.txt'. #' @param use.output A binary variable to indicate whether the output is automatically saved to an external text file. Defaults to TRUE. If FALSE, the output will not be saved to a file. #' @param bin.levels A list that provides the binary values utilized in the dataset. Defaults to c(0,1), indicating that 0 and 1 are used as the binary outcomes; can also be 1, -1. List the value for the "A" environment level first, then the value for the "B" environment level. #' @return Produces a data frame with three columns: var, sd1, and sdneg1. These provide the variable and its corresponding standard deviation of stress values for As and Bs, corresponding to different environment levels. #' #' @examples #' test.data <- simu.inter.dat.interboth(n.rep = 3, n.obs.per.rep = 15, ran.seed = 1) #' variables <- colnames(test.data[-1]) #' sd.stress(test.data, variables, 'stress', use.output = FALSE) #' @export sd.stress<-function(dataset,var,stress_variable,output.name='sd_stress.txt',use.output=TRUE, bin.levels=c(0,1)){ if (use.output){ sink(output.name); } out = data.frame(var=character(), sdB=double(), sdA=double()) for (i in var){ v.txt<-paste('dataset',i,sep='$') v<-eval(parse(text = v.txt)); v2.txt<-paste('dataset',stress_variable,sep='$') v2<-eval(parse(text = v2.txt)); d = data.frame(v,v2) sdB = stats::sd((d[d[,'v']==bin.levels[2],'v2'])) # sd for stress among Bs (or 1s) sdA = stats::sd((d[d[,'v']==bin.levels[1],'v2'])) # sd for stress among As (or -1s) out[nrow(out)+1,'var'] <- i out[nrow(out),'sdB'] <- sdB out[nrow(out),'sdA'] <- sdA } #if (use.output){ # sink(); #} return(out) } ### the function above takes the dataset, a list of variables, and the stress variable and produces a dataframe with the ### standard deviation of stress of As and standard deviation of stress of Bs for each variable listed in var #' @title Bootstrap #' #' @description This function implements a custom bootstrapping procedure that utilizes bootstrapping to estimate mean and SD of stress between two environment states (A and B). #' #' @param dataset Data set to be utilized. #' @param n.boot Number of bootstraps to perform. Defaults to 10^5. #' @param variables List of variables from mean and variance models in DGLM. #' @param stress_variable Name of the variable with the stress values. #' @param alpha Significance level by which to determine the confidence intervals for the bootstrap estimates. Defaults to 0.05, thus creating the 95 percent confidence intervals. #' @param ran.seed Random seed value for generating different random bootstrap samples.] #' @return Lists with confidence intervals for the bootstrap estimations for average stress in As and Bs of variables in mean model and confidence intervals for the bootstrap estimations of standard deviation of stress in As and Bs of variables in variance model. #' #' @examples #' test.data <- simu.inter.dat.interboth(n.rep = 3, n.obs.per.rep = 15, ran.seed = 1) #' variables <- colnames(test.data[-1]) #' bootstrap(test.data, n.boot=100,variables, 'stress') #' unlink(c('bootstrap mean A stress.txt','bootstrap mean B stress.txt', #' 'bootstrap sd A stress.txt', 'bootstrap sd B stress.txt')) #' @export bootstrap <- function(dataset, n.boot=10^5, variables, stress_variable, alpha=0.05, ran.seed=12345){ n<-dim(dataset)[1]; set.seed(ran.seed); boot.mean.B<-boot.mean.A<-boot.var.A<-boot.var.B<-NULL; i<-1; out.loop1<-vector(mode = "list", length = n.boot) out.loop2<-vector(mode = "list", length = n.boot) while(i<=n.boot) { boot.index<-sample(1:n,replace=TRUE) data.idx <- dataset[boot.index,] out.loop1[[i]]<-mean_stress(dataset=data.idx,variables,stress_variable,use.output=FALSE); out.loop2[[i]]<-sd.stress(dataset=data.idx,variables,stress_variable,use.output=FALSE); # conditional check to ensure that there are no NA's in the final output if (!any(is.na(out.loop1[[i]][2])) && !any(is.na(out.loop1[[i]][3])) && !any(is.na(out.loop2[[i]][2])) && !any(is.na(out.loop1[[i]][3]))) { # means, separated by A's and B's boot.mean.B<-rbind(boot.mean.B,out.loop1[[i]][[2]]); boot.mean.A<-rbind(boot.mean.A,out.loop1[[i]][[3]]); # SD's, separated by A's and B's boot.var.B<- rbind(boot.var.B, out.loop2[[i]][[2]]); boot.var.A<- rbind(boot.var.A, out.loop2[[i]][[3]]); i<-i+1; } } colnames(boot.mean.A)<- colnames(boot.mean.B) <- colnames(boot.var.A) <- colnames(boot.var.B) <- variables mean_stressA <- apply(boot.mean.A,2,stats::quantile,c(alpha/2,1-(alpha/2))) mean_stressB <- apply(boot.mean.B,2,stats::quantile,c(alpha/2,1-(alpha/2))) var_stressA <- apply(boot.var.A,2,stats::quantile,c(alpha/2,1-(alpha/2))) var_stressB <- apply(boot.var.B,2,stats::quantile,c(alpha/2,1-(alpha/2))) utils::write.table(mean_stressA, 'bootstrap mean A stress.txt', row.names = T, col.names = T) utils::write.table(mean_stressB, 'bootstrap mean B stress.txt', row.names = T, col.names = T) utils::write.table(var_stressA, 'bootstrap sd A stress.txt', row.names = T, col.names = T) utils::write.table(var_stressB, 'bootstrap sd B stress.txt', row.names = T, col.names = T) return (list(mean_stressA, mean_stressB, var_stressA, var_stressB)) }
/scratch/gouwar.j/cran-all/cranData/CIS.DGLM/R/Boot.functions.R