content
stringlengths 0
14.9M
| filename
stringlengths 44
136
|
---|---|
### subsetEventData
##' @title Subset a \code{bammdata} object
##'
##' @description Subsets a \code{bammdata} object. Returns a \code{bammdata}
##' object after extracting a specified set of samples from the posterior.
##'
##' @param ephy An object of class \code{bammdata}.
##' @param index A vector of integers corresponding to samples to be extracted
##' from the posterior distribution of shift configurations included in
##' the \code{bammdata} object.
##'
##' @details This will result in an error if you attempt to access samples
##' that do not exist in the \code{ephy} data object. For example, if your
##' \code{bammdata} object includes 100 samples from a posterior
##' distribution sampled with \code{BAMM}, you can only attempt to subset
##' with index values 1:100.
##'
##' @author Dan Rabosky
##'
##' @seealso \code{\link{plot.bammdata}}, \code{\link{getCohortMatrix}},
##' \code{\link{image}}
##'
##' @examples
##' data(whales, events.whales)
##' ed <- getEventData(whales, events.whales, nsamples=500)
##' ed2 <- subsetEventData(ed, index=1)
##' plot(ed2)
##' addBAMMshifts(ed2, cex=2)
##' @keywords manip
##' @export
subsetEventData <- function(ephy, index) {
if (!inherits(ephy, 'bammdata')) {
stop("Object ephy must be of class bammdata\n");
}
nsamples <- length(ephy$eventData);
ss <- which((1:nsamples) %in% index);
badsubset <- setdiff(index, 1:nsamples);
if (length(badsubset) > 0) {
cat("Bad call to BAMMtools::subsetEventData\n");
cat("You have << ", nsamples, " >> samples in your data object \n");
stop("Attempt to access invalid samples. Check index.")
}
obj <- list();
obj$edge <- ephy$edge;
obj$Nnode <- ephy$Nnode;
obj$tip.label <- ephy$tip.label;
obj$edge.length <- ephy$edge.length;
obj$begin <- ephy$begin;
obj$end <- ephy$end;
obj$downseq <- ephy$downseq;
obj$lastvisit <- ephy$lastvisit;
obj$numberEvents <- ephy$numberEvents[ss];
obj$eventData <- ephy$eventData[ss];
obj$eventVectors <- ephy$eventVectors[ss];
obj$tipStates <- ephy$tipStates[ss]
obj$tipLambda <- ephy$tipLambda[ss];
obj$tipMu <- ephy$tipMu[ss];
obj$eventBranchSegs <- ephy$eventBranchSegs[ss];
obj$meanTipLambda <- ephy$meanTipLambda;
obj$meanTipMu <- ephy$meanTipMu;
obj$type <- ephy$type;
class(obj) <- 'bammdata';
attributes(obj)$order = attributes(ephy)$order;
return(obj);
}
| /scratch/gouwar.j/cran-all/cranData/BAMMtools/R/subsetEventData.R |
##' @title Pulls out a subtree from \code{bammdata} object
##'
##' @description Given a set of tips or a node, this function extracts the
##' corresponding subtree from the \code{bammdata} object. User should
##' specify either a set of tips or a node, and the node will overwrite
##' the tips if both are given.
##'
##' @param ephy An object of class \code{bammdata}.
##' @param tips An integer or character vector indicating which tips (more
##' than one) to be included in the subtree.
##' @param node An integer indicating the root of the subtree to be extracted,
##' and it must correspond to an innernode on the tree.
##'
##' @details This function allows users to extract a subtree from a big
##' \code{bammdata} object, and examine the subset using
##' \code{\link{plot.bammdata}}
##'
##' @return An object of class \code{bammdata}.
##'
##' @author Huateng Huang
##'
##' @seealso \code{\link{getmrca}}, \code{\link{plot.bammdata}}
##'
##' @examples
##' data(whales, events.whales)
##' ephy <- getEventData(whales, events.whales, burnin=0.25, nsamples=500)
##'
##' # specify a set of tips for the subtree
##' tips <- sample(ephy$tip.label,size=20,replace=FALSE)
##' subphy <- subtreeBAMM(ephy,tips=tips)
##'
##' # specify a innernode for subsetting
##' subphy <- subtreeBAMM(ephy,node=103)
##'
##' # plot the subtree
##' plot(subphy)
##' @keywords graphics
##' @export
subtreeBAMM <- function(ephy,tips=NULL,node=NULL)
{
if (!inherits(ephy, 'bammdata'))
stop('Object phy must be of class bammdata');
if (is.null(tips) && is.null(node))
stop("need to specify either the tips or a innernode on the tree for subsetting");
if ((!is.null(tips)) && (!is.null(node)))
cat("specified both tips and node, will subset the bammdata object according to the node\n");
wtree <- as.phylo.bammdata(ephy);
if (!is.null(node)) {
if(node <= length(wtree$tip.label))
stop('error: the node corresponds to one single tip')
else if (node > max(wtree$edge))
stop('the node does not exist on the tree');
tips <- ephy$downseq[which(ephy$downseq == node):which(ephy$downseq == ephy$lastvisit[node])];
tips <- wtree$tip.label[tips[tips <= wtree$Nnode + 1]];
}
else {
if (length(tips) == 1)
stop("need more than one tip to subset the bammdata object");
if (!inherits(tips, 'character'))
tips <- wtree$tip.label[tips];
}
stree <- drop.tip(wtree, tip = setdiff(wtree$tip.label, tips));
stree <- getStartStopTimes(stree);
stree <- getRecursiveSequence(stree);
sNtip <- length(stree$tip.label);
oldnode <- integer(max(stree$edge));
oldnode[1:sNtip] <- match(stree$tip.label, wtree$tip.label);
fn <- function(node, phy) {
tps <- phy$downseq[which(phy$downseq == node):which(phy$downseq == phy$lastvisit[node])];
tps <- tps[tps <= phy$Nnode+1];
return (c(node, tps[1], tps[length(tps)]));
}
lrkids <- t(sapply(unique(stree$edge[,1]), fn, stree));
oldnode[lrkids[,1]] <- getmrca(wtree, oldnode[lrkids[,2]], oldnode[lrkids[,3]]);
inner_node_shift <- matrix(0L, 0, 2);
sapply(seq.int(1,nrow(stree$edge)), function(x) {
downnode <- oldnode[stree$edge[x,2]];
upnode <- oldnode[stree$edge[x,1]];
j <- wtree$edge[which(wtree$edge[,2] == downnode), 1];
while (j != upnode) {
inner_node_shift <<- rbind(inner_node_shift, c(j, stree$edge[x,2]));
j <- wtree$edge[which(wtree$edge[,2] == j), 1];
}
});
nsamples <- length(ephy$eventData);
subphy <- stree;
class(subphy) <- "bammdata";
subphy$numberEvents <- integer(nsamples);
subphy$eventData <- vector("list",nsamples);
subphy$eventVectors <- vector("list",nsamples);
subphy$tipStates <- vector("list",nsamples);
subphy$tipLambda <- lapply(ephy$tipLambda, function(x) x[oldnode[1:sNtip]]);
subphy$meanTipLambda <- ephy$meanTipLambda[oldnode[1:sNtip]];
subphy$eventBranchSegs <- vector("list",nsamples);
subphy$tipMu <- lapply(ephy$tipMu, function(x) x[oldnode[1:sNtip]]);
subphy$meanTipMu <- ephy$meanTipMu[oldnode[1:sNtip]];
subphy$type <- ephy$type;
if (oldnode[sNtip+1] == length(ephy$tip.label)+1)
rootshift <- 0
else
rootshift <- max(ephy$end) - max(subphy$end);
for (en in 1:nsamples) {
eventData <- ephy$eventData[[en]];
eventVectors <- ephy$eventVectors[[en]];
if (rootshift > 0)
root_proc <- eventVectors[which(ephy$edge[,2] == oldnode[sNtip+1])]
else
root_proc <- 1L;
eventData$node <- sapply(eventData$node, function(x) {
if (x %in% oldnode)
which(oldnode == x)
else if (x %in% inner_node_shift[, 1])
inner_node_shift[which(inner_node_shift[, 1] == x), 2]
else
0L;
});
eventData$time <- eventData$time-rootshift;
eventData <- eventData[(eventData$node > 0L) | (eventData$index == root_proc), ];
eventData$node[eventData$node == 0L] <- sNtip+1;
r <- which(eventData$time < 0);
if (length(r) > 0) {
if (length(r) > 1)
r <- which(eventData$time == max(eventData$time[r]));
eventData$lam1[r] <- exponentialRate(0-eventData$time[r], eventData$lam1[r], eventData$lam2[r]);
if (subphy$type == "diversification")
eventData$mu1[r] <- exponentialRate(0-eventData$time[r], eventData$mu1[r], eventData$mu2[r]);
eventData$time[r] <- 0;
}
eventData <- eventData[eventData$time >= 0, ];
eventData <- eventData[order(eventData$time),];
subphy$numberEvents[en] <- dim(eventData)[1];
newprocess <-eventData$index;
eventData$index <- 1:dim(eventData)[1];
subphy$eventData[[en]] <- eventData;
tipStates <- ephy$tipStates[[en]];
tipStates <- tipStates[oldnode[1:sNtip]];
subphy$tipStates[[en]] <- match(tipStates, newprocess);
eventVectors <- eventVectors[match(oldnode[subphy$edge[,2]], ephy$edge[,2], nomatch = 0)];
subphy$eventVectors[[en]] <- match(eventVectors, newprocess);
eventBranchSegs <- cbind(subphy$edge[,2], subphy$begin, subphy$end, subphy$eventVectors[[en]]);
eventBranchSegs <- eventBranchSegs[!(eventBranchSegs[,1] %in% eventData$node[-1]),];
if (nrow(eventData) > 1) {
for (n in unique(eventData$node[-1])) {
branch_event <- eventData[eventData$node == n,];
upnode <- subphy$edge[which(subphy$edge[,2] == n), 1];
if (upnode == sNtip+1)
startproc <- 1L
else
startproc <- subphy$eventVectors[[en]][which(subphy$edge[,2] == upnode)];
starttime <- subphy$begin[which(subphy$edge[,2] == n)];
for (be in 1:nrow(branch_event)) {
eventBranchSegs <- rbind(eventBranchSegs,c(n,starttime,branch_event$time[be],startproc));
startproc <- branch_event$index[be];
starttime <- branch_event$time[be];
}
eventBranchSegs <- rbind(eventBranchSegs,c(n,starttime,subphy$end[which(subphy$edge[,2]==n)],startproc));
}
}
subphy$eventBranchSegs[[en]] <- eventBranchSegs[order(eventBranchSegs[,1]),];
}
return (subphy);
}
# subtreeBAMM<-function(ephy,tips=NULL,node=NULL)
# {
# if (! 'bammdata' %in% class(ephy)) {
# stop('Object phy must be of class bammdata');
# }
# if(is.null(tips)& is.null(node)){
# stop("need to specify either the tips or a innernode on the tree for subsetting");
# }
# if((!is.null(tips))&(! is.null(node))){
# cat("specified both tips and node, will subset the bammdata object according to the node\n")
# }
# # get the whole tree
# wtree <- as.phylo.bammdata(ephy)
# #wtree<-list()
# #wtree$edge<-phy$edge
# #wtree$Nnode<-phy$Nnode
# #wtree$tip.label<-phy$tip.label
# #wtree$edge.length<-phy$edge.length
# #class(wtree)<-'phylo'
# if(! is.null(node)){
# if(node<=length(wtree$tip.label)){
# stop('error: the node corresponds to one single tip')
# }else if (node> max(wtree$edge)){
# stop('the node does not exist on the tree')
# }
# tips <- ephy$downseq[which(ephy$downseq == node):which(ephy$downseq == ephy$lastvisit[node])]
# tips <- wtree$tip.label[tips[tips <= wtree$Nnode + 1]]
# #get_all_kid<-function(phy,node){
# # if(node<=phy$Nnode+1){
# # return(node);
# # }else{
# # tip<-c();
# # innernode<-c(node);
# # while (length(innernode)>0){
# # l<-phy$edge[,1] %in% innernode
# # m<-phy$edge[l,2]
# # tip<-c(tip,m[m<=phy$Nnode+1])
# # innernode<-m[m>phy$Nnode+1]
# # }
# # return(tip)
# # }
# #}
# #tips<-wtree$tip.label[get_all_kid(wtree,node)]
# }else{
# if(length(tips)==1){
# stop("need more than one tip to subset the bammdata object")
# }
# if(class(tips) != 'character'){
# #stop("tips should be a character string")
# tips <- wtree$tip.label[tips]
# }
# }
# #get the sub tree
# stree<-drop.tip(wtree,tip=wtree$tip.label[! wtree$tip.label %in% tips])
# sNtip<-length(stree$tip.label)
# #for every node on the subset tree, get its corresponding node on the whole tree
# oldnode<-integer(length=max(stree$edge))
# oldnode[1:sNtip]<-match(stree$tip.label,wtree$tip.label)
# # for every inner node on the stree get its left kid and right kid
# lrkids<-matrix(0,nrow=0,ncol=3);
# get_lr_kids<-function(tree,node){
# ll<-which(tree$edge[,1]==node)
# if(length(ll)>0){
# l<-get_lr_kids(tree,tree$edge[ll[1],2])
# r<-get_lr_kids(tree,tree$edge[ll[2],2])
# return(rbind(l,r,c(node,min(l),min(r))))
# }else{
# return(matrix(c(node,node,node),nrow=1,ncol=3))
# }
# }
# lrkids<-get_lr_kids(stree,sNtip+1);
# lrkids<-lrkids[which(lrkids[,1]>sNtip),]
# oldnode[lrkids[,1]]<-getmrca(wtree,oldnode[lrkids[,2]],oldnode[lrkids[,3]])
# # for every branch on the new tree, get its corresponding branches on the whole tree
# # innernodes on the original trees shift towards the tip
#
# inner_node_shift<-matrix(0L,nrow=0,2)
# for (x in 1: dim(stree$edge)[1]){
# downnode<-oldnode[stree$edge[x,2]]
# upnode<-oldnode[stree$edge[x,1]]
# j<-downnode;
# j=wtree$edge[which(wtree$edge[,2]==j),1]
# while (j !=upnode){
# inner_node_shift<-rbind(inner_node_shift,c(j,stree$edge[x,2]))
# j=wtree$edge[which(wtree$edge[,2]==j),1]
# #cat(j)
# }
# }
# subphy<-stree;
# class(subphy)<-"bammdata"
# stree<-getStartStopTimes(stree)
# subphy$begin<-stree$begin
# subphy$end<-stree$end
# stree <- getRecursiveSequence(stree);
# subphy$downseq<-stree$downseq
# subphy$lastvisit<-stree$lastvisit
# subphy$numberEvents<- c()
# subphy$eventData<-list()
# subphy$eventVectors<-list()
# subphy$tipStates<-list()
# subphy$tipLambda<-lapply(ephy$tipLambda,function(x){x[oldnode[1:sNtip]]})
# subphy$meanTipLambda<-ephy$meanTipLambda[oldnode[1:sNtip]]
# subphy$eventBranchSegs<-list()
# subphy$tipMu<-lapply(ephy$tipMu,function(x){x[oldnode[1:sNtip]]})
# subphy$meanTipMu<-ephy$meanTipMu[oldnode[1:sNtip]]
# subphy$type<-ephy$type
# if(oldnode[sNtip+1]==length(ephy$tip.label)+1){
# rootshift<-0
# }else{
# rootshift<-max(ephy$end)-max(subphy$end)
# }
# for (en in 1:length(ephy$numberEvents)){
# #cat(en,"\n")
# eventData<-ephy$eventData[[en]];
# eventVectors<-ephy$eventVectors[[en]]
# if(rootshift>0){
# root_process<-eventVectors[which(ephy$edge[,2]==oldnode[sNtip+1])]
# }else{
# root_process<-1L
# }
# eventData$node<-sapply(eventData$node,function(x){
# if(x %in% oldnode){
# which(oldnode==x);
# }else if(x %in% inner_node_shift[,1]){
# inner_node_shift[ which(inner_node_shift[,1]==x),2]
# }else{
# 0L
# }
# })
# eventData$time<-eventData$time-rootshift
# eventData<-eventData[(eventData$node>0)|(eventData$index==root_process),]
# #fix the root process
# eventData$node[eventData$node==0L]<-sNtip+1; #the only reason that a event that does not happen on stree and still is kept is that it is a root process
# l<-which(eventData$time<0);
# if(length(l)>0){
# if(length(l)>1){
# l<-which(eventData$time==max(eventData$time[l]))
# }
# #eventData$lam1[l]<-eventData$lam1[l]*exp((0-eventData$time[l])*eventData$lam2[l])
# eventData$lam1[l]<-exponentialRate(0-eventData$time[l], eventData$lam1[l], eventData$lam2[l])
# eventData$time[l]<-0;
# }
# eventData<-eventData[eventData$time>=0,]
# eventData<-eventData[order(eventData$time),]
# #now fix the index of the process
# subphy$numberEvents[en]<-dim(eventData)[1]
# newprocess<-eventData$index;
# eventData$index<-1:dim(eventData)[1];
# subphy$eventData[[en]]<-eventData
# #fix the tipstate
# tipState<-ephy$tipStates[[en]];
# tipState<-tipState[oldnode[1:sNtip]]
# subphy$tipStates[[en]]<-match(tipState,newprocess)
# #fix the eventVectors
# eventVectors<-sapply(subphy$edge[,2], function(x){eventVectors[which(ephy$edge[,2]==oldnode[x])]})
# subphy$eventVectors[[en]]<-match(eventVectors,newprocess)
# #write up a new eventBranchSeg
# eventBranchSegs<-cbind(subphy$edge[,2],subphy$begin,subphy$end,subphy$eventVectors[[en]])
# eventBranchSegs<-eventBranchSegs[ ! eventBranchSegs[,1] %in% eventData$node[eventData$time>0],]
# if(length(eventData$node[eventData$time>0])>0){
# for (n in unique(eventData$node[eventData$time>0])){
# branch_event<-eventData[eventData$node==n,]
# branch_event<-branch_event[order(branch_event$time),]
# upnode<-subphy$edge[ which(subphy$edge[,2]==n),1]
# if(upnode==sNtip+1){startproc<-1L;}else{startproc<-subphy$eventVectors[[en]][which(subphy$edge[,2]==upnode)]}
# starttime<-subphy$begin[which(subphy$edge[,2]==n)];
# for (be in 1:dim(branch_event)[1]){
# #l<-c(n,starttime,branch_event$time[be],startproc);
# eventBranchSegs<-rbind(eventBranchSegs,c(n,starttime,branch_event$time[be],startproc));
# startproc<-branch_event$index[be]
# starttime<-branch_event$time[be]
# }
# eventBranchSegs<-rbind(eventBranchSegs,c(n,starttime,subphy$end[which(subphy$edge[,2]==n)],startproc));
# }
# }
# subphy$eventBranchSegs[[en]]<-eventBranchSegs[order(eventBranchSegs[,1]),]
# }
# return(subphy);
# }
| /scratch/gouwar.j/cran-all/cranData/BAMMtools/R/subtreeBAMM.R |
##' @title Summary of rate shift results from \code{BAMM} analysis
##'
##' @description Summarizes the posterior distribution on the number of
##' shifts.
##'
##' @param object An object of class \code{bammdata}.
##' @param display An integer for the number of rows of the posterior to
##' display.
##' @param print Print summary of shift distribution in console window?
##' @param \dots Additional arguments (currently unused).
##'
##' @details Prints to console the number of posterior samples and the
##' posterior distribution on the number of shifts, which is just the
##' fraction of samples in the posterior having 0, 1, 2,...n shifts.
##'
##' @return Returns (invisibly) a dataframe with 2 components:
##' \item{shifts}{The number of shifts.}
##' \item{prob}{The corresponding posterior probability of a model with a
##' given number of rate shifts.}
##'
##' @author Mike Grundler, Dan Rabosky
##'
##' @references \url{http://bamm-project.org/}
##'
##' @examples
##' data(whales, events.whales)
##' ephy <- getEventData(whales, events.whales, nsamples=100)
##' summary(ephy)
##' @keywords models
##' @export
summary.bammdata = function(object, display=10, print=T, ...) {
fev <- sapply(object$eventData, nrow);
xx <- table(fev - 1);
shifts <- as.numeric(names(xx));
xx <- as.numeric(xx);
df <- data.frame(shifts = shifts, prob = signif(xx / sum(xx), digits= 3));
if (print){
cat("\nAnalyzed", length(object$eventData), "posterior samples\n");
cat("Shift posterior distribution:\n\n");
disp <- data.frame(cbind(df$shifts),signif(df$prob,2));
if (nrow(disp) <= display) {
write.table(format(disp,justify="left",width=10), col.names=FALSE, row.names=FALSE, quote=FALSE);
} else {
if(nrow(disp)-display == 1) {
write.table(format(disp[1:display,],justify="left",width=10), col.names=FALSE, row.names=FALSE, quote=FALSE);
cat("... omitted 1 row\n\n");
}else {
wr <- which(disp[,2] == max(disp[,2]))[1];
index <- c(max(1,floor(wr-display/2)), wr, min(ceiling(wr+display/2),nrow(disp)));
if (index[1] > 1) {
cat("... omitted",index[1]-1,"rows\n");
}
write.table(format(disp[index[1]:index[3],],justify="left",width=10), col.names=FALSE, row.names=FALSE, quote=FALSE);
cat("... omitted", nrow(disp)-index[3]-1,"rows\n\n");
}
}
cat("\nCompute credible set of shift configurations for more information:\n");
cat("\tSee ?credibleShiftSet and ?getBestShiftConfiguration\n");
}
invisible(df);
}
| /scratch/gouwar.j/cran-all/cranData/BAMMtools/R/summary.bammdata.R |
##' @title Summary of credible set of shift configurations from a \code{BAMM}
##' analysis
##'
##' @description Prints summary attributes of the \code{BAMM} credible set of
##' shift configurations.
##'
##' @param object,x An object of class \code{credibleshiftset}.
##' @param \dots Additional arguments (unused).
##'
##' @details Prints to console summary attributes of the XX\% credible set of
##' shift configurations sampled using \code{BAMM}. Attributes printed
##' include: the number of distinct configurations in the XX\% credible
##' set and the posterior probability, cumulative probability, and number
##' of rate shifts in the 9 most-probable shift configurations.
##'
##' @return \code{summary.credibleshiftset} returns (invisibly) a dataframe
##' with a number of rows equal to the number of shift configurations in
##' the credible set and four columns:
##' \item{rank}{The ranked index of each shift configuration (ranked by
##' posterior probability).}
##' \item{probability}{The posterior probability of each shift
##' configuration.}
##' \item{cumulative}{The cumulative probability of each shift
##' configuration.}
##' \item{N_shifts}{The number of rate shifts in each shift
##' configuration (can be zero).}
##'
##' @author Dan Rabosky
##'
##' @seealso \code{\link{distinctShiftConfigurations}},
##' \code{\link{plot.bammshifts}}, \code{\link{credibleShiftSet}}
##'
##' @references \url{http://bamm-project.org/}
##'
##' @examples
##' data(whales, events.whales)
##' ed <- getEventData(whales, events.whales, nsamples = 500)
##' cset <- credibleShiftSet(ed, expectedNumberOfShifts = 1, threshold = 5)
##' summary(cset)
##' @rdname summary.credibleshiftset
##' @keywords models
##' @export
summary.credibleshiftset <- function(object, ...) {
conf <- round(100*object$set.limit);
cat('\n', conf, '% credible set of rate shift configurations sampled with BAMM');
cat('\n\nDistinct shift configurations in credible set: ', object$number.distinct);
mm <- min(c(9, object$number.distinct));
if (object$number.distinct > 9){
omitted <- object$number.distinct - 9;
}
xvec <- numeric(object$number.distinct);
dd <- data.frame(rank=1:object$number.distinct, probability = xvec, cumulative=xvec, Core_shifts=xvec);
for (i in 1:nrow(dd)){
dd$probability[i] <- object$frequency[i];
dd$cumulative[i] <- object$cumulative[i];
dd$Core_shifts[i] <- length(object$shiftnodes[[i]]);
}
cat('\n\nFrequency of', mm, 'shift configurations with highest posterior probability:\n\n\n');
write.table(format(t(names(dd)),justify="centre",width=10), col.names=FALSE, row.names=FALSE, quote=FALSE);
write.table(format(dd[1:mm,], justify="none", width=10), col.names=FALSE, row.names=FALSE, quote=FALSE);
# cat('\n\tRank\t\tProb\tCumulative\t\tCoreShifts\n')
# for (i in 1:mm){
# cat('\t\t', format(i, justify='left'), '\t\t', format(round(object$frequency[i], 3), nsmall=3), '\t');
# cat(round(object$cumulative[i], 3), '\t\t\t', length(object$shiftnodes[[i]]), '\n');
# }
if (object$number.distinct > 9){
cat('\n...omitted', omitted, 'additional distinct shift configurations\n');
cat('from the credible set. You can access the full set from your \n');
cat('credibleshiftset object\n');
}
cat('\n')
invisible(dd);
}
##' @export
##' @rdname summary.credibleshiftset
print.credibleshiftset <- function(x, ...){
summary.credibleshiftset(x, ...);
}
| /scratch/gouwar.j/cran-all/cranData/BAMMtools/R/summary.credibleshiftset.R |
##' @title Evaluate evidence for temporal rate variation across tree
##'
##' @description For each branch in a phylogenetic tree, evaluates the
##' evidence (posterior probability or Bayes factor) that
##' macroevolutionary rates have varied through time.
##'
##' @param ephy An object of class \code{bammdata}.
##' @param prior_tv The prior probability that rate shifts lead to a new
##' time-varying rate process (versus a time-constant process).
##' @param return.type Either \code{"posterior"} or \code{"bayesfactor"},
##' depending on which form of evidence you would like.
##'
##' @details In \code{BAMM 2.0}, rate shifts on trees can lead to time-varying
##' or constant-rate diversification processes. In other words, the model
##' will incorporate temporal variation in rates only if there is
##' sufficient evidence in the data to favor it. The function
##' \code{testTimeVariableBranches} enables the user to extract the
##' evidence in favor of time-varying rates on any branch of a
##' phylogenetic tree from a \code{bammdata} object.
##'
##' The function returns a copy of the original phylogenetic tree, but
##' where branch lengths have been replaced by either the posterior
##' probability (\code{return.type = "posterior"}) or the Bayes factor
##' evidence (\code{return.type = "bayesfactor"}) that the
##' macroevolutionary rate regime governing each branch is time-variable.
##' Consider a particular branch X on a phylogenetic tree. If the length
##' of this branch is 0.97 and \code{return.type = "posterior"}, this
##' implies that branch X was governed by a time-varying rate dynamic in
##' 97\% of all samples in the posterior. Alternatively, only 3\% of
##' samples specified a constant rate dynamic on this branch.
##'
##' The function also provides an alternative measure of support if
##' \code{return.type = "bayesfactor"}. In this case, the Bayes factor
##' evidence for temporal rate variation is computed for each branch. We
##' simply imagine that diversification rates on each branch can be
##' explained by one of two models: either rates vary through time, or
##' they do not. In the above example (branch X), the Bayes factor would
##' be computed as follows, letting \emph{Prob_timevar} and
##' \emph{Prior_timevar} be the posterior and prior probabilities that a
##' particular branch is governed by a time-varying rate process:
##'
##' \emph{( Prob_timevar) / (1 - Prob_timevar)} * \emph{ (1 -
##' prior_timevar) / (prior_timevar) }
##'
##' The Bayes factor is not particularly useful under uniform prior odds
##' (e.g., \code{prior_tv = 0.5}), since this simply reduces to the ratio
##' of posterior probabilities. Note that the prior must correspond to
##' whatever you used to analyze your data in \code{BAMM}. By default,
##' time-variable and time-constant processes are assumed to have equal
##' prior odds.
##'
##' This function can be used several ways, but this function allows the
##' user to quickly evaluate which portions of a phylogenetic tree have
##' "significant" evidence for rate variation through time (see Examples
##' below).
##'
##' @return An object of class \code{phylo}, but where branch lengths are
##' replaced with the desired evidence (posterior probability or Bayes
##' factor) that each branch is governed by a time-varying rate dynamic.
##'
##' @author Dan Rabosky
##'
##' @seealso \code{\link{getRateThroughTimeMatrix}}
##'
##' @references \url{http://bamm-project.org/}
##'
##' @examples
##' # Load whale data:
##' data(whales, events.whales)
##' ed <- getEventData(whales, events.whales, burnin=0.1, nsamples=200)
##'
##' # compute the posterior probability of
##' # time-varying rates on each branch
##' tree.pp <- testTimeVariableBranches(ed)
##'
##' # Plot tree, but color all branches where the posterior
##' # probability of time-varying rates exceeds 95\%:
##'
##' colvec <- rep("black", nrow(whales$edge))
##' colvec[tree.pp$edge.length >= 0.95] <- 'red'
##'
##' plot.phylo(whales, edge.color=colvec, cex=0.5)
##'
##' # now, compute Bayes factors for each branch:
##'
##' tree.bf <- testTimeVariableBranches(ed, return.type = "bayesfactor")
##'
##' # now, assume that our prior was heavily stacked in favor
##' # of a time-constant process:
##' tree.bf2 <- testTimeVariableBranches(ed, prior_tv = 0.1,
##' return.type = "bayesfactor")
##'
##' # Plotting the branch-specific Bayes factors against each other:
##'
##' plot.new()
##' par(mar=c(5,5,1,1))
##' plot.window(xlim=c(0, 260), ylim=c(0, 260))
##' points(tree.bf2$edge.length, tree.bf$edge.length, pch=21, bg='red',
##' cex=1.5)
##' axis(1)
##' axis(2, las=1)
##' mtext(side=1, text="Bayes factor: prior_tv = 0.1", line=3, cex=1.5)
##' mtext(side = 2, text = "Bayes factor: uniform prior odds", line=3,
##' cex=1.5)
##'
##' # and you can see that if your prior favors CONSTANT RATE dynamics
##' # you will obtain much stronger Bayes factor support for time varying
##' # rates.
##' # IF the evidence is present in your data to support time variation.
##' # To be clear, the Bayes factors in this example were computed from the
##' # same posterior probabilities: it is only the prior odds that differed.
##' @export
testTimeVariableBranches <- function(ephy, prior_tv = 0.5, return.type = 'posterior'){
# return.type = bayesfactor or posterior
TOL <- .Machine$double.eps * 10;
esum <- numeric(nrow(ephy$edge));
em <- ephy$edge;
for (i in 1:length(ephy$eventBranchSegs)){
segmat <- ephy$eventBranchSegs[[i]];
rv <- ephy$eventData[[i]]$lam2[segmat[,4]];
rv <- as.numeric(abs(rv) > TOL);
for (k in 1:nrow(ephy$edge)){
esum[k] <- esum[k] + rv[which(segmat[,1] == em[k,2])[1]];
}
}
prob.rv <- esum / length(ephy$eventData);
bl <- prob.rv;
if (return.type == "bayesfactor"){
prob.null <- 1 - prob.rv;
bl <- (prob.rv / prob.null) * ((1 - prior_tv) / prior_tv);
}else if (return.type != "posterior"){
stop("Invalid return type\n");
}
newphy <- list(edge=ephy$edge, edge.length = bl, Nnode = ephy$Nnode, tip.label=ephy$tip.label);
class(newphy) <- 'phylo';
newphy;
}
| /scratch/gouwar.j/cran-all/cranData/BAMMtools/R/testTimeVariableBranches.R |
#############################################################
#
# timeIntegratedBranchRate(....)
# computes the integral of rates on a branch segment with respect to time
# Not the average.
#
#
timeIntegratedBranchRate <- function(t1, t2, p1, p2){
tol <- 0.00001;
res <- vector(mode = 'numeric', length = length(t1));
# constant rate
zero <- which(abs(p2) < tol);
p1s <- p1[zero];
t1s <- t1[zero];
t2s <- t2[zero];
res[zero] <- p1s * (t2s - t1s);
# declining rate
nonzero <- which(p2 < -tol);
p1s <- p1[nonzero];
p2s <- p2[nonzero];
t1s <- t1[nonzero];
t2s <- t2[nonzero];
res[nonzero] <- (p1s/p2s)*(exp(p2s*t2s) - exp(p2s*t1s));
# increasing rate
nonzero <- which(p2 > tol);
p1s <- p1[nonzero];
p2s <- p2[nonzero];
t1s <- t1[nonzero];
t2s <- t2[nonzero];
res[nonzero] <- (p1s/p2s)*(2*p2s*(t2s-t1s) + exp(-p2s*t2s) - exp(-p2s*t1s));
return(res);
}
| /scratch/gouwar.j/cran-all/cranData/BAMMtools/R/timeIntegratedBranchRate.R |
# Arguments:
# ephy: a bammdata object
# rate: either "speciation", "extinction" or "net diversification". default to "speciation".
# traits: a vector of trait data, with names corresponding to tips in the ephy object
# reps: number of permutations to do
# return.full: include the permutated and observed correlations in the retunred object?
# method: either spearman, pearson, mann-whitney, kruskal
# logrates: log-transform the rates before analysis? This can only matter for the pearson correlation
# two.tailed: perform a two tailed statistical test? (in which case it will double the p-value)
# traitorder: for one tail test, specify the direction of correlation ("positive" or "negative") for countinues trait or a string
# indicating states of binary trait with increasing speciation rate, separted by comma (e.g., 'A, B'). Currently, this function only
# perform two-tailed test for categorical data with more than two states.
# Returns:
# estimate: the mean observed correlation coefficient
# p.value: the probability that the observed correlation is less than or equal to
# a sample from the null distribution. If you are doing a one-tailed
# test on a continuous trait, a small pvalue means that your observed correlation is larger
# than the null distribution. P-values approaching 1 mean that the observed
# correlation is more negative than expected.
# gen: if return.full=TRUE, the vector of generations sampled from the bammdata objected for permutation
# obs.corr: if return.full=TRUE, a vector of observed correlation coefficients between traits and tip speciation rate for every sampled generation
# null: if return.full=TRUE, a vector of permuted correlation coefficients for everty sample generation
# ephy<-ed
# traits<-bitrait
# reps<-100
# return.full=T
# method="m"
# logrates=T
# two.tailed=T
# nthreads=6
# traitorder='0,1';
##' @title STRAPP: STructured Rate Permutations on Phylogenies
##'
##' @description Given a \code{bammdata} object and a vector of (continuous)
##' trait data, assess whether the correlation between the trait and bamm
##' estimated speciation, extinction or net diversification rate is
##' significant using permutation. A set of posterior samples is randomly
##' drawn from the \code{bammdata} object. If the trait is continuous,
##' this function calculates the correlation coefficients between the
##' trait and tip rates (observed correlation), as well as that with
##' permuted rates for each posterior sample. In a one-tailed test for
##' positive correlations, the reported p-value is the proportion of the
##' posterior samples in which the observed correlation is larger than the
##' correlations calculated with permuted rates. In a two-tailed test, the
##' reported p-value is the proportion of the posterior samples in which
##' the null correlation is as extreme as the correlation observed. If the
##' trait is binary, the U statistic of the Mann-Whitney test is
##' calculated instead of correlation coefficients to assess whether there
##' is a significant difference in rate between the two trait states. For
##' categorical traits with more than two states, the Kruskal-Wallis rank
##' sum statistic is used.
##'
##' @param ephy An object of class \code{bammdata}.
##' @param traits A vector of trait data, with names corresponding to tips in
##' the \code{bammdata} object. It can be numeric or categorical.
##' @param reps An integer specifying the number of permutations (i.e., the
##' number of posterior samples to randomly draw with replacement from the
##' \code{bammdata} object).
##' @param rate A character string specifying which estimated rate from the
##' \code{bammdata} object to use for testing correlation, must be one of
##' 'speciation', 'extinction', 'net diversification' or 'trait'. Defaults to
##' 'speciation'. You can specify just the initial letter. Ignored for
##' trait event data.
##' @param return.full A logical. If \code{TRUE}, the list of posterior
##' samples, the observed correlation for each posterior sample, and the
##' null distribution will be included in the returned object. Defaults to
##' \code{FALSE}.
##' @param method A character string, must be one of 'spearman', 'pearson',
##' 'mann-whitney', or 'kruskal'. Defaults to 'spearman'. You can specify
##' just the initial letter.
##' @param logrates A logical. If \code{TRUE} log-transform the rates before
##' analysis. Defaults to \code{TRUE}. This can only matter for the
##' pearson correlation.
##' @param two.tailed A logical, used for continuous trait data. If
##' \code{TRUE}, perform a two-tailed statistical test (i.e., if the null
##' distribution is symmetric, it is equivalent to doubling the p-value).
##' Defaults to \code{TRUE}.
##' @param traitorder A character string specifying the direction of
##' correlation for the alternative hypothesis. For continuous traits, it
##' must be either "positive" or "negative"; only the initial letter is
##' needed. For binary traits, it must be a string indicating states with
##' increasing rate under the alternative hypothesis, separated by comma
##' (e.g., 'A, B'). One-tailed test for categorical data with more than
##' two states is not supported.
##' @param nthreads Number of threads to use for parallelization of the
##' function. The R package \code{parallel} must be loaded for
##' \code{nthreads > 1}.
##'
##' @details Tip rates --trait, speciation, extinction, or net diversification
##' rates-- are permuted in a way such that pairwise covariances in rates
##' between species are maintained. That is, tips with the same
##' \code{tipStates} still have the same rate after permutation. Posterior
##' samples are randomly selected with replacement from the
##' \code{bammdata} object, so \code{reps} could be smaller or larger than
##' the total number of samples in the object.
##'
##' This function expects that the bamm-data object and the trait data
##' have the same taxon set. It may be necessary to subset the trait data
##' and/or run \code{\link{subtreeBAMM}} on the \code{bamm-data} object in
##' order to meet this requirement.
##'
##' @return A list with the following components:
##' \itemize{
##' \item estimate: A numeric value for continous trait data: the
##' average observed correlation between tip rates and the trait
##' across the posterior samples. For categorical traits, it is
##' a list showing the median species-specific rates for each
##' trait state.
##' \item p.value: A numeric value. The probability that the observed
##' correlation is less than or equal to a sample from the null
##' distribution.
##' \item method: A character string, as input.
##' \item rate: A character string, as input.
##' \item two.tailed: A logical, as input.
##' \item gen: An integer vector, recording which posterior samples
##' were selected. Only present when \code{return.full} is
##' \code{TRUE}.
##' \item obs.corr: A numeric vector, the observed correlation
##' coefficents for each posterior sample. Only present when
##' \code{return.full} is \code{TRUE}. For binary traits, centered
##' U statistics (U - n1* n2/2; where n1 and n2 are the number of
##' species in each state of the binary trait) is reported.
##' \item null: A numeric vector. The null distribution of
##' correlation coefficients (or centered U statistics for binary
##' traits) from permutation. Only present when \code{return.full}
##' is \code{TRUE}.
##' }
##'
##' @author Dan Rabosky, Huateng Huang
##'
##' @seealso \code{\link{subtreeBAMM}}
##'
##' @references \url{http://bamm-project.org/}
##'
##' Rabosky, D. L. and Huang, H., 2015. A Robust Semi-Parametric Test for
##' Detecting Trait-Dependent Diversification. Systematic Biology 65:
##' 181-193.
##'
##' Rabosky, D. L. 2014. Automatic detection of key innovations, rate
##' shifts, and diversity-dependence on phylogenetic trees. PLoS ONE
##' 9:e89543.
##'
##' Rabosky, D. L., F. Santini, J. T. Eastman, S. A. Smith, B. L.
##' Sidlauskas, J. Chang, and M. E. Alfaro. 2013. Rates of speciation and
##' morphological evolution are correlated across the largest vertebrate
##' radiation. Nature Communications DOI: 10.1038/ncomms2958.
##'
##' @examples
##' # using a small subset of the fish data set (300 taxa) in Rabosky et al.
##' # 2013. Nat. Com. paper
##' data(fishes, events.fishes)
##' xx <- getEventData(phy = fishes, eventdata = events.fishes,
##' nsamples = 500, type = "diversification")
##' # traits.fishes is the trait -- body size
##' data(traits.fishes)
##' x <- traitDependentBAMM(ephy = xx, traits = traits.fishes, reps = 1000,
##' return.full = TRUE, method = 's', logrates = TRUE,
##' two.tailed = TRUE)
##' @aliases strapp
##' @keywords nonparametric
##' @export
traitDependentBAMM <- function(ephy, traits, reps, rate = 'speciation', return.full = FALSE, method = 'spearman', logrates = TRUE, two.tailed = TRUE, traitorder = NA, nthreads = 1) {
if (nthreads > 1) {
if (!"package:parallel" %in% search()) {
stop("Please load package 'parallel' for using the multi-thread option\n");
}
}
if (ephy$type == 'trait') {
rate <- 'trait'
}
ratetype.option <- c("speciation", "extinction", "net diversification", "trait");
ratetype <- grep(paste0("^", rate), ratetype.option, value = TRUE, ignore.case = TRUE);
if (length(ratetype) == 0) {
stop("Rate must be one of 'speciation', 'extinction', or 'net diversification', only the initial letter is needed.\n")
}
if (ratetype == "net diversification" & logrates == TRUE) {
cat("WARNING: Net diversification might be negative and logged rates would then produce NaNs.\n");
}
if (ratetype == 'trait' & ephy$type == 'diversification') {
stop('Rate must be either speciation or net diversification if ephy is a diversification analysis.\n');
}
if (ratetype %in% c('speciation', 'net diversification') & ephy$type == 'trait') {
stop('Rate must be trait if ephy is a trait analysis.\n');
}
# check if species in ephy and traits match
if (!identical(sort(names(traits)), sort(ephy$tip.label))) {
stop('Species names in the bamm-data object and trait data are not identical. You may want to run subtreeBAMM and subset the trait data in order to reduce the two datasets to a common taxon set.')
}
method.option <- c("spearman", "pearson", "mann-whitney", "kruskal");
method <- grep(paste0("^", method), method.option, ignore.case = TRUE, value = TRUE);
if (length(method) == 0) {
stop("method must be one of 'spearman', 'pearson', 'mann-whitney', or 'kruskal', only the initial letter is needed");
}
# check if the trait is right class
if (method == 'spearman' | method == "pearson") {
if (! is.numeric(traits)){
cat(paste0("selected ", method, ", but the trait is not numeric, converted the trait into a numeric vector\n"));
traits <- as.numeric(traits);
}
} else if (method == "mann-whitney"| method == "kruskal") {
if (length(unique(traits[! is.na(traits)])) == 1) {
stop(paste("selected ", method, ", but the trait only has one level\n", sep = ''));
}
if (method == "mann-whitney") {
if (length(unique(traits[! is.na(traits)])) > 2) {
stop(paste("selected ", method, ", but the trait has more than two levels\n", sep = ''));
}
}
}
#check if the traitorder is specified
trait.state <- NA;
if (!two.tailed) {
if (anyNA(traitorder)) {
stop("selected one-tail test, but traitorder is not specified\n");
}
if ( method == "kruskal") {
stop(" currently one-tail test is only available for continous or binary trait");
}
if (method == 'spearman' | method == "pearson") {
direction.option <- c("positive", "negative");
direction <- grep(paste0("^", traitorder), direction.option, ignore.case = TRUE, value = TRUE);
if (length(direction) == 0) {
stop(" for one-tail test with continous trait, traitorder must be either 'positive' or 'negative', only the initial letter is needed");
} else {
cat(paste0("select one-tailed ", method, " test\nAlternative hypothesis: the trait is ", direction, "ly correlated with speciation rate\n"));
}
} else {
traitorder <- gsub(" ", "", traitorder);
trait.state <- as.character(unlist(strsplit(x = traitorder, split = ",")));
if (length(trait.state) != 2) {
stop("please specify the traitorder for binary trait:\nTwo states separated by comma, and the state that is expected to have lower speciation rate first\n");
} else {
cat(paste0("selected one-tail ", method, " test\nAlternative hypothesis: species with trait ", trait.state[2], " has higher speciation rate than those with trait ", trait.state[1], "\n"));
}
for (i in trait.state) {
if (sum(traits == i) == 0) {
stop(paste("no species with state ", i," \n", sep = ''));
}
}
}
}
if (ratetype == 'speciation') {
tiprates <- ephy$tipLambda;
} else if (ratetype == "extinction") {
tiprates <- ephy$tipMu;
} else if (ratetype == 'net diversification') {
tiprates <- lapply(1:length(ephy$tipLambda), function(i) ephy$tipLambda[[i]] - ephy$tipMu[[i]]);
} else if (ratetype == 'trait') {
tiprates <- ephy$tipLambda;
}
tipstates <- ephy$tipStates;
#tiprates <- tiprates[ephy$tip.label];
traits <- traits[ephy$tip.label];
stat.mu <- 0;
if (method == "mann-whitney") {
trait.stat.count <- table(traits);
trait.stat.count <- trait.stat.count[! is.na(names(trait.stat.count))];
stat.mu <- prod(trait.stat.count) / 2;
}
if (logrates) {
tiprates <- lapply(1:length(tiprates), function(x) log(tiprates[[x]]));
}
#randomly sample generations from BAMM posterior
gen <- sample(1:length(tiprates), size = reps, replace = TRUE);
gen.tiprates <- list();
for (l in 1:length(gen)) {
gen.tiprates[[l]] <- data.frame(rates = tiprates[[gen[l]]], states = tipstates[[gen[l]]], stringsAsFactors = FALSE);
}
rm("tiprates", "tipstates");
permute_tiprates <- function(m) {
tt <- m$states;
tlam <- m$rates;
index <- unique(tt);
lvec <- numeric(length(index));
for (k in 1:length(index)) {
lvec[k] <- tlam[tt == index[k]][1];
}
new_index <- sample(index, size = length(index), replace = FALSE);
x <- rep(0,length(tt));
for (xx in 1:length(index)) {
x[which(tt == index[xx])] <- lvec[which(index == new_index[xx])];
}
x;
}
if (nthreads > 1) {
cl <- parallel::makePSOCKcluster(nthreads);
p.gen.tiprates <- parallel::parLapply(cl, gen.tiprates, permute_tiprates);
parallel::stopCluster(cl);
} else {
p.gen.tiprates <- lapply(gen.tiprates, permute_tiprates);
}
xgen.tiprates <- list();
for (l in 1:length(gen)) {
xgen.tiprates[[l]] <- gen.tiprates[[l]]$rates;
}
gen.tiprates <- xgen.tiprates; rm("xgen.tiprates");
cortest <- function(rates, traits, method) {
if (sd(rates, na.rm = TRUE) == 0) {
return(0);
} else {
return(cor.test(rates, traits, method = method, exact = FALSE)$estimate);
}
}
manntest <- function(rates, traits, two.tailed, trait.state) {
if (two.tailed) {
return(wilcox.test(rates ~ traits, exact = FALSE)$statistic);
} else {
return(wilcox.test(rates[which(traits == trait.state[2])], rates[which(traits == trait.state[1])], exact = FALSE)$statistic);
}
}
kruskaltest <- function(rates, traits) {
testres <- kruskal.test(rates ~ traits);
# If there is no variation in rates (chi-squared value is NaN), then return a chi-squared value that has a P-value of 0.999, using the appropriate degrees of freedom
if (is.na(testres$statistic)) {
return(qchisq(p = 0.999, df = testres$parameter));
} else {
return(testres$statistic);
}
}
if (nthreads > 1) {
cl <- parallel::makePSOCKcluster(nthreads);
if (method == 'spearman' | method == "pearson") {
obs <- parallel::parLapply(cl, gen.tiprates,cortest, traits, method);
permu <- parallel::parLapply(cl, p.gen.tiprates, cortest, traits, method);
} else if (method == "mann-whitney") {
obs <- parallel::parLapply(cl, gen.tiprates, manntest, traits, two.tailed, trait.state);
permu <- parallel::parLapply(cl, p.gen.tiprates, manntest, traits, two.tailed, trait.state);
} else {
obs <- parallel::parLapply(cl, gen.tiprates, kruskaltest, traits);
permu <- parallel::parLapply(cl, p.gen.tiprates, kruskaltest, traits);
}
parallel::stopCluster(cl);
} else {
if (method == 'spearman' | method == "pearson") {
obs <- lapply(gen.tiprates, cortest, traits, method);
permu <- lapply(p.gen.tiprates, cortest, traits, method);
} else if (method == "mann-whitney") {
obs <- lapply(gen.tiprates, manntest, traits, two.tailed, trait.state);
permu <- lapply(p.gen.tiprates, manntest, traits, two.tailed, trait.state);
} else {
obs <- lapply(gen.tiprates, kruskaltest, traits);
permu <- lapply(p.gen.tiprates, kruskaltest, traits);
}
}
obs <- unlist(obs);
permu <- unlist(permu);
obs <- obs - stat.mu;
permu <- permu - stat.mu;
if (two.tailed) {
pval <- sum(abs(obs) <= abs(permu)) / length(permu);
} else {
if (method == "spearman" | method == "pearson") {
if (direction == 'positive') {
pval <- sum(obs <= permu) / length(permu);
} else {
pval <- sum(obs >= permu) / length(permu);
}
} else {
pval <- sum(obs <= permu) / length(permu);
}
}
if (method == "spearman" | method == "pearson") {
obj <- list(estimate = mean(as.numeric(obs)), p.value = pval, method = method, two.tailed = two.tailed);
} else {
if (ratetype == 'speciation') {
ave.tiprate <- getTipRates(ephy)$lambda.avg;
} else if (ratetype == 'extinction') {
ave.tiprate <- getTipRates(ephy)$mu.avg;
} else if (ratetype == 'net diversification') {
ave.tiprate <- getTipRates(ephy)$lambda.avg - getTipRates(ephy)$mu.avg;
} else if (ratetype == 'trait') {
ave.tiprate <- getTipRates(ephy)$beta.avg;
}
l <- lapply(unique(traits[!is.na(traits)]), function(x) {
median(ave.tiprate[which(traits == x)], na.rm = TRUE);
});
names(l) <- as.character(unique(traits[! is.na(traits)]));
obj <- list(estimate = l, p.value = pval, method = method, two.tailed = two.tailed);
}
obj$rate <- ratetype;
if (return.full) {
obj$obs.corr <- as.numeric(obs);
obj$gen <- gen;
obj$null <- as.numeric(permu);
}
return(obj);
}
| /scratch/gouwar.j/cran-all/cranData/BAMMtools/R/traitDependentBAMM.R |
#############################################################
#
# transparentColor <- function(...)
#
# Internal function allows for defining named colors with opacity
# alpha = opacity
#
##' @title Define colors with transparency
##'
##' @description Converts a named color and opacity and returns the proper RGB
##' code.
##'
##' @param namedColor A color name.
##' @param alpha A transparency value between 0 and 1, where 0 is fully
##' transparent.
##'
##' @details This function is used internally by
##' \code{\link{plotRateThroughTime}}.
##'
##' @return Returns the transparent color in RGB format.
##'
##' @author Pascal Title
##' @keywords manip
##' @export
transparentColor <- function(namedColor, alpha = 0.8) {
res <- col2rgb(namedColor) / 255;
return(rgb(red = res[1,], green = res[2,], blue = res[3,], alpha = alpha));
}
| /scratch/gouwar.j/cran-all/cranData/BAMMtools/R/transparentColor.R |
##' @title Write a \code{bammdata} object to disk
##'
##' @description Takes a \code{bammdata} object and re-writes it back into a
##' treefile and an event csv file.
##'
##' @param ephy A \code{bammdata} object.
##' @param outtreefile The file name for outputting the tree.
##' @param outeventfile The file name for outputting the event csv file.
##' @param \dots Additional arguments to pass to \code{write.csv}.
##'
##' @seealso \code{\link{subtreeBAMM}}
##' @export
writeEventData <- function(ephy, outtreefile, outeventfile, ...){
if(!inherits(ephy, "bammdata")) {
stop("Input has to be a bammdata object.\n");
}
tree <- as.phylo(ephy);
write.tree(tree, file = outtreefile);
#get all the nodes in the eventData
nodes <- c();
for (i in 1:length(ephy$eventData)) {
nodes <- c(nodes, ephy$eventData[[i]]$node);
}
nodes <- as.integer(unique(nodes));
lr_child <- sapply(nodes, function(x) {
l <- tree$edge[which(tree$edge[,1] == x), 2];
if (length(l) == 0) {
return(c(x, NA));
} else {
c(min(ephy$downseq[which(ephy$downseq == l[1]):which(ephy$downseq == ephy$lastvisit[l[1]])]), min(ephy$downseq[which(ephy$downseq == l[2]):which(ephy$downseq == ephy$lastvisit[l[2]])]));
}
})
tree_child <- data.frame(node = nodes, leftchild = tree$tip.label[lr_child[1,]], rightchild = tree$tip.label[lr_child[2,]], stringsAsFactors = FALSE);
eventdata <- data.frame(generation = integer(0), leftchild = character(0), rightchild = character(0), abstime = double(0), lambdainit = double(0), lambdashift = double(0), muinit=double(0), mushift = double(0), stringsAsFactors = FALSE);
for (i in 1:length(ephy$eventData)) {
t <- ephy$eventData[[i]];
eventdata <- rbind(eventdata, data.frame(generation = rep(i,dim(t)[1]),
leftchild = tree_child$leftchild[match(t$node,tree_child$node)],
rightchild = tree_child$rightchild[match(t$node,tree_child$node)],
abstime = t$time,
lambdainit = t$lam1,
lambdashift = t$lam2,
muinit = t$mu1,
mushift = t$mu2,
stringsAsFactors = FALSE
))
}
write.csv(eventdata, file = outeventfile, row.names = FALSE, quote = FALSE, ...);
}
| /scratch/gouwar.j/cran-all/cranData/BAMMtools/R/writeEventData.R |
BANOVA.Bernoulli <-
function(l1_formula = 'NA', l2_formula = 'NA', data, id, l2_hyper = c(1,1,0.0001), burnin = 5000, sample = 2000, thin = 10, adapt = 0, conv_speedup = F, jags = runjags.getOption('jagspath')){
# if (jags == 'JAGS not found') stop('Please install the JAGS software (Version 3.4 or above). Check http://mcmc-jags.sourceforge.net/')
sol <- BANOVA.BernNormal(l1_formula, l2_formula, data, id, l2_hyper = l2_hyper, burnin = burnin, sample = sample, thin = thin, adapt = adapt, conv_speedup = conv_speedup, jags = jags)
sol$call <- match.call()
class(sol) <- 'BANOVA.Bernoulli'
sol
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/BANOVA.Bern.R |
BANOVA.BernNormal <-
function(l1_formula = 'NA', l2_formula = 'NA', data, id, l2_hyper, burnin, sample, thin, adapt, conv_speedup, jags){
cat('Model initializing...\n')
if (l1_formula == 'NA'){
stop("Formula in level 1 is missing or not correct!")
}else{
mf1 <- model.frame(formula = l1_formula, data = data)
# check y, if it is integers
y <- model.response(mf1)
if (!inherits(y, 'integer')){
warning("The response variable must be integers (data class also must be 'integer')..")
y <- as.integer(as.character(y))
warning("The response variable has been converted to integers..")
}
}
if (l2_formula == 'NA'){
stop("The level 2 formula is not specified, please check BANOVA.run for single level models.")
# # check each column in the dataframe should have the class 'factor' or 'numeric', no other classes such as 'matrix'...
# for (i in 1:ncol(data)){
# if(class(data[,i]) != 'factor' && class(data[,i]) != 'numeric' && class(data[,i]) != 'integer') stop("data class must be 'factor', 'numeric' or 'integer'")
# # checking numerical predictors, converted to categorical variables if the number of levels is <= 3
# if ((class(data[,i]) == 'numeric' | class(data[,i]) == 'integer') & length(unique(data[,i])) <= 3){
# data[,i] <- as.factor(data[,i])
# warning("Variables(levels <= 3) have been converted to factors")
# }
# }
# n <- nrow(data)
# uni_id <- unique(id)
# num_id <- length(uni_id)
# new_id <- rep(0, length(id)) # store the new id from 1,2,3,...
# for (i in 1:length(id))
# new_id[i] <- which(uni_id == id[i])
# id <- new_id
# dMatrice <- design.matrix(l1_formula, l2_formula, data = data, id = id)
# JAGS.model <- JAGSgen.bernNormal(dMatrice$X, dMatrice$Z, l2_hyper, conv_speedup)
# JAGS.data <- dump.format(list(n = n, id = id, M = num_id, y = y, X = dMatrice$X, Z = dMatrice$Z))
# result <- run.jags (model = JAGS.model$sModel, data = JAGS.data, inits = JAGS.model$inits, n.chains = 1,
# monitor = c(JAGS.model$monitorl1.parameters, JAGS.model$monitorl2.parameters),
# burnin = burnin, sample = sample, thin = thin, adapt = adapt, jags = jags, summarise = FALSE,
# method="rjags")
# samples <- result$mcmc[[1]]
# # find the correct samples, in case the order of monitors is shuffled by JAGS
# n_p_l1 <- length(JAGS.model$monitorl1.parameters)
# index_l1_param<- array(0,dim = c(n_p_l1,1))
# for (i in 1:n_p_l1)
# index_l1_param[i] <- which(colnames(result$mcmc[[1]]) == JAGS.model$monitorl1.parameters[i])
# if (length(index_l1_param) > 1)
# samples_l1_param <- result$mcmc[[1]][,index_l1_param]
# else
# samples_l1_param <- matrix(result$mcmc[[1]][,index_l1_param], ncol = 1)
# colnames(samples_l1_param) <- colnames(result$mcmc[[1]])[index_l1_param]
#
# #anova.table <- table.ANOVA(samples_l1_param, dMatrice$X, dMatrice$Z)
# cat('Constructing ANOVA/ANCOVA tables...\n')
# # anova.table <- table.ANCOVA(samples_l1_param, dMatrice$X, dMatrice$Z, samples_l2_param) # for ancova models
# # coef.tables <- table.coefficients(samples_l2_param, JAGS.model$monitorl2.parameters, colnames(dMatrice$X), colnames(dMatrice$Z),
# # attr(dMatrice$X, 'assign') + 1, attr(dMatrice$Z, 'assign') + 1)
# # pvalue.table <- table.pvalue(coef.tables$coeff_table, coef.tables$row_indices, l1_names = attr(dMatrice$X, 'varNames'),
# # l2_names = attr(dMatrice$Z, 'varNames'))
# # conv <- conv.geweke.heidel(samples_l2_param, colnames(dMatrice$X), colnames(dMatrice$Z))
# # class(conv) <- 'conv.diag'
# # cat('Done...\n')
}else{
mf2 <- model.frame(formula = l2_formula, data = data)
# check each column in the dataframe should have the class 'factor' or 'numeric', no other classes such as 'matrix'...
for (i in 1:ncol(data)){
if(!inherits(data[,i], 'factor') && !inherits(data[,i], 'numeric') && !inherits(data[,i], 'integer')) stop("data class must be 'factor', 'numeric' or 'integer'")
#response_name <- attr(mf1,"names")[attr(attr(mf1, "terms"),"response")]
# checking missing predictors, already checked in design matrix
# if(i != which(colnames(data) == response_name) & sum(is.na(data[,i])) > 0) stop("Data type error, NAs/missing values included in independent variables")
#if(i != which(colnames(data) == response_name) & class(data[,i]) == 'numeric')
# data[,i] = data[,i] - mean(data[,i])
# checking numerical predictors, converted to categorical variables if the number of levels is <= 3
if ((inherits(data[,i], 'numeric') | inherits(data[,i], 'integer')) & length(unique(data[,i])) <= 3){
data[,i] <- as.factor(data[,i])
warning("Variables(levels <= 3) have been converted to factors")
}
}
n <- nrow(data)
uni_id <- unique(id)
num_id <- length(uni_id)
new_id <- rep(0, length(id)) # store the new id from 1,2,3,...
for (i in 1:length(id))
new_id[i] <- which(uni_id == id[i])
id <- new_id
dMatrice <- design.matrix(l1_formula, l2_formula, data = data, id = id)
JAGS.model <- JAGSgen.bernNormal(dMatrice$X, dMatrice$Z, l2_hyper, conv_speedup)
JAGS.data <- dump.format(list(n = n, id = id, M = num_id, y = y, X = dMatrice$X, Z = dMatrice$Z))
result <- run.jags (model = JAGS.model$sModel, data = JAGS.data, inits = JAGS.model$inits, n.chains = 1,
monitor = c(JAGS.model$monitorl1.parameters, JAGS.model$monitorl2.parameters),
burnin = burnin, sample = sample, thin = thin, adapt = adapt, jags = jags, summarise = FALSE,
method="rjags")
samples <- result$mcmc[[1]]
# find the correct samples, in case the order of monitors is shuffled by JAGS
n_p_l2 <- length(JAGS.model$monitorl2.parameters)
index_l2_param<- array(0,dim = c(n_p_l2,1))
for (i in 1:n_p_l2)
index_l2_param[i] <- which(colnames(result$mcmc[[1]]) == JAGS.model$monitorl2.parameters[i])
if (length(index_l2_param) > 1)
samples_l2_param <- result$mcmc[[1]][,index_l2_param]
else
samples_l2_param <- matrix(result$mcmc[[1]][,index_l2_param], ncol = 1)
colnames(samples_l2_param) <- colnames(result$mcmc[[1]])[index_l2_param]
n_p_l1 <- length(JAGS.model$monitorl1.parameters)
index_l1_param<- array(0,dim = c(n_p_l1,1))
for (i in 1:n_p_l1)
index_l1_param[i] <- which(colnames(result$mcmc[[1]]) == JAGS.model$monitorl1.parameters[i])
if (length(index_l1_param) > 1)
samples_l1_param <- result$mcmc[[1]][,index_l1_param]
else
samples_l1_param <- matrix(result$mcmc[[1]][,index_l1_param], ncol = 1)
colnames(samples_l1_param) <- colnames(result$mcmc[[1]])[index_l1_param]
#anova.table <- table.ANOVA(samples_l1_param, dMatrice$X, dMatrice$Z)
cat('Constructing ANOVA/ANCOVA tables...\n')
anova.table <- table.ANCOVA(samples_l1_param, dMatrice$X, dMatrice$Z, samples_l2_param) # for ancova models
coef.tables <- table.coefficients(samples_l2_param, JAGS.model$monitorl2.parameters, colnames(dMatrice$X), colnames(dMatrice$Z),
attr(dMatrice$X, 'assign') + 1, attr(dMatrice$Z, 'assign') + 1)
pvalue.table <- table.pvalue(coef.tables$coeff_table, coef.tables$row_indices, l1_names = attr(dMatrice$X, 'varNames'),
l2_names = attr(dMatrice$Z, 'varNames'))
conv <- conv.geweke.heidel(samples_l2_param, colnames(dMatrice$X), colnames(dMatrice$Z))
class(conv) <- 'conv.diag'
cat('Done...\n')
}
return(list(anova.table = anova.table,
coef.tables = coef.tables,
pvalue.table = pvalue.table,
conv = conv,
dMatrice = dMatrice, samples_l2_param = samples_l2_param, data = data, num_trials = 1,
mf1 = mf1, mf2 = mf2, JAGSmodel = JAGS.model$sModel, single_level = F, model_name = "BANOVA.Bernoulli"))
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/BANOVA.BernNormal.R |
BANOVA.Binomial <-
function(l1_formula = 'NA', l2_formula = 'NA', data, id, num_trials, l2_hyper = c(1,1,0.0001), burnin = 5000, sample = 2000, thin = 10, adapt = 0, conv_speedup = F, jags = runjags.getOption('jagspath')){
# if (jags == 'JAGS not found') stop('Please install the JAGS software (Version 3.4 or above). Check http://mcmc-jags.sourceforge.net/')
sol <- BANOVA.BinNormal(l1_formula, l2_formula, data, id, num_trials, l2_hyper = l2_hyper, burnin = burnin, sample = sample, thin = thin, adapt = adapt, conv_speedup = conv_speedup, jags = jags)
sol$call <- match.call()
class(sol) <- 'BANOVA.Binomial'
sol
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/BANOVA.Bin.R |
BANOVA.BinNormal <-
function(l1_formula = 'NA', l2_formula = 'NA', data, id, num_trials, l2_hyper, burnin, sample, thin, adapt, conv_speedup, jags){
cat('Model initializing...\n')
if (l1_formula == 'NA'){
stop("Formula in level 1 is missing or not correct!")
}else{
mf1 <- model.frame(formula = l1_formula, data = data)
# check y, if it is integers
y <- model.response(mf1)
if (!inherits(y, 'integer')){
warning("The response variable must be integers (data class also must be 'integer')..")
y <- as.integer(as.character(y))
warning("The response variable has been converted to integers..")
}
}
if (l2_formula == 'NA'){
stop("The level 2 formula is not specified, please check BANOVA.run for single level models.")
# if (class(num_trials) != 'integer') stop('The number of trials should be integers! Might use as.integer()')
# # check each column in the dataframe should have the class 'factor' or 'numeric', no other classes such as 'matrix'...
# for (i in 1:ncol(data)){
# if(class(data[,i]) != 'factor' && class(data[,i]) != 'numeric' && class(data[,i]) != 'integer') stop("data class must be 'factor', 'numeric' or 'integer'")
# # checking numerical predictors, converted to categorical variables if the number of levels is <= 3
# if ((class(data[,i]) == 'numeric' | class(data[,i]) == 'integer') & length(unique(data[,i])) <= 3){
# data[,i] <- as.factor(data[,i])
# warning("Variables(levels <= 3) have been converted to factors")
# }
# }
# n <- nrow(data)
# uni_id <- unique(id)
# num_id <- length(uni_id)
# new_id <- rep(0, length(id)) # store the new id from 1,2,3,...
# for (i in 1:length(id))
# new_id[i] <- which(uni_id == id[i])
# id <- new_id
# dMatrice <- design.matrix(l1_formula, l2_formula, data = data, id = id)
# N <- num_trials
# if (length(N) == 1) N <- rep(num_trials, n)
# if (length(N) != n) stop('The length of num_trials must be equal to the number of observations!')
# # handle missing values
# if (sum(y > num_trials, na.rm = T) > 0) stop('The number of trials is less than observations!')
# JAGS.model <- JAGSgen.binNormal(dMatrice$X, dMatrice$Z, l2_hyper, conv_speedup)
# JAGS.data <- dump.format(list(n = n, y = y, X = dMatrice$X, N = N))
# result <- run.jags (model = JAGS.model$sModel, data = JAGS.data, inits = JAGS.model$inits, n.chains = 1,
# monitor = c(JAGS.model$monitorl1.parameters, JAGS.model$monitorl2.parameters),
# burnin = burnin, sample = sample, thin = thin, adapt = adapt, jags = jags, summarise = FALSE,
# method="rjags")
# samples <- result$mcmc[[1]]
# # find the correct samples, in case the order of monitors is shuffled by JAGS
# n_p_l1 <- length(JAGS.model$monitorl1.parameters)
# index_l1_param<- array(0,dim = c(n_p_l1,1))
# for (i in 1:n_p_l1)
# index_l1_param[i] <- which(colnames(result$mcmc[[1]]) == JAGS.model$monitorl1.parameters[i])
# if (length(index_l1_param) > 1)
# samples_l1_param <- result$mcmc[[1]][,index_l1_param]
# else
# samples_l1_param <- matrix(result$mcmc[[1]][,index_l1_param], ncol = 1)
# colnames(samples_l1_param) <- colnames(result$mcmc[[1]])[index_l1_param]
}else{
mf2 <- model.frame(formula = l2_formula, data = data)
if (!inherits(num_trials, 'integer')) stop('The number of trials should be integers! Might use as.integer()')
# check each column in the dataframe should have the class 'factor' or 'numeric', no other classes such as 'matrix'...
for (i in 1:ncol(data)){
if(!inherits(data[,i], 'factor') && !inherits(data[,i], 'numeric') && !inherits(data[,i], 'integer')) stop("data class must be 'factor', 'numeric' or 'integer'")
#response_name <- attr(mf1,"names")[attr(attr(mf1, "terms"),"response")]
# checking missing predictors, already checked in design matrix
# if(i != which(colnames(data) == response_name) & sum(is.na(data[,i])) > 0) stop("Data type error, NAs/missing values included in independent variables")
#if(i != which(colnames(data) == response_name) & class(data[,i]) == 'numeric')
# data[,i] = data[,i] - mean(data[,i])
# checking numerical predictors, converted to categorical variables if the number of levels is <= 3
if ((inherits(data[,i], 'numeric') | inherits(data[,i], 'integer')) & length(unique(data[,i])) <= 3){
data[,i] <- as.factor(data[,i])
warning("Variables(levels <= 3) have been converted to factors")
}
}
n <- nrow(data)
uni_id <- unique(id)
num_id <- length(uni_id)
new_id <- rep(0, length(id)) # store the new id from 1,2,3,...
for (i in 1:length(id))
new_id[i] <- which(uni_id == id[i])
id <- new_id
dMatrice <- design.matrix(l1_formula, l2_formula, data = data, id = id)
N <- num_trials
if (length(N) == 1) N <- rep(num_trials, n)
if (length(N) != n) stop('The length of num_trials must be equal to the number of observations!')
# handle missing values
if (sum(y > num_trials, na.rm = T) > 0) stop('The number of trials is less than observations!')
JAGS.model <- JAGSgen.binNormal(dMatrice$X, dMatrice$Z, l2_hyper, conv_speedup)
JAGS.data <- dump.format(list(n = n, id = id, M = num_id, y = y, X = dMatrice$X, Z = dMatrice$Z, N = N))
result <- run.jags (model = JAGS.model$sModel, data = JAGS.data, inits = JAGS.model$inits, n.chains = 1,
monitor = c(JAGS.model$monitorl1.parameters, JAGS.model$monitorl2.parameters),
burnin = burnin, sample = sample, thin = thin, adapt = adapt, jags = jags, summarise = FALSE,
method="rjags")
samples <- result$mcmc[[1]]
# find the correct samples, in case the order of monitors is shuffled by JAGS
n_p_l2 <- length(JAGS.model$monitorl2.parameters)
index_l2_param<- array(0,dim = c(n_p_l2,1))
for (i in 1:n_p_l2)
index_l2_param[i] <- which(colnames(result$mcmc[[1]]) == JAGS.model$monitorl2.parameters[i])
if (length(index_l2_param) > 1)
samples_l2_param <- result$mcmc[[1]][,index_l2_param]
else
samples_l2_param <- matrix(result$mcmc[[1]][,index_l2_param], ncol = 1)
colnames(samples_l2_param) <- colnames(result$mcmc[[1]])[index_l2_param]
n_p_l1 <- length(JAGS.model$monitorl1.parameters)
index_l1_param<- array(0,dim = c(n_p_l1,1))
for (i in 1:n_p_l1)
index_l1_param[i] <- which(colnames(result$mcmc[[1]]) == JAGS.model$monitorl1.parameters[i])
if (length(index_l1_param) > 1)
samples_l1_param <- result$mcmc[[1]][,index_l1_param]
else
samples_l1_param <- matrix(result$mcmc[[1]][,index_l1_param], ncol = 1)
colnames(samples_l1_param) <- colnames(result$mcmc[[1]])[index_l1_param]
cat('Constructing ANOVA/ANCOVA tables...\n')
anova.table <- table.ANCOVA(samples_l1_param, dMatrice$X, dMatrice$Z, samples_l2_param) # for ancova models
coef.tables <- table.coefficients(samples_l2_param, JAGS.model$monitorl2.parameters, colnames(dMatrice$X), colnames(dMatrice$Z),
attr(dMatrice$X, 'assign') + 1, attr(dMatrice$Z, 'assign') + 1)
pvalue.table <- table.pvalue(coef.tables$coeff_table, coef.tables$row_indices, l1_names = attr(dMatrice$X, 'varNames'),
l2_names = attr(dMatrice$Z, 'varNames'))
conv <- conv.geweke.heidel(samples_l2_param, colnames(dMatrice$X), colnames(dMatrice$Z))
class(conv) <- 'conv.diag'
cat('Done...\n')
}
return(list(anova.table = anova.table,
coef.tables = coef.tables,
pvalue.table = pvalue.table,
conv = conv,
dMatrice = dMatrice, samples_l2_param = samples_l2_param, data = data, num_trials = num_trials,
mf1 = mf1, mf2 = mf2, JAGSmodel = JAGS.model$sModel, single_level = F, model_name = "BANOVA.Binomial"))
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/BANOVA.BinNormal.R |
BANOVA.MultiNormal <-
function(l1_formula = 'NA', l2_formula = 'NA', dataX, dataZ, y, id, l2_hyper, burnin, sample, thin, adapt, conv_speedup, jags){
cat('Model initializing...\n')
# TODO one level model
if (l2_formula == 'NA')
stop("The level 2 formula is not specified, please check BANOVA.run for single level models.")
# check y, if it is integers
if (!inherits(y, 'integer')){
warning("The response variable must be integers (data class also must be 'integer')..")
y <- as.integer(as.character(y))
warning("The response variable has been converted to integers..")
}
DV_sort <- sort(unique(y))
n_categories <- length(DV_sort)
if (n_categories < 2) stop('The number of categories must be greater than 1!')
if (DV_sort[1] != 1 || DV_sort[n_categories] != n_categories) stop('Check if response variable follows categorical distribution!')
# check each column in the dataframe should have the class 'factor' or 'numeric', no other classes such as 'matrix'...
for (i in 1:ncol(dataZ)){
if(!inherits(dataZ[,i], 'factor') && !inherits(dataZ[,i], 'numeric') && !inherits(dataZ[,i], 'integer')) stop("data class must be 'factor', 'numeric' or 'integer'")
# checking missing predictors, already checked in design matrix
# if(sum(is.na(dataZ[,i])) > 0) stop("Data type error, NAs/missing values included in independent variables")
#if(class(dataZ[,i]) == 'numeric')
# dataZ[,i] = dataZ[,i] - mean(dataZ[,i])
# checking numerical predictors, converted to categorical variables if the number of levels is <= 3
if (inherits(dataZ[,i], 'numeric') | inherits(dataZ[,i], 'integer') & length(unique(dataZ[,i])) <= 3){
dataZ[,i] <- as.factor(dataZ[,i])
warning("Between-subject variables(levels <= 3) have been converted to factors")
}
}
for (i in 1:length(dataX))
for (j in 1:ncol(dataX[[i]])){
if(!inherits(dataX[[i]][,j], 'factor') && !inherits(dataX[[i]][,j], 'numeric') && !inherits(dataX[[i]][,j], 'integer')) stop("data class must be 'factor', 'numeric' or 'integer'")
# checking missing predictors, already checked in design matrix
# if(sum(is.na(dataX[[i]][,j])) > 0) stop("Data type error, NAs/missing values included in independent variables")
#if(class(dataX[[i]][,j]) == 'numeric')
# dataX[[i]][,j] = dataX[[i]][,j] - mean(dataX[[i]][,j])
# checking numerical predictors, converted to categorical variables if the number of levels is <= 3
if ((inherits(dataX[[i]][,j], 'numeric') | inherits(dataX[[i]][,j], 'integer')) & length(unique(dataX[[i]][,j])) <= 3){
dataX[[i]][,j] <- as.factor(dataX[[i]][,j])
warning("Within-subject variables(levels <= 3) have been converted to factors")
}
}
n <- nrow(dataZ)
uni_id <- unique(id)
num_id <- length(uni_id)
new_id <- rep(0, length(id)) # store the new id from 1,2,3,...
for (i in 1:length(id))
new_id[i] <- which(uni_id == id[i])
id <- new_id
dMatrice <- multi.design.matrix(l1_formula, l2_formula, dataX = dataX, dataZ = dataZ, id = id)
# create 3-dimensional matrix of X for BUGS data
X_new <- array(0, dim = c(n, ncol(dMatrice$X_full[[1]]), n_categories))
for (i in 1:n_categories){
X_new[,,i] <- dMatrice$X_full[[i]]
}
JAGS.model <- JAGSgen.multiNormal(X_new, dMatrice$Z, l2_hyper, conv_speedup)
JAGS.data <- dump.format(list(n = n, id = id, M = num_id, y = y, X = X_new, Z = dMatrice$Z, n_choice = n_categories))
result <- run.jags (model = JAGS.model$sModel, data = JAGS.data, inits = JAGS.model$inits, n.chains = 1,
monitor = c(JAGS.model$monitorl1.parameters, JAGS.model$monitorl2.parameters, JAGS.model$monitor.cutp),
burnin = burnin, sample = sample, thin = thin, adapt = adapt, jags = jags, summarise = FALSE,
method="rjags")
samples <- result$mcmc[[1]]
# find the correct samples, in case the order of monitors is shuffled by JAGS
n_p_l2 <- length(JAGS.model$monitorl2.parameters)
index_l2_param<- array(0,dim = c(n_p_l2,1))
for (i in 1:n_p_l2)
index_l2_param[i] <- which(colnames(result$mcmc[[1]]) == JAGS.model$monitorl2.parameters[i])
if (length(index_l2_param) > 1)
samples_l2_param <- result$mcmc[[1]][,index_l2_param]
else
samples_l2_param <- matrix(result$mcmc[[1]][,index_l2_param], ncol = 1)
colnames(samples_l2_param) <- colnames(result$mcmc[[1]])[index_l2_param]
n_p_l1 <- length(JAGS.model$monitorl1.parameters)
index_l1_param<- array(0,dim = c(n_p_l1,1))
for (i in 1:n_p_l1)
index_l1_param[i] <- which(colnames(result$mcmc[[1]]) == JAGS.model$monitorl1.parameters[i])
if (length(index_l1_param) > 1)
samples_l1_param <- result$mcmc[[1]][,index_l1_param]
else
samples_l1_param <- matrix(result$mcmc[[1]][,index_l1_param], ncol = 1)
colnames(samples_l1_param) <- colnames(result$mcmc[[1]])[index_l1_param]
#anova.table <- table.ANOVA(samples_l1_param, dMatrice$X_full[[1]], dMatrice$Z) # only need the colnames of X
cat('Constructing ANOVA/ANCOVA tables...\n')
anova.table <- table.ANCOVA(samples_l1_param, dMatrice$X_full[[1]], dMatrice$Z, samples_l2_param) # for ancova models
coef.tables <- table.coefficients(samples_l2_param, JAGS.model$monitorl2.parameters, colnames(dMatrice$X_full[[1]]), colnames(dMatrice$Z),
attr(dMatrice$X_full[[1]], 'assign'), attr(dMatrice$Z, 'assign') + 1)
pvalue.table <- table.pvalue(coef.tables$coeff_table, coef.tables$row_indices, l1_names = attr(dMatrice$X_full[[1]], 'varNames'),
l2_names = attr(dMatrice$Z, 'varNames'))
conv <- conv.geweke.heidel(samples_l2_param, colnames(dMatrice$X_full[[1]]), colnames(dMatrice$Z))
class(conv) <- 'conv.diag'
mf1 <- model.frame(formula = l1_formula, data = dataX[[1]])
mf2 <- model.frame(formula = l2_formula, data = dataZ)
cat('Done...\n')
return(list(anova.table = anova.table,
coef.tables = coef.tables,
pvalue.table = pvalue.table,
conv = conv,
dMatrice = dMatrice, samples_l2_param = samples_l2_param, dataX = dataX, dataZ = dataZ,
mf1 = mf1, mf2 = mf2, n_categories = n_categories,JAGSmodel = JAGS.model$sModel, single_level = F, model_name = "BANOVA.Multinomial"))
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/BANOVA.MultiNormal.R |
BANOVA.Multinomial<-
function(l1_formula = 'NA', l2_formula = 'NA', dataX, dataZ, y, id, l2_hyper = c(1,1,0.0001), burnin = 5000, sample = 2000, thin = 10, adapt = 0, conv_speedup = F, jags = runjags.getOption('jagspath')){
# if (jags == 'JAGS not found') stop('Please install the JAGS software (Version 3.4 or above). Check http://mcmc-jags.sourceforge.net/')
sol <- BANOVA.MultiNormal(l1_formula, l2_formula, dataX, dataZ, y, id, l2_hyper = l2_hyper, burnin = burnin, sample = sample, thin = thin, adapt = adapt, conv_speedup = conv_speedup, jags = jags)
sol$call <- match.call()
class(sol) <- 'BANOVA.Multinomial'
sol
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/BANOVA.Multinomial.R |
BANOVA.Normal<-
function(l1_formula = 'NA', l2_formula = 'NA', data, id, l1_hyper = c(1,1), l2_hyper = c(1,1,0.0001), burnin = 5000, sample = 2000, thin = 10, adapt = 0, conv_speedup = F, jags = runjags.getOption('jagspath')){
# if (jags == 'JAGS not found') stop('Please install the JAGS software (Version 3.4 or above). Check http://mcmc-jags.sourceforge.net/')
sol <- BANOVA.NormalNormal(l1_formula, l2_formula, data, id, l1_hyper = l1_hyper, l2_hyper = l2_hyper, burnin = burnin, sample = sample, thin = thin, adapt = adapt, conv_speedup = conv_speedup, jags = jags)
sol$call <- match.call()
class(sol) <- 'BANOVA.Normal'
sol
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/BANOVA.Normal.R |
BANOVA.NormalNormal <-
function(l1_formula = 'NA',
l2_formula = 'NA',
data,
id,
l1_hyper,
l2_hyper,
burnin,
sample,
thin,
adapt,
conv_speedup,
jags){
cat('Model initializing...\n')
if (l1_formula == 'NA'){
stop("Formula in level 1 is missing or not correct!")
}else{
mf1 <- model.frame(formula = l1_formula, data = data)
}
single_level = F
if (l2_formula == 'NA'){
# one level models
single_level = T
# check y, if it is numeric
y <- model.response(mf1)
if (!inherits(y, 'numeric')){
warning("The response variable must be numeric (data class also must be 'numeric')")
y <- as.numeric(y)
warning("The response variable has been converted to numeric")
}
# check each column in the dataframe should have the class 'factor' or 'numeric', no other classes such as 'matrix'...
for (i in 1:ncol(data)){
if(!inherits(data[,i], 'factor') && !inherits(data[,i], 'numeric') && !inherits(data[,i], 'integer')) stop("data class must be 'factor', 'numeric' or 'integer'")
# checking numerical predictors, converted to categorical variables if the number of levels is <= 3
if ((inherits(data[,i], 'numeric') | inherits(data[,i], 'integer')) & length(unique(data[,i])) <= 3){
data[,i] <- as.factor(data[,i])
warning("Variables(levels <= 3) have been converted to factors")
}
}
n <- nrow(data)
uni_id <- unique(id)
num_id <- length(uni_id)
new_id <- rep(0, length(id)) # store the new id from 1,2,3,...
for (i in 1:length(id))
new_id[i] <- which(uni_id == id[i])
id <- new_id
dMatrice <- design.matrix(l1_formula, l2_formula, data = data, id = id)
JAGS.model <- JAGSgen.normalNormal(dMatrice$X, dMatrice$Z, l1_hyper, l2_hyper, conv_speedup)
JAGS.data <- dump.format(list(n = n, y = dMatrice$y, X = dMatrice$X))
result <- run.jags (model = JAGS.model$sModel, data = JAGS.data, inits = JAGS.model$inits, n.chains = 1,
monitor = c(JAGS.model$monitorl1.parameters, JAGS.model$monitorl2.parameters),
burnin = burnin, sample = sample, thin = thin, adapt = adapt, jags = jags, summarise = FALSE,
method="rjags")
samples <- result$mcmc[[1]]
# find the correct samples, in case the order of monitors is shuffled by JAGS
n_p_l1 <- length(JAGS.model$monitorl1.parameters)
index_l1_param<- array(0,dim = c(n_p_l1,1))
for (i in 1:n_p_l1)
index_l1_param[i] <- which(colnames(result$mcmc[[1]]) == JAGS.model$monitorl1.parameters[i])
if (length(index_l1_param) > 1)
samples_l1_param <- result$mcmc[[1]][,index_l1_param]
else
samples_l1_param <- matrix(result$mcmc[[1]][,index_l1_param], ncol = 1)
colnames(samples_l1_param) <- colnames(result$mcmc[[1]])[index_l1_param]
cat('Constructing ANOVA/ANCOVA tables...\n')
dMatrice$Z <- array(1, dim = c(1,1), dimnames = list(NULL, ' '))
attr(dMatrice$Z, 'assign') <- 0
attr(dMatrice$Z, 'varNames') <- " "
samples_l2_param <- NULL
anova.table <- table.ANCOVA(samples_l2_param, dMatrice$Z, dMatrice$X, samples_l1_param, array(y, dim = c(length(y), 1))) # for ancova models
coef.tables <- table.coefficients(samples_l1_param, JAGS.model$monitorl1.parameters, colnames(dMatrice$Z), colnames(dMatrice$X),
attr(dMatrice$Z, 'assign') + 1, attr(dMatrice$X, 'assign') + 1)
pvalue.table <- table.pvalue(coef.tables$coeff_table, coef.tables$row_indices, l1_names = attr(dMatrice$Z, 'varNames'),
l2_names = attr(dMatrice$X, 'varNames'))
conv <- conv.geweke.heidel(samples_l1_param, colnames(dMatrice$Z), colnames(dMatrice$X))
mf2 <- NULL
class(conv) <- 'conv.diag'
cat('Done.\n')
}else{
mf2 <- model.frame(formula = l2_formula, data = data)
# check y, if it is numeric
y <- model.response(mf1)
if (!inherits(y, 'numeric')){
warning("The response variable must be numeric (data class also must be 'numeric')")
y <- as.numeric(y)
warning("The response variable has been converted to numeric")
}
# check each column in the dataframe should have the class 'factor' or 'numeric', no other classes such as 'matrix'...
for (i in 1:ncol(data)){
if(!inherits(data[,i], 'factor') && !inherits(data[,i], 'numeric') && !inherits(data[,i], 'integer')) stop("data class must be 'factor', 'numeric' or 'integer'")
# checking numerical predictors, converted to categorical variables if the number of levels is <= 3
if ((inherits(data[,i], 'numeric') | !inherits(data[,i], 'integer')) & length(unique(data[,i])) <= 3){
data[,i] <- as.factor(data[,i])
warning("Variables(levels <= 3) have been converted to factors")
}
}
n <- nrow(data)
uni_id <- unique(id)
num_id <- length(uni_id)
new_id <- rep(0, length(id)) # store the new id from 1,2,3,...
for (i in 1:length(id))
new_id[i] <- which(uni_id == id[i])
id <- new_id
dMatrice <- design.matrix(l1_formula, l2_formula, data = data, id = id)
JAGS.model <- JAGSgen.normalNormal(dMatrice$X, dMatrice$Z, l1_hyper, l2_hyper, conv_speedup)
JAGS.data <- dump.format(list(n = n, id = id, M = num_id, y = dMatrice$y, X = dMatrice$X, Z = dMatrice$Z))
result <- run.jags (model = JAGS.model$sModel, data = JAGS.data, inits = JAGS.model$inits, n.chains = 1,
monitor = c(JAGS.model$monitorl1.parameters, JAGS.model$monitorl2.parameters),
burnin = burnin, sample = sample, thin = thin, adapt = adapt, jags = jags, summarise = FALSE,
method="rjags")
samples <- result$mcmc[[1]]
# find the correct samples, in case the order of monitors is shuffled by JAGS
n_p_l2 <- length(JAGS.model$monitorl2.parameters)
index_l2_param<- array(0,dim = c(n_p_l2,1))
for (i in 1:n_p_l2)
index_l2_param[i] <- which(colnames(result$mcmc[[1]]) == JAGS.model$monitorl2.parameters[i])
if (length(index_l2_param) > 1)
samples_l2_param <- result$mcmc[[1]][,index_l2_param]
else
samples_l2_param <- matrix(result$mcmc[[1]][,index_l2_param], ncol = 1)
colnames(samples_l2_param) <- colnames(result$mcmc[[1]])[index_l2_param]
n_p_l1 <- length(JAGS.model$monitorl1.parameters)
index_l1_param<- array(0,dim = c(n_p_l1,1))
for (i in 1:n_p_l1)
index_l1_param[i] <- which(colnames(result$mcmc[[1]]) == JAGS.model$monitorl1.parameters[i])
if (length(index_l1_param) > 1)
samples_l1_param <- result$mcmc[[1]][,index_l1_param]
else
samples_l1_param <- matrix(result$mcmc[[1]][,index_l1_param], ncol = 1)
colnames(samples_l1_param) <- colnames(result$mcmc[[1]])[index_l1_param]
cat('Constructing ANOVA/ANCOVA tables...\n')
anova.table <- table.ANCOVA(samples_l1_param, dMatrice$X, dMatrice$Z, samples_l2_param) # for ancova models
coef.tables <- table.coefficients(samples_l2_param, JAGS.model$monitorl2.parameters, colnames(dMatrice$X), colnames(dMatrice$Z),
attr(dMatrice$X, 'assign') + 1, attr(dMatrice$Z, 'assign') + 1)
pvalue.table <- table.pvalue(coef.tables$coeff_table, coef.tables$row_indices, l1_names = attr(dMatrice$X, 'varNames'),
l2_names = attr(dMatrice$Z, 'varNames'))
conv <- conv.geweke.heidel(samples_l2_param, colnames(dMatrice$X), colnames(dMatrice$Z))
class(conv) <- 'conv.diag'
cat('Done...\n')
}
return(list(anova.table = anova.table,
coef.tables = coef.tables,
pvalue.table = pvalue.table,
conv = conv,
dMatrice = dMatrice, samples_l1_param = samples_l1_param, samples_l2_param = samples_l2_param, data = data,
mf1 = mf1, mf2 = mf2, JAGSmodel = JAGS.model$sModel, single_level = single_level, model_name = "BANOVA.Normal"))
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/BANOVA.NormalNormal.R |
BANOVA.PNormal <-
function(l1_formula = 'NA', l2_formula = 'NA', data, id, l2_hyper, burnin, sample, thin, adapt, conv_speedup, jags){
cat('Model initializing...\n')
if (l1_formula == 'NA'){
stop("Formula in level 1 is missing or not correct!")
}else{
mf1 <- model.frame(formula = l1_formula, data = data)
# check y, if it is integers
y <- model.response(mf1)
if (!inherits(y, 'integer')){
warning("The response variable must be integers (data class also must be 'integer')..")
y <- as.integer(as.character(y))
warning("The response variable has been converted to integers..")
}
}
single_level = F
if (l2_formula == 'NA'){
single_level = T
# check each column in the dataframe should have the class 'factor' or 'numeric', no other classes such as 'matrix'...
for (i in 1:ncol(data)){
if(!inherits(data[,i], 'factor') && !inherits(data[,i], 'numeric') && !inherits(data[,i], 'integer')) stop("data class must be 'factor', 'numeric' or 'integer'")
# checking numerical predictors, converted to categorical variables if the number of levels is <= 3
if ((inherits(data[,i], 'numeric') | inherits(data[,i], 'integer')) & length(unique(data[,i])) <= 3){
data[,i] <- as.factor(data[,i])
warning("Variables(levels <= 3) have been converted to factors")
}
}
n <- nrow(data)
uni_id <- unique(id)
num_id <- length(uni_id)
new_id <- rep(0, length(id)) # store the new id from 1,2,3,...
for (i in 1:length(id))
new_id[i] <- which(uni_id == id[i])
id <- new_id
dMatrice <- design.matrix(l1_formula, l2_formula, data = data, id = id)
JAGS.model <- JAGSgen.PNormal(dMatrice$X, dMatrice$Z, l2_hyper, conv_speedup)
JAGS.data <- dump.format(list(n = n, y = y, X = dMatrice$X))
result <- run.jags (model = JAGS.model$sModel, data = JAGS.data, inits = JAGS.model$inits, n.chains = 1,
monitor = c(JAGS.model$monitorl1.parameters, JAGS.model$monitorl2.parameters, JAGS.model$monitorl2.sigma.parameters),
burnin = burnin, sample = sample, thin = thin, adapt = adapt, jags = jags, summarise = FALSE,
method="rjags")
samples <- result$mcmc[[1]]
# find the correct samples, in case the order of monitors is shuffled by JAGS
n_p_l1 <- length(JAGS.model$monitorl1.parameters)
index_l1_param<- array(0,dim = c(n_p_l1,1))
for (i in 1:n_p_l1)
index_l1_param[i] <- which(colnames(result$mcmc[[1]]) == JAGS.model$monitorl1.parameters[i])
if (length(index_l1_param) > 1)
samples_l1_param <- result$mcmc[[1]][,index_l1_param]
else
samples_l1_param <- matrix(result$mcmc[[1]][,index_l1_param], ncol = 1)
colnames(samples_l1_param) <- colnames(result$mcmc[[1]])[index_l1_param]
cat('Constructing ANOVA/ANCOVA tables...\n')
dMatrice$Z <- array(1, dim = c(1,1), dimnames = list(NULL, ' '))
attr(dMatrice$Z, 'assign') <- 0
attr(dMatrice$Z, 'varNames') <- " "
samples_l2_param <- NULL
samples_l2_sigma_param = 0
anova.table <- NULL # for ancova models
coef.tables <- table.coefficients(samples_l1_param, JAGS.model$monitorl1.parameters, colnames(dMatrice$Z), colnames(dMatrice$X),
attr(dMatrice$Z, 'assign') + 1, attr(dMatrice$X, 'assign') + 1)
pvalue.table <- table.pvalue(coef.tables$coeff_table, coef.tables$row_indices, l1_names = attr(dMatrice$Z, 'varNames'),
l2_names = attr(dMatrice$X, 'varNames'))
conv <- conv.geweke.heidel(samples_l1_param, colnames(dMatrice$Z), colnames(dMatrice$X))
mf2 <- NULL
class(conv) <- 'conv.diag'
cat('Done.\n')
}else{
mf2 <- model.frame(formula = l2_formula, data = data)
# check each column in the dataframe should have the class 'factor' or 'numeric', no other classes such as 'matrix'...
for (i in 1:ncol(data)){
if(!inherits(data[,i], 'factor') && !inherits(data[,i], 'numeric') && !inherits(data[,i], 'integer')) stop("data class must be 'factor', 'numeric' or 'integer'")
# checking numerical predictors, converted to categorical variables if the number of levels is <= 3
if ((inherits(data[,i], 'numeric') | inherits(data[,i], 'integer')) & length(unique(data[,i])) <= 3){
data[,i] <- as.factor(data[,i])
warning("Variables(levels <= 3) have been converted to factors")
}
}
n <- nrow(data)
uni_id <- unique(id)
num_id <- length(uni_id)
new_id <- rep(0, length(id)) # store the new id from 1,2,3,...
for (i in 1:length(id))
new_id[i] <- which(uni_id == id[i])
id <- new_id
dMatrice <- design.matrix(l1_formula, l2_formula, data = data, id = id)
JAGS.model <- JAGSgen.PNormal(dMatrice$X, dMatrice$Z, l2_hyper, conv_speedup)
JAGS.data <- dump.format(list(n = n, id = id, M = num_id, y = y, X = dMatrice$X, Z = dMatrice$Z))
result <- run.jags (model = JAGS.model$sModel, data = JAGS.data, inits = JAGS.model$inits, n.chains = 1,
monitor = c(JAGS.model$monitorl1.parameters, JAGS.model$monitorl2.parameters, JAGS.model$monitorl2.sigma.parameters),
burnin = burnin, sample = sample, thin = thin, adapt = adapt, jags = jags, summarise = FALSE,
method="rjags")
samples <- result$mcmc[[1]]
# find the correct samples, in case the order of monitors is shuffled by JAGS
n_p_l2 <- length(JAGS.model$monitorl2.parameters)
index_l2_param<- array(0,dim = c(n_p_l2,1))
for (i in 1:n_p_l2)
index_l2_param[i] <- which(colnames(result$mcmc[[1]]) == JAGS.model$monitorl2.parameters[i])
if (length(index_l2_param) > 1)
samples_l2_param <- result$mcmc[[1]][,index_l2_param]
else
samples_l2_param <- matrix(result$mcmc[[1]][,index_l2_param], ncol = 1)
colnames(samples_l2_param) <- colnames(result$mcmc[[1]])[index_l2_param]
n_p_l1 <- length(JAGS.model$monitorl1.parameters)
index_l1_param<- array(0,dim = c(n_p_l1,1))
for (i in 1:n_p_l1)
index_l1_param[i] <- which(colnames(result$mcmc[[1]]) == JAGS.model$monitorl1.parameters[i])
if (length(index_l1_param) > 1)
samples_l1_param <- result$mcmc[[1]][,index_l1_param]
else
samples_l1_param <- matrix(result$mcmc[[1]][,index_l1_param], ncol = 1)
colnames(samples_l1_param) <- colnames(result$mcmc[[1]])[index_l1_param]
# for table of means
n_p_l2_sigma <- length(JAGS.model$monitorl2.sigma.parameters)
index_l2_sigma_param<- array(0,dim = c(n_p_l2_sigma,1))
for (i in 1:n_p_l2_sigma)
index_l2_sigma_param[i] <- which(colnames(result$mcmc[[1]]) == JAGS.model$monitorl2.sigma.parameters[i])
if (length(index_l2_sigma_param) > 1)
samples_l2_sigma_param <- result$mcmc[[1]][,index_l2_sigma_param]
else
samples_l2_sigma_param <- matrix(result$mcmc[[1]][,index_l2_sigma_param], ncol = 1)
colnames(samples_l2_sigma_param) <- colnames(result$mcmc[[1]])[index_l2_sigma_param]
cat('Constructing ANOVA/ANCOVA tables...\n')
anova.table <- table.ANCOVA(samples_l1_param, dMatrice$X, dMatrice$Z, samples_l2_param) # for ancova models
coef.tables <- table.coefficients(samples_l2_param, JAGS.model$monitorl2.parameters, colnames(dMatrice$X), colnames(dMatrice$Z),
attr(dMatrice$X, 'assign') + 1, attr(dMatrice$Z, 'assign') + 1)
pvalue.table <- table.pvalue(coef.tables$coeff_table, coef.tables$row_indices, l1_names = attr(dMatrice$X, 'varNames'),
l2_names = attr(dMatrice$Z, 'varNames'))
conv <- conv.geweke.heidel(samples_l2_param, colnames(dMatrice$X), colnames(dMatrice$Z))
class(conv) <- 'conv.diag'
cat('Done...\n')
}
return(list(anova.table = anova.table,
coef.tables = coef.tables,
pvalue.table = pvalue.table,
conv = conv,
dMatrice = dMatrice,
samples_l1_param = samples_l1_param,
samples_l2_param = samples_l2_param,
samples_l2_sigma_param = samples_l2_sigma_param,
data = data, mf1 = mf1, mf2 = mf2, JAGSmodel = JAGS.model$sModel, single_level = single_level, model_name = "BANOVA.Poisson"))
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/BANOVA.PNormal.R |
BANOVA.Poisson <-
function(l1_formula = 'NA', l2_formula = 'NA', data, id, l2_hyper = c(1,1,0.0001), burnin = 5000, sample = 2000, thin = 10, adapt = 0, conv_speedup = F, jags = runjags.getOption('jagspath')){
# if (jags == 'JAGS not found') stop('Please install the JAGS software (Version 3.4 or above). Check http://mcmc-jags.sourceforge.net/')
sol <- BANOVA.PNormal(l1_formula, l2_formula, data, id, l2_hyper = l2_hyper, burnin = burnin, sample = sample, thin = thin, adapt = adapt, conv_speedup = conv_speedup, jags = jags)
sol$call <- match.call()
class(sol) <- 'BANOVA.Poisson'
sol
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/BANOVA.Poisson.R |
BANOVA.T <-
function(l1_formula = 'NA', l2_formula = 'NA', data, id, l1_hyper = c(1, 1, 1),l2_hyper = c(1,1,0.0001), burnin = 5000, sample = 2000, thin = 10, adapt = 0, conv_speedup = F, jags = runjags.getOption('jagspath')){
# if (jags == 'JAGS not found') stop('Please install the JAGS software (Version 3.4 or above). Check http://mcmc-jags.sourceforge.net/')
sol <- BANOVA.TNormal(l1_formula, l2_formula, data, id, l1_hyper = l1_hyper, l2_hyper = l2_hyper, burnin = burnin, sample = sample, thin = thin, adapt = adapt, conv_speedup = conv_speedup, jags = jags)
sol$call <- match.call()
class(sol) <- 'BANOVA.T'
sol
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/BANOVA.T.R |
BANOVA.TNormal <-
function(l1_formula = 'NA', l2_formula = 'NA', data, id, l1_hyper, l2_hyper, burnin, sample, thin, adapt, conv_speedup, jags){
cat('Model initializing...\n')
if (l1_formula == 'NA'){
stop("Formula in level 1 is missing or not correct!")
}else{
mf1 <- model.frame(formula = l1_formula, data = data)
# check y, if it is numeric
y <- model.response(mf1)
if (!inherits(y, 'numeric')){
warning("The response variable must be numeric (data class also must be 'numeric')..")
y <- as.numeric(y)
warning("The response variable has been converted to numeric..")
}
}
single_level = F
if (l2_formula == 'NA'){
# one level models
single_level = T
# check each column in the dataframe should have the class 'factor' or 'numeric', no other classes such as 'matrix'...
for (i in 1:ncol(data)){
if(!inherits(data[,i], 'factor') && !inherits(data[,i], 'numeric') && !inherits(data[,i], 'integer')) stop("data class must be 'factor', 'numeric' or 'integer'")
# checking numerical predictors, converted to categorical variables if the number of levels is <= 3
if ((inherits(data[,i], 'numeric') | inherits(data[,i], 'integer')) & length(unique(data[,i])) <= 3){
data[,i] <- as.factor(data[,i])
warning("Variables(levels <= 3) have been converted to factors")
}
}
n <- nrow(data)
uni_id <- unique(id)
num_id <- length(uni_id)
new_id <- rep(0, length(id)) # store the new id from 1,2,3,...
for (i in 1:length(id))
new_id[i] <- which(uni_id == id[i])
id <- new_id
dMatrice <- design.matrix(l1_formula, l2_formula, data = data, id = id)
JAGS.model <- JAGSgen.TNormal(dMatrice$X, dMatrice$Z, l1_hyper, l2_hyper, conv_speedup)
JAGS.data <- dump.format(list(n = n, y = dMatrice$y, X = dMatrice$X))
result <- run.jags (model = JAGS.model$sModel, data = JAGS.data, inits = JAGS.model$inits, n.chains = 1,
monitor = c(JAGS.model$monitorl1.parameters, JAGS.model$monitorl2.parameters),
burnin = burnin, sample = sample, thin = thin, adapt = adapt, jags = jags, summarise = FALSE,
method="rjags")
samples <- result$mcmc[[1]]
# find the correct samples, in case the order of monitors is shuffled by JAGS.
n_p_l1 <- length(JAGS.model$monitorl1.parameters)
index_l1_param<- array(0,dim = c(n_p_l1,1))
for (i in 1:n_p_l1)
index_l1_param[i] <- which(colnames(result$mcmc[[1]]) == JAGS.model$monitorl1.parameters[i])
if (length(index_l1_param) > 1)
samples_l1_param <- result$mcmc[[1]][,index_l1_param]
else
samples_l1_param <- matrix(result$mcmc[[1]][,index_l1_param], ncol = 1)
colnames(samples_l1_param) <- colnames(result$mcmc[[1]])[index_l1_param]
cat('Constructing ANOVA/ANCOVA tables...\n')
dMatrice$Z <- array(1, dim = c(1,1), dimnames = list(NULL, ' '))
attr(dMatrice$Z, 'assign') <- 0
attr(dMatrice$Z, 'varNames') <- " "
samples_l2_param <- NULL
anova.table <- table.ANCOVA(samples_l2_param, dMatrice$Z, dMatrice$X, samples_l1_param, array(y, dim = c(length(y), 1))) # for ancova models
coef.tables <- table.coefficients(samples_l1_param, JAGS.model$monitorl1.parameters, colnames(dMatrice$Z), colnames(dMatrice$X),
attr(dMatrice$Z, 'assign') + 1, attr(dMatrice$X, 'assign') + 1)
pvalue.table <- table.pvalue(coef.tables$coeff_table, coef.tables$row_indices, l1_names = attr(dMatrice$Z, 'varNames'),
l2_names = attr(dMatrice$X, 'varNames'))
conv <- conv.geweke.heidel(samples_l1_param, colnames(dMatrice$Z), colnames(dMatrice$X))
mf2 <- NULL
class(conv) <- 'conv.diag'
cat('Done...\n')
}else{
mf2 <- model.frame(formula = l2_formula, data = data)
# check each column in the dataframe should have the class 'factor' or 'numeric', no other classes such as 'matrix'...
for (i in 1:ncol(data)){
if(!inherits(data[,i], 'factor') && !inherits(data[,i], 'numeric') && !inherits(data[,i], 'integer')) stop("data class must be 'factor', 'numeric' or 'integer'")
# response_name <- attr(mf1,"names")[attr(attr(mf1, "terms"),"response")]
# checking missing predictors, already checked in design matrix
# if(i != which(colnames(data) == response_name) & sum(is.na(data[,i])) > 0) stop("Data type error, NAs/missing values included in independent variables")
#if(i != which(colnames(data) == response_name) & class(data[,i]) == 'numeric')
# data[,i] = data[,i] - mean(data[,i])
# checking numerical predictors, converted to categorical variables if the number of levels is <= 3
if ((inherits(data[,i], 'numeric') | inherits(data[,i], 'integer')) & length(unique(data[,i])) <= 3){
data[,i] <- as.factor(data[,i])
warning("Variables(levels <= 3) have been converted to factors")
}
}
n <- nrow(data)
uni_id <- unique(id)
num_id <- length(uni_id)
new_id <- rep(0, length(id)) # store the new id from 1,2,3,...
for (i in 1:length(id))
new_id[i] <- which(uni_id == id[i])
id <- new_id
dMatrice <- design.matrix(l1_formula, l2_formula, data = data, id = id)
JAGS.model <- JAGSgen.TNormal(dMatrice$X, dMatrice$Z, l1_hyper, l2_hyper, conv_speedup)
JAGS.data <- dump.format(list(n = n, id = id, M = num_id, y = dMatrice$y, X = dMatrice$X, Z = dMatrice$Z))
result <- run.jags (model = JAGS.model$sModel, data = JAGS.data, inits = JAGS.model$inits, n.chains = 1,
monitor = c(JAGS.model$monitorl1.parameters, JAGS.model$monitorl2.parameters),
burnin = burnin, sample = sample, thin = thin, adapt = adapt, jags = jags, summarise = FALSE,
method="rjags")
samples <- result$mcmc[[1]]
# find the correct samples, in case the order of monitors is shuffled by JAGS
n_p_l2 <- length(JAGS.model$monitorl2.parameters)
index_l2_param<- array(0,dim = c(n_p_l2,1))
for (i in 1:n_p_l2)
index_l2_param[i] <- which(colnames(result$mcmc[[1]]) == JAGS.model$monitorl2.parameters[i])
if (length(index_l2_param) > 1)
samples_l2_param <- result$mcmc[[1]][,index_l2_param]
else
samples_l2_param <- matrix(result$mcmc[[1]][,index_l2_param], ncol = 1)
colnames(samples_l2_param) <- colnames(result$mcmc[[1]])[index_l2_param]
n_p_l1 <- length(JAGS.model$monitorl1.parameters)
index_l1_param<- array(0,dim = c(n_p_l1,1))
for (i in 1:n_p_l1)
index_l1_param[i] <- which(colnames(result$mcmc[[1]]) == JAGS.model$monitorl1.parameters[i])
if (length(index_l1_param) > 1)
samples_l1_param <- result$mcmc[[1]][,index_l1_param]
else
samples_l1_param <- matrix(result$mcmc[[1]][,index_l1_param], ncol = 1)
colnames(samples_l1_param) <- colnames(result$mcmc[[1]])[index_l1_param]
#anova.table <- table.ANOVA(samples_l1_param, dMatrice$X, dMatrice$Z)
cat('Constructing ANOVA/ANCOVA tables...\n')
anova.table <- table.ANCOVA(samples_l1_param, dMatrice$X, dMatrice$Z, samples_l2_param) # for ancova models
coef.tables <- table.coefficients(samples_l2_param, JAGS.model$monitorl2.parameters, colnames(dMatrice$X), colnames(dMatrice$Z),
attr(dMatrice$X, 'assign') + 1, attr(dMatrice$Z, 'assign') + 1)
pvalue.table <- table.pvalue(coef.tables$coeff_table, coef.tables$row_indices, l1_names = attr(dMatrice$X, 'varNames'),
l2_names = attr(dMatrice$Z, 'varNames'))
conv <- conv.geweke.heidel(samples_l2_param, colnames(dMatrice$X), colnames(dMatrice$Z))
class(conv) <- 'conv.diag'
cat('Done...\n')
}
return(list(anova.table = anova.table,
coef.tables = coef.tables,
pvalue.table = pvalue.table,
conv = conv,
dMatrice = dMatrice, samples_l1_param = samples_l1_param,
samples_l2_param = samples_l2_param, data = data, mf1 = mf1, mf2 = mf2,
JAGSmodel = JAGS.model$sModel, single_level = single_level, model_name = "BANOVA.T"))
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/BANOVA.TNormal.R |
#' build BANOVA models
#' @param model_code BANOVA models in stan format
#'
#' @return A BANOVA stan model.
#'
#' @examples
#' \dontrun{
#'
#' }
#'
BANOVA.build <- function(BANOVA_model){
if(!is(BANOVA_model, 'BANOVA.model')) stop('BANOVA_model must be a BANOVA.model object, use the BANOVA.model function to create a model first!')
cat('Compiling...\n')
stan_c <- stanc(model_code = BANOVA_model$model_code, model_name = BANOVA_model$model_name)
utils::capture.output(stanmodel <- rstan::stan_model(stanc_ret = stan_c,save_dso = T), type = "output")
cat('Compiled successfully\n')
sol <- list(stanmodel = stanmodel, model_name = BANOVA_model$model_name, single_level = BANOVA_model$single_level)
class(sol) <- 'BANOVA.build'
return(sol)
} | /scratch/gouwar.j/cran-all/cranData/BANOVA/R/BANOVA.build.R |
BANOVA.floodlight <-
function(sol, var_numeric, var_factor, flood_values = list()){
if(class(sol) %in% c('BANOVA', 'BANOVA.Normal', 'BANOVA.T', 'BANOVA.Poisson', 'BANOVA.Bern',
'BANOVA.Bin', 'BANOVA.ordMultinomial', 'BANOVA.Multinomial', 'BANOVA.truncNormal')){
if (sol$single_level){
if (sol$model_name == 'BANOVA.Multinomial'){
sol_tables <- floodlight.analysis(sol,
var_numeric,
var_factor,
sol$samples_l1_param,
sol$dMatrice$X_full[[1]],
sol$dMatrice$Z,
dataX= sol$dataX,
dataZ = sol$dataZ,
flood_values = flood_values)
} else if(sol$model_name == 'BANOVA.multiNormal') {
sol_tables <- list()
for (i in 1:sol$num_depenent_variables){
name <- sol$names_of_dependent_variables[i]
title <- paste0("\nFloodlight analysis for ", name,"\n")
sol_tables[[name]] <- floodlight.analysis(sol,
var_numeric,
var_factor,
sol$samples_l1.list[[i]],
sol$dMatrice$X,
sol$dMatrice$Z,
data = sol$data,
flood_values = flood_values)
}
} else{
sol_tables <- floodlight.analysis(sol,
var_numeric,
var_factor,
sol$samples_l1_param,
sol$dMatrice$X,
sol$dMatrice$Z,
data = sol$data,
flood_values = flood_values)
}
}else{
if (sol$model_name == 'BANOVA.Multinomial'){
sol_tables <- floodlight.analysis(sol,
var_numeric,
var_factor,
sol$samples_l2_param,
sol$dMatrice$X_full[[1]],
sol$dMatrice$Z,
dataX = sol$dataX,
dataZ = sol$dataZ,
flood_values = flood_values)
} else if(sol$model_name == 'BANOVA.multiNormal') {
sol_tables <- list()
for (i in 1:sol$num_depenent_variables){
name <- sol$names_of_dependent_variables[i]
sol_tables[[name]] <- floodlight.analysis(sol,
var_numeric,
var_factor,
sol$samples_l2.list[[i]],
sol$dMatrice$X,
sol$dMatrice$Z,
data = sol$data,
flood_values = flood_values)
}
}else{
sol_tables <- floodlight.analysis(sol,
var_numeric,
var_factor,
sol$samples_l2_param,
sol$dMatrice$X,
sol$dMatrice$Z,
data = sol$data,
flood_values = flood_values)
}
}
class(sol_tables) <- 'BANOVA.floodlight'
return(sol_tables)
}else{
stop('Model is not recognized')
}
} | /scratch/gouwar.j/cran-all/cranData/BANOVA/R/BANOVA.floodlight.R |
###
# In this version, the mediation analysis only includes one mediator
###
BANOVA.mediation <-
function(sol_1, sol_2, xvar, mediator, individual = F, return_posterior_samples = F,
multi_samples_beta1_raw_m = NULL){
#Function which prepares labels for the results returened to the user
prepare_list_name <- function(moderated_var, table_colnames){
#check if there are factors at other levels
n_col <- length(table_colnames)
if (n_col-3 > 0){
table_colnames <- table_colnames[1:(n_col-3)]
moderators <- table_colnames[table_colnames != moderated_var]
num_moderators <- length(moderators)
if (num_moderators > 1){
moderators <- paste(moderators, collapse ="_and_")
}
if (num_moderators!=0){
title <- paste0("Direct_effects_of_", moderated_var, "_moderated_by_", moderators)
} else {
title <- NULL
}
} else {
title <- NULL
}
return(title)
}
#Model for the outome variable (sol_1) can follow any distribution except for the Multinomial
if(!(class(sol_1) %in% c('BANOVA', 'BANOVA.Normal', 'BANOVA.T', 'BANOVA.Poisson', 'BANOVA.Bern',
'BANOVA.Bin', 'BANOVA.ordMultinomial'))) stop('The Model is not supported yet')
if(sol_1$model_name == 'BANOVA.Multinomial') stop('The Model is not supported yet')
#Model for the mediator (sol_2) must be Normal
if(sol_2$model_name != 'BANOVA.Normal') stop('The mediator must follow the Normal distribution, use BANOVA Normal models instead.')
#####Outcome variable
#Extract names of the regressors in the outome model
X_names = colnames(sol_1$dMatrice$X)
Z_names = colnames(sol_1$dMatrice$Z)
#Extract indexes of regressors with correspondace to the variables (Intercept - 0)
X_assign = attr(sol_1$dMatrice$X, 'assign')
Z_assign = attr(sol_1$dMatrice$Z, 'assign')
num_l1 <- length(X_assign) #num level 1 regressors in the outome model
num_l2 <- length(Z_assign) #num level 2 regressors in the outome model
#Extract relevant coefficients in the outome model
if (sol_1$single_level){
samples_l2_param <- sol_1$samples_l1_param
} else {
samples_l2_param <- sol_1$samples_l2_param
}
n_sample <- nrow(samples_l2_param)
est_matrix <- array(0 , dim = c(num_l1, num_l2, n_sample), dimnames = list(X_names, Z_names, NULL))
for (i in 1:num_l1){
for (j in 1:n_sample)
est_matrix[i,,j] <- samples_l2_param[j,((i-1)*num_l2+1):((i-1)*num_l2+num_l2)]
}
#####Mediator
#Extract names of the regressors in the mediator model
X_names_m = colnames(sol_2$dMatrice$X)
Z_names_m = colnames(sol_2$dMatrice$Z)
#Extract indexes of regressors with correspondace to the variables (Intercept - 0)
X_assign_m = attr(sol_2$dMatrice$X, 'assign')
Z_assign_m = attr(sol_2$dMatrice$Z, 'assign')
num_l1_m <- length(X_assign_m) #num level 1 regressors in the mediator model
num_l2_m <- length(Z_assign_m) #num level 2 regressors in the mediator model
#Extract relevant coefficients in the mediator model
if (sol_2$single_level) {
samples_l2_param_m <- sol_2$samples_l1_param
} else {
samples_l2_param_m <- sol_2$samples_l2_param
}
n_sample_m <- nrow(samples_l2_param_m)
est_matrix_m <- array(0, dim = c(num_l1_m, num_l2_m, n_sample_m), dimnames = list(X_names_m, Z_names_m, NULL))
for (i in 1:num_l1_m){
for (j in 1:n_sample_m)
est_matrix_m[i,,j] <- samples_l2_param_m[j,((i-1)*num_l2_m+1):((i-1)*num_l2_m+num_l2_m)]
}
sol <- list()
#Individal effects can be calculated the outome and mediator model are multi-level
if (individual){
model1_level1_var_matrix <- attr(attr(sol_1$mf1, 'terms'),'factors')
model1_level1_var_dataClasses <- attr(attr(sol_1$mf1, 'terms'),'dataClasses')
model1_level2_var_matrix <- attr(attr(sol_1$mf2, 'terms'),'factors')
model1_level2_var_dataClasses <- attr(attr(sol_1$mf2, 'terms'),'dataClasses')
model2_level1_var_matrix <- attr(attr(sol_2$mf1, 'terms'),'factors')
model2_level1_var_dataClasses <- attr(attr(sol_2$mf1, 'terms'),'dataClasses')
model2_level2_var_matrix <- attr(attr(sol_2$mf2, 'terms'),'factors')
model2_level2_var_dataClasses <- attr(attr(sol_2$mf2, 'terms'),'dataClasses')
if (sol_1$single_level || sol_2$single_level){
stop("It seems to be a between-subject design, set individual = FALSE instead.")
}
fit_betas <- rstan::extract(sol_1$stan_fit, permuted = T)
samples_l1_raw <- fit_betas$beta1
samples_l1_individual <- aperm(samples_l1_raw, c(2,1,3)) # dimension: num_l1 x sample size x num_id
dimnames(samples_l1_individual) <- list(X_names, NULL, NULL)
# mediator
if(is.null(multi_samples_beta1_raw_m)){
fit_betas_m <- rstan::extract(sol_2$stan_fit, permuted = T)
samples_l1_raw_m <- fit_betas_m$beta1
samples_l1_individual_m <- aperm(samples_l1_raw_m, c(2,1,3)) # dimension: num_l1 x sample size x num_id
} else {
samples_l1_raw_m <- multi_samples_beta1_raw_m
samples_l1_individual_m <- aperm(samples_l1_raw_m, c(3,1,2))
}
dimnames(samples_l1_individual_m) <- list(X_names_m, NULL, NULL)
# calc id map
id_map = idmap(sol_1$old_id, sol_1$new_id)
# calculate direct effect of xvar in model 1
sol$dir_effects <- list()
if (xvar %in% rownames(model1_level1_var_matrix)){
sol$individual_direct <- list()
direct_effects <- cal.mediation.effects.individual(sol_1, samples_l1_individual, xvar, "NA")
for (i in 1:length(direct_effects)){
# filter columns with only "1" or 1 (numeric), TODO: here 1 is hard coded, think about a better way to determine if it is numeric
idx_to_rm <- c()
for (j in 1:dim(direct_effects[[i]]$table_m[,,1,drop = F])[2]){
if (all(direct_effects[[i]]$table_m[, j, 1] == '1') || all(direct_effects[[i]]$table_m[, j, 1] == 1))
idx_to_rm <- c(idx_to_rm, j)
}
if(length(idx_to_rm) > 0)
sol$dir_effects[[i]] <- direct_effects[[i]]$table_m[, -idx_to_rm, ,drop = F]
else
sol$dir_effects[[i]] <- direct_effects[[i]]$table_m
sol$individual_direct[[i]] <- rabind(sol$dir_effects[[i]], id_map)
#prepare a title for the table if moderation is present
element_name <- prepare_list_name(mediator, colnames(sol$dir_effects[[i]]))
if(!is.null(element_name))
names(sol$individual_direct)[i] <- element_name
names(sol$dir_effects)[i] <- element_name
}
}else{
direct_effects <- cal.mediation.effects(sol_1, est_matrix, n_sample, xvar, "NA")
for (i in 1:length(direct_effects)){
# filter columns with only "1" or 1 (numeric), TODO: here 1 is hard coded, think about a better way to determine if it is numeric
idx_to_rm <- c()
for (j in 1:ncol(direct_effects[[i]]$table_m)){
if (all(direct_effects[[i]]$table_m[, j] == '1') || all(direct_effects[[i]]$table_m[, j] == 1))
idx_to_rm <- c(idx_to_rm, j)
}
if(length(idx_to_rm) > 0)
sol$dir_effects[[i]] <- direct_effects[[i]]$table_m[, -idx_to_rm]
else
sol$dir_effects[[i]] <- direct_effects[[i]]$table_m
}
#prepare a title for the table if moderation is present
element_name <- prepare_list_name(xvar, colnames(sol$dir_effects[[i]]))
if(!is.null(element_name))
names(sol$dir_effects)[i] <- element_name
}
# calculate (direct) effects of the mediator in model 1
if (!(mediator %in% rownames(model1_level1_var_matrix))) stop("The mediator is between subjects, please set individual = FALSE.")
mediator_l1_effects <- cal.mediation.effects.individual(sol_1, samples_l1_individual, mediator, xvar = "NA", is_mediator = T)
sol$m1_effects <- list()
for (i in 1:length(mediator_l1_effects)){
# filter columns with only "1" or 1 (numeric), TODO: here 1 is hard coded, think about a better way to determine if it is numeric
idx_to_rm <- c()
for (j in 1:dim(mediator_l1_effects[[i]]$table_m[,,1, drop = F])[2]){
if (all(mediator_l1_effects[[i]]$table_m[, j, 1] == '1') || all(mediator_l1_effects[[i]]$table_m[, j, 1] == 1))
idx_to_rm <- c(idx_to_rm, j)
}
if(length(idx_to_rm) > 0)
sol$m1_effects[[i]] <- mediator_l1_effects[[i]]$table_m[, -idx_to_rm, , drop = F]
else
sol$m1_effects[[i]] <- mediator_l1_effects[[i]]$table_m
#prepare a title for the table if moderation is present
element_name <- prepare_list_name(mediator, colnames(sol$m1_effects[[i]]))
if(!is.null(element_name))
names(sol$m1_effects)[i] <- element_name
}
# calculate (direct) effects of the xvar on mediator (in model 2)
sol$m2_effects <- list()
if (xvar %in% rownames(model2_level1_var_matrix)){
mediator_xvar_effects <- cal.mediation.effects.individual(sol_2, samples_l1_individual_m, xvar)
for (i in 1:length(mediator_xvar_effects)){
temp_array <- array(1, dim = c(nrow(mediator_xvar_effects[[i]]$table_m), 1), dimnames = list(NULL, mediator))
mediator_xvar_effects[[i]]$table_m <- abind(temp_array, mediator_xvar_effects[[i]]$table_m)
mediator_xvar_effects[[i]]$index_name <- cbind(array(1, dim = c(nrow(mediator_xvar_effects[[i]]$index_name), 1), dimnames = list(NULL, mediator)), mediator_xvar_effects[[i]]$index_name)
# filter columns with only "1" or 1 (numeric), TODO: here 1 is hard coded, think about a better way to determine if it is numeric
idx_to_rm <- c()
for (j in 1:dim(mediator_xvar_effects[[i]]$table_m[,,1, drop = F])[2]){
if (all(mediator_xvar_effects[[i]]$table_m[, j, 1] == '1') || all(mediator_xvar_effects[[i]]$table_m[, j, 1] == 1))
idx_to_rm <- c(idx_to_rm, j)
}
if(length(idx_to_rm) > 0)
sol$m2_effects[[i]] <- mediator_xvar_effects[[i]]$table_m[, -idx_to_rm,, drop = F]
else
sol$m2_effects[[i]] <- mediator_xvar_effects[[i]]$table_m
#prepare a title for the table if moderation is present
element_name <- prepare_list_name(xvar, colnames(sol$m2_effects[[i]]))
if(!is.null(element_name))
names(sol$m2_effects)[i] <- element_name
}
}else if (xvar %in% rownames(model2_level2_var_matrix)){
mediator_xvar_effects <- cal.mediation.effects(sol_2, est_matrix_m, n_sample_m, xvar)
for (i in 1:length(mediator_xvar_effects)){
mediator_xvar_effects[[i]]$table_m <- cbind(array(1, dim = c(nrow(mediator_xvar_effects[[i]]$table_m), 1), dimnames = list(NULL, mediator)), mediator_xvar_effects[[i]]$table_m)
mediator_xvar_effects[[i]]$index_name <- cbind(array(1, dim = c(nrow(mediator_xvar_effects[[i]]$index_name), 1), dimnames = list(NULL, mediator)), mediator_xvar_effects[[i]]$index_name)
# filter columns with only "1" or 1 (numeric), TODO: here 1 is hard coded, think about a better way to determine if it is numeric
idx_to_rm <- c()
for (j in 1:ncol(mediator_xvar_effects[[i]]$table_m)){
if (all(mediator_xvar_effects[[i]]$table_m[, j] == '1') || all(mediator_xvar_effects[[i]]$table_m[, j] == 1))
idx_to_rm <- c(idx_to_rm, j)
}
if(length(idx_to_rm) > 0)
sol$m2_effects[[i]] <- mediator_xvar_effects[[i]]$table_m[, -idx_to_rm]
else
sol$m2_effects[[i]] <- mediator_xvar_effects[[i]]$table_m
#prepare a title for the table if moderation is present
element_name <- prepare_list_name(xvar, colnames(sol$m2_effects[[i]]))
if(!is.null(element_name))
names(sol$m2_effects)[i] <- element_name
}
}
if (return_posterior_samples){
sol$direct_effects_samples <- direct_effects
sol$indirect_effects_samples <- list()
}
k <- 1
sol$indir_effects <- list()
sol$effect_size <- list()
sol$individual_indirect <- list()
for (i in 1:length(mediator_l1_effects)){
for (j in 1:length(mediator_xvar_effects)){
comb_eff <- combine.effects.individual(mediator_l1_effects[[i]], mediator_xvar_effects[[j]],
sol_1$tau_ySq, sol_1$data, mediator, id_map,
return_posterior_samples)
indirect_effects <- comb_eff$table
sol$effect_size[[k]] <- comb_eff$effect_size
if (return_posterior_samples){
sol$indirect_effects_samples[[k]] <- comb_eff$samples
}
idx_to_rm <- c()
for (j in 1:ncol(indirect_effects)){
if (all(indirect_effects[, j, 1] == '1') || all(indirect_effects[, j, 1] == 1))
idx_to_rm <- c(idx_to_rm, j)
}
if(length(idx_to_rm) > 0)
sol$indir_effects[[k]] <- indirect_effects[, -idx_to_rm,, drop = F]
else
sol$indir_effects[[k]] <- indirect_effects
sol$individual_indirect[[k]] <- rabind(sol$indir_effects[[k]])
#Prepare label for the table
name_effect_X_on_M <- names(sol$m2_effects)
name_effect_M_on_Y <- names(sol$m1_effects[i])
#Prepare a label for the table with indirect effects
if (sum(is.null(name_effect_X_on_M), is.null(name_effect_M_on_Y)) != 2){
if (is.null(name_effect_X_on_M)){
table_label <- paste0("Indirect_effects_of_", xvar)
} else {
name_effect_X_on_M <- gsub("Direct_effects_of_", "", name_effect_X_on_M)
table_label <- paste0("Indirect_effects_of_", name_effect_X_on_M)
}
if (!is.null(name_effect_M_on_Y)){
name_effect_M_on_Y <- gsub("Direct_effects_of_", "", name_effect_M_on_Y)
table_label <- paste0(table_label, "_through_", name_effect_M_on_Y)
}
names(sol$indir_effects)[k] <- table_label
names(sol$individual_indirect)[k] <- table_label
}
k <- k + 1
}
}
sol$xvar = xvar
sol$mediator = mediator
sol$individual = individual
class(sol) <- 'BANOVA.mediation'
return(sol)
}else{
#################
if(0){ # temporarily replaced by the function cal.mediation.effects
model1_level1_var_matrix <- attr(attr(sol_1$mf1, 'terms'),'factors')
model1_level1_var_dataClasses <- attr(attr(sol_1$mf1, 'terms'),'dataClasses')
model1_level2_var_matrix <- attr(attr(sol_1$mf2, 'terms'),'factors')
model1_level2_var_dataClasses <- attr(attr(sol_1$mf2, 'terms'),'dataClasses')
# find the direct effects
# find corresponding names in X or Z for xvar, see floodlight analysis, then used in est_matrix
xvar_in_l1 <- xvar %in% rownames(model1_level1_var_matrix)
xvar_in_l2 <- xvar %in% rownames(model1_level2_var_matrix)
if (!xvar_in_l1 & !xvar_in_l2) stop("xvar is not included in the model!")
if (xvar_in_l1){
attr(xvar, 'class') = model1_level1_var_dataClasses[xvar]
xvar_index <- which(rownames(model1_level1_var_matrix) == xvar)
xvar_index_assign <- which(model1_level1_var_matrix[xvar_index, ] == 1)
xvar_related_names <- X_names[which(X_assign %in% xvar_index_assign)]
for (xvar_name in xvar_related_names){
print('Direct effects:')
est_samples <- array(0, dim = c(n_sample))
for (n_s in 1:n_sample){
est_samples[n_s] <- est_matrix[xvar_name, 1, n_s]
}
direct_effec_mean <- mean(est_samples)
quantiles <- quantile(est_samples, c(0.025, 0.975))
tmp_output <- array(0, dim = c(1,3), dimnames = list(NULL, c('mean', '2.5%', '97.5%')))
tmp_output[1,1] <- direct_effec_mean
tmp_output[1,2:3] <- quantiles
print(tmp_output)
}
}else{
attr(xvar, 'class') = model1_level2_var_dataClasses[xvar]
xvar_index <- which(rownames(model1_level2_var_matrix) == xvar)
xvar_index_assign <- which(model1_level2_var_matrix[xvar_index, ] == 1)
xvar_related_names <- Z_names[which(Z_assign %in% xvar_index_assign)]
for (xvar_name in xvar_related_names){
print('Direct effects:')
est_samples <- array(0, dim = c(n_sample))
for (n_s in 1:n_sample){
est_samples[n_s] <- est_matrix[1, xvar_name, n_s]
}
direct_effec_mean <- mean(est_samples)
quantiles <- quantile(est_samples, c(0.025, 0.975))
tmp_output <- array(0, dim = c(1,3), dimnames = list(NULL, c('mean', '2.5%', '97.5%')))
tmp_output[1,1] <- direct_effec_mean
tmp_output[1,2:3] <- quantiles
print(tmp_output)
}
}
}
##################
# calculate direct effect of xvar in model 1 (based on the outcome model)
direct_effects <- cal.mediation.effects(sol_1, est_matrix, n_sample, xvar, mediator)
sol$dir_effects <- list()
for (i in 1:length(direct_effects)){
# filter columns with only "1" or 1 (numeric), TODO: here 1 is hard coded, think about a better way to determine if it is numeric
idx_to_rm <- c()
for (j in 1:ncol(direct_effects[[i]]$table_m)){
if (all(direct_effects[[i]]$table_m[, j] == '1') || all(direct_effects[[i]]$table_m[, j] == 1))
idx_to_rm <- c(idx_to_rm, j)
}
if(length(idx_to_rm) > 0)
sol$dir_effects[[i]] <- direct_effects[[i]]$table_m[, -idx_to_rm]
else
sol$dir_effects[[i]] <- direct_effects[[i]]$table_m
#prepare a title for the table if moderation is present
element_name <- prepare_list_name(xvar, colnames(sol$dir_effects[[i]]))
if(!is.null(element_name))
names(sol$dir_effects)[i] <- element_name
}
# calculate effects of the mediator in model 1
mediator_l1_effects <- cal.mediation.effects(sol_1, est_matrix, n_sample, mediator, xvar = "NA")
sol$m1_effects <- list()
for (i in 1:length(mediator_l1_effects)){
temp_table <- mediator_l1_effects[[i]]$table_m
# filter columns with only "1" or 1 (numeric), TODO: here 1 is hard coded, think about a better way to determine if it is numeric
idx_to_rm <- c()
for (j in 1:ncol(temp_table)){
if (all(temp_table[, j] == '1') || all(temp_table[, j] == 1))
idx_to_rm <- c(idx_to_rm, j)
}
if(length(idx_to_rm) > 0)
sol$m1_effects[[i]] <- temp_table[, -idx_to_rm]
else
sol$m1_effects[[i]] <- temp_table
#prepare a title for the table if moderation is present
element_name <- prepare_list_name(mediator, colnames(sol$m1_effects[[i]]))
if(!is.null(element_name))
names(sol$m1_effects)[i] <- element_name
}
# calculate effects of the xvar in model 2
mediator_xvar_effects <- cal.mediation.effects(sol_2, est_matrix_m, n_sample_m, xvar, "NA")
sol$m2_effects <- list()
for (i in 1:length(mediator_xvar_effects)){
mediator_xvar_effects[[i]]$table_m <- cbind(array(1, dim = c(nrow(mediator_xvar_effects[[i]]$table_m), 1), dimnames = list(NULL, mediator)), mediator_xvar_effects[[i]]$table_m)
mediator_xvar_effects[[i]]$index_name <- cbind(array(1, dim = c(nrow(mediator_xvar_effects[[i]]$index_name), 1), dimnames = list(NULL, mediator)), mediator_xvar_effects[[i]]$index_name)
# filter columns with only "1" or 1 (numeric), TODO: here 1 is hard coded, think about a better way to determine if it is numeric
idx_to_rm <- c()
for (j in 1:ncol(mediator_xvar_effects[[i]]$table_m)){
if (all(mediator_xvar_effects[[i]]$table_m[, j] == '1') || all(mediator_xvar_effects[[i]]$table_m[, j] == 1))
idx_to_rm <- c(idx_to_rm, j)
}
if(length(idx_to_rm) > 0)
sol$m2_effects[[i]] <- mediator_xvar_effects[[i]]$table_m[, -idx_to_rm]
else
sol$m2_effects[[i]] <- mediator_xvar_effects[[i]]$table_m
#prepare a title for the table if moderation is present
element_name <- prepare_list_name(xvar, colnames(sol$m2_effects[[i]]))
if(!is.null(element_name))
names(sol$m2_effects)[i] <- element_name
}
k <- 1
sol$indir_effects <- list()
sol$effect_size <- list()
if (return_posterior_samples){
sol$direct_effects_samples <- direct_effects
sol$indirect_effects_samples <- list()
}
# calculate effects of the xvar in model 2
for (i in 1:length(mediator_l1_effects)){
for (j in 1:length(mediator_xvar_effects)){
comb_eff <- combine.effects(mediator_l1_effects[[i]], mediator_xvar_effects[[j]], sol_1$tau_ySq,
sol_1$data, mediator, return_posterior_samples)
indirect_effects <- comb_eff$table
sol$effect_size[[k]] <- comb_eff$effect_size
if (return_posterior_samples){
sol$indirect_effects_samples[[k]] <- comb_eff$samples
}
idx_to_rm <- c()
for (j in 1:ncol(indirect_effects)){
if (all(indirect_effects[, j] == '1') || all(indirect_effects[, j] == 1))
idx_to_rm <- c(idx_to_rm, j)
}
if(length(idx_to_rm) > 0){
sol$indir_effects[[k]] <- indirect_effects[, -idx_to_rm]
} else {
sol$indir_effects[[k]] <- indirect_effects
}
#Prepare label for the table
name_effect_X_on_M <- names(sol$m2_effects[1])
name_effect_M_on_Y <- names(sol$m1_effects[i])
#Prepare a label for the table with indirect effects
if (sum(is.null(name_effect_X_on_M), is.null(name_effect_M_on_Y)) !=2){
if (is.null(name_effect_X_on_M)){
table_label <- paste0("Indirect_effects_of_", xvar)
} else {
name_effect_X_on_M <- gsub("Direct_effects_of_", "", name_effect_X_on_M)
table_label <- paste0("Indirect_effects_of_", name_effect_X_on_M)
}
if (!is.null(name_effect_M_on_Y)){
name_effect_M_on_Y <- gsub("Direct_effects_of_", "", name_effect_M_on_Y)
table_label <- paste0(table_label, "_through_", name_effect_M_on_Y)
}
names(sol$indir_effects)[k] <- table_label
}
k <- k + 1
}
}
sol$xvar = xvar
sol$mediator = mediator
sol$individual = individual
class(sol) <- 'BANOVA.mediation'
return(sol)
}
}
combine.effects.individual <- function (mediator_l1_effects, mediator_xvar_effects, tau_ySq, data, mediator, id_map,
return_posterior_samples){
num_id = dim(mediator_l1_effects$samples)[3]
table_1_names <- mediator_l1_effects$index_name
table_2_names <- mediator_xvar_effects$index_name
# find common columns
temp_1 <- mediator_l1_effects$index
colnames(temp_1) <- paste(colnames(temp_1), '.1', sep = "")
table_1_names_index <- cbind(table_1_names, temp_1)
temp_2 <- mediator_xvar_effects$index
colnames(temp_2) <- paste(colnames(temp_2), '.2', sep = "")
table_2_names_index <- cbind(table_2_names, temp_2)
table_2_names_index.df <- table_2_names_index
table_1_names_index.df <- table_1_names_index
temp_table_index <- merge(table_2_names_index.df, table_1_names_index.df,
by = intersect(colnames(table_1_names), colnames(table_2_names)), all.x = T)
table_1_est_sample_index <- temp_table_index[,colnames(temp_1), drop = F]
table_2_est_sample_index <- temp_table_index[,colnames(temp_2), drop = F]
# standardize the names of this table, so that the output table looks consistant, direct vs indirect, e.g. sort the column names
union_names <- union(colnames(table_1_names), colnames(table_2_names))
union_names <- union_names[order(union_names)]
union_names_original <- union_names
result_table <- array('1', dim = c(nrow(temp_table_index), length(union_names) + 6, num_id),
dimnames = list(rep("",nrow(temp_table_index)), c(union_names, 'mean', '2.5%', '97.5%', 'p.value', 'id', 'effect size'), NULL))
common_n_sample <- min(dim(mediator_l1_effects$samples)[2], dim(mediator_xvar_effects$samples)[2])
#result_table_sample <- array('1', dim = c(nrow(temp_table_index), ncol(temp_table_index) - 2 + common_n_sample, num_id), dimnames = list(rep("",nrow(temp_table_index)), c(union_names, paste('s_', 1:common_n_sample, sep = "")), NULL))
result_table_sample <- array('1', dim = c(nrow(temp_table_index), length(union_names) + common_n_sample, num_id),
dimnames = list(rep("",nrow(temp_table_index)), c(union_names, paste('s_', 1:common_n_sample, sep = "")), NULL))
effect_size <- rep("", num_id)
for (i in 1:num_id){
union_names <- union_names_original
result_table[, 'id', i] <- id_map[i]
for (nm in union_names){
result_table[, nm, i] <- as.character(temp_table_index[[nm]])
result_table_sample[, nm, i] <- as.character(temp_table_index[[nm]])
}
for (ind in 1:nrow(table_1_est_sample_index)){
index_1 <- as.integer(table_1_est_sample_index[ind,1])
index_2 <- as.integer(table_2_est_sample_index[ind,1])
m_samples <- mediator_l1_effects$samples[index_1, 1:common_n_sample, i] * mediator_xvar_effects$samples[index_2, 1:common_n_sample, i]
result_table[ind,'mean', i] <- round(mean(m_samples), 4)
result_table[ind,c('2.5%', '97.5%'), i] <- round(quantile(m_samples, probs = c(0.025, 0.975)),4)
result_table[ind,'p.value', i] <- ifelse(round(pValues(array(m_samples, dim = c(length(m_samples), 1))), 4) == 0,
'<0.0001', round(pValues(array(m_samples, dim = c(length(m_samples), 1))), 4))
result_table_sample[ind, paste('s_', 1:common_n_sample, sep = ""), i] <- m_samples
}
# compute effect size for the indirect effect
if (mediator %in% union_names)
union_names <- union_names[-which(union_names == mediator)]
if ('(Intercept)' %in% union_names)
union_names <- union_names[-which(union_names == '(Intercept)')]
#remove numeric variable
to_rm <- c()
for (to_rm_ind in 1:length(union_names)){
if (is.numeric(data[,union_names[to_rm_ind]])){
to_rm <- c(to_rm, to_rm_ind)
}
}
if (length(to_rm) > 0)
union_names <- union_names[-to_rm]
data_eff <- data[, union_names, drop = F]
#If result_table_sample contains only one row it is treated as "character and mergind fails
if (!inherits(result_table_sample[,,i], "matrix")){
data_eff_sample <- merge(data_eff, t(data.frame(result_table_sample[,,i])), by = union_names, all.x = TRUE)
} else {
data_eff_sample <- merge(data_eff, result_table_sample[,,i], by = union_names, all.x = TRUE)
}
data_eff_sample <- apply(data_eff_sample[, paste('s_', 1:common_n_sample, sep = "")], 2, as.character)
data_eff_sample <- apply(data_eff_sample, 2, as.numeric)
var_sample <- apply(data_eff_sample, 2, var)
eff_sample <- var_sample/(var_sample + tau_ySq)
effect_size[i] <- paste(round(mean(eff_sample), 3), " (", paste(round(quantile(eff_sample, probs = c(0.025, 0.975)),3), collapse = ','), ")", sep="")
result_table[, 'effect size', i] <- effect_size[i]
}
if (return_posterior_samples){
return_list <- list(table = result_table, effect_size = effect_size, samples = result_table_sample)
} else {
return_list <- list(table = result_table, effect_size = effect_size)
}
return(return_list)
}
combine.effects <- function (mediator_l1_effects, mediator_xvar_effects, tau_ySq, data, mediator,
return_posterior_samples){
table_1_names <- mediator_l1_effects$index_name #indexing of the table with direct effects of mediator
table_2_names <- mediator_xvar_effects$index_name #indexing of the table with indirect effects of xvar
#Prepare tables with variables and corresponding index of the effects
temp_1 <- mediator_l1_effects$index
colnames(temp_1) <- paste(colnames(temp_1), '.1', sep = "")
table_1_names_index.df <- cbind(table_1_names, temp_1)
temp_2 <- mediator_xvar_effects$index
colnames(temp_2) <- paste(colnames(temp_2), '.2', sep = "")
table_2_names_index.df <- cbind(table_2_names, temp_2)
temp_table_index <- merge(table_2_names_index.df, table_1_names_index.df,
by = intersect(colnames(table_1_names), colnames(table_2_names)), all.x = T)
#TODO: what's really going on here?
if(all(is.na(temp_table_index[colnames(temp_1)]))){
temp_table_index[colnames(temp_1)] <- table_1_names_index.df[, colnames(temp_1)]
}
#Final indexing of tables
table_1_est_sample_index <- temp_table_index[,colnames(temp_1), drop = F]
table_2_est_sample_index <- temp_table_index[,colnames(temp_2), drop = F]
# standardize the names of this table, so that the output table looks consistant, direct vs indirect
# e.g. sort the column names
union_names <- union(colnames(table_1_names), colnames(table_2_names))
union_names <- union_names[order(union_names)]
#Number of samples in the calculation should be the same for the direct and indirect effects
common_n_sample <- min(dim(mediator_l1_effects$samples)[3], dim(mediator_xvar_effects$samples)[3])
#Prepare results
result_table <- array('1', dim = c(nrow(temp_table_index), length(union_names) + 4),
dimnames = list(rep("",nrow(temp_table_index)),
c(union_names, 'mean', '2.5%', '97.5%', 'p.value')))
result_table_sample <- array('1', dim = c(nrow(temp_table_index), length(union_names) + common_n_sample),
dimnames = list(rep("",nrow(temp_table_index)),
c(union_names, paste('s_', 1:common_n_sample, sep = ""))))
return_samples <- data.frame(matrix(nrow = nrow(temp_table_index), ncol = length(union_names) + common_n_sample))
colnames(return_samples) <- c(union_names, paste('s_', 1:common_n_sample, sep = ""))
for (name in union_names){
result_table[, name] <- as.character(temp_table_index[[name]])
result_table_sample[, name] <- as.character(temp_table_index[[name]])
return_samples[, name ] <- as.character(temp_table_index[[name]])
}
#Fill in the table with results by row
for (ind in 1:nrow(table_1_est_sample_index)){
#Selct and multiply samples
m_samples <- mediator_l1_effects$samples[as.integer(table_1_est_sample_index[ind,1]), as.integer(table_1_est_sample_index[ind,2]), 1:common_n_sample] *
mediator_xvar_effects$samples[as.integer(table_2_est_sample_index[ind,1]), as.integer(table_2_est_sample_index[ind,2]), 1:common_n_sample]
#Calculate summary statistics
result_table[ind,'mean'] <- round(mean(m_samples), 4)
result_table[ind,c('2.5%', '97.5%')] <- round(quantile(m_samples, probs = c(0.025, 0.975)), 4)
result_table[ind,'p.value'] <- ifelse(round(pValues(array(m_samples, dim = c(length(m_samples), 1))), 4) == 0, '<0.0001', round(pValues(array(m_samples, dim = c(length(m_samples), 1))), 4))
#Prepare samples to be returned
result_table_sample[ind, paste('s_', 1:common_n_sample, sep = "")] <- m_samples
return_samples[ind, paste('s_', 1:common_n_sample, sep = "")] <- m_samples
}
######Compute effect size for the indirect effect
#Remove mediator and intercept form the union of names
if (mediator %in% union_names)
union_names <- union_names[-which(union_names == mediator)]
if ('(Intercept)' %in% union_names)
union_names <- union_names[-which(union_names == '(Intercept)')]
#Remove numeric variable
to_rm <- c()
for (i in 1:length(union_names)){
to_rm <- c(to_rm, i)
}
if (length(to_rm) > 0)
union_names <- union_names[-to_rm]
#Select relevant columns
data_eff <- data[, union_names, drop = F]
data_eff_sample <- merge(data_eff, result_table_sample, by = union_names, all.x = TRUE)
# remove redundant columns and convert the variance
data_eff_sample <- apply(data_eff_sample[, paste('s_', 1:common_n_sample, sep = "")], 2, as.character)
data_eff_sample <- apply(data_eff_sample, 2, as.numeric)
# culculate effect sizes
var_sample <- apply(data_eff_sample, 2, var) #variance of each column of the indirect effects samples
eff_sample <- var_sample/(var_sample + tau_ySq)
effect_size <- paste(round(mean(eff_sample), 3), " (", paste(round(quantile(eff_sample, probs = c(0.025, 0.975), na.rm = T),3), collapse = ','), ")", sep="")
#sort values column by column
result_table <- data.frame(result_table, check.names=FALSE)
result_table <- result_table[do.call(order, result_table), ]
if (return_posterior_samples){
return_list <- list(table = result_table, effect_size = effect_size, samples = return_samples)
} else {
return_list <- list(table = result_table, effect_size = effect_size)
}
return(return_list)
}
# a three dimensional array b cbind its first two dimension matrice with a matrix a (2 dim)
abind <- function(a, b){
n_id <- dim(b)[3]
n_r <- dim(b)[1]
n_c <- dim(b)[2]
dim_a <- dim(a)
mediator <- colnames(a)
res <- array(NA, dim = c(n_r, n_c+ncol(a), n_id), dimnames = list(NULL, c(colnames(a), dimnames(b)[[2]]), NULL))
if(dim_a[1] != 1){
for (i in 1:n_id){
res[,,i] <- cbind(a, b[,,i])
}
} else {
for (i in 1:n_id){
temp <- c(a, b[,,i])
names(temp)[1:dim_a[2]] <- mediator
res[,,i] <- temp
}
}
return(res)
}
# rbind all first two dimesion matrice for a 3 dimension matrix
rabind <- function(a, id_map = NULL){
if(is.null(id_map)){
res = array(0, dim = c(dim(a)[1], dim(a)[2],0))
for (i in 1:dim(a)[3]){
res <- rbind(res, a[,,i])
}
}else{
# the last dimension is the new id
res = array(0, dim = c(dim(a)[1], dim(a)[2] + 1,0))
for (i in 1:dim(a)[3]){
res <- rbind(res, cbind(a[,,i], id = id_map[i]))
}
}
return(res)
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/BANOVA.mediation.R |
#' extract BANOVA models
#' @param model_name String specifying BANOVA models (e.g. Normal)
#'
#' @return A BANOVA model (stan code).
#'
#' @examples
#' \dontrun{
#'
#' }
#'
BANOVA.model <- function (model_name,
single_level = F){
if(model_name %in% c('Normal', 'Poisson', 'T', 'Bernoulli',
'Binomial', 'ordMultinomial', 'Multinomial',
'multiNormal', 'truncNormal')){
if(single_level){
name <- paste("stan/single_",model_name, ".stan", sep = "")
}else{
name <- paste("stan/", model_name, "_Normal.stan", sep = "")
}
file_src <- system.file(name, package = 'BANOVA', mustWork = TRUE)
model_code = readChar(file_src, nchars=1000000)
}else{
stop(paste(model_name, " model is not supported currently!"))
}
sol <- list(model_code = model_code, model_name = model_name, single_level = single_level)
class(sol) <- 'BANOVA.model'
return(sol)
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/BANOVA.model.R |
#' Mediation analysis with multiple possibly correlated mediators
#'
#' \code{BANOVA.multi.mediation} is a function for analysis of multiple possibly correlated mediators.
#' These mediators are assumed to have no causal influence on each other.
#' Both single-level and multi-level models can be analyzed.
#' @usage BANOVA.multi.mediation(sol_1, sol_2, xvar, mediators, individual = FALSE)
#' @param sol_1 an object of class "BANOVA" returned by BANOVA.run function with a fitted
#' model for an outcome variable regressed on a causal variable, a mediator, and, possibly,
#' moderators and control variables. The outcome variable can follow Normal, T, Poisson, Bernoulli,
#' Binomial, and ordered Multinomial distributions.
#' @param sol_2 an object of class "BANOVA" returned by BANOVA.run function, which contains an
#' outcome of the analysis for multiple Multivariate Normal mediators regressed on a casual variable
#' and other possible moderators and control variables.
#' @param xvar a character string that specifies the name of the causal variable used in both models.
#' @param mediators a vector with character strings, which specifies the names of the mediator
#' variables used in the models.
#' @param individual logical indicator of whether to output effects for individual units in the
#' analysis (TRUE or FALSE). This analysis requires a multilevel \code{sol_1}.
#' @return Returns an object of class \code{"BANOVA.multi.mediation"}. The returned object is a list
#' containing:
#
#' \item{\code{dir_effects}}{table or tables with the direct effect.}
#' \item{\code{individual_direct}}{is returned if \code{individual} is set to \code{TRUE} and the
#' causal variable is a within-subject variable. Contains a table or tables of the direct effect at
#' the individual levels of the analysis}
#' \item{\code{m1_effects}}{a list with tables of the effects of the mediator on the outcome}
#' \item{\code{m2_effects}}{a list with tables of the effect of the causal variable on the mediator}
#' \item{indir_effects}{tables of the indirect effect}
#' \item{individual_indirect}{is returned if \code{individual} is set to \code{TRUE} and the
#' mediator is a within-subject variable. Contains the table or tables with the indirect effect}
#' \item{effect_sizes}{a list with effect sizes on individual mediators}
#' \item{total_indir_effects}{table or tables with the total indirect effect of the causal variable}
#' \item{xvar}{the name of the causal variable}
#' \item{mediators}{the names of the mediating variables}
#' \item{individual}{the value of the argument individual (TRUE or FALSE)}
#' @details The function extends \code{BANOVA.mediation} to the case with multiple possibly
#' correlated mediators. For details about mediation analysis performed in BANOVA see
#' the help page for the \link[BANOVA]{BANOVA.mediation}.
#'
#' \code{BANOVA.multi.mediation} estimates and tests specific indirect effects of the causal
#' variable conveyed through each mediator. Furthermore, the total indirect effect of the causal
#' variables are computed as a sum of the specific indirect effects.
#'
#' The function prints multiple tables with mediated effects. Tables with direct effects of the
#' causal variable and mediators on the outcome variable, as well as direct effects of the causal
#' variable on the mediators include a posterior mean and 95\% credible intervals of the effects.
#' Next, the function displays on the console tables with specific indirect effects and effect sizes
#' of the mediators, followed by the TIE of the causal variable. These tables include the mean,
#' 95\% credible intervals, and two-sided Bayesian p-values.
#' @examples
#' # Use the colorad data set
#' data(colorad)
#' # Add a second mediator to the data set
#' colorad$blur_squared <- (colorad$blur)^2
#' # Prepare mediators to be analyzed in the Multivariate Normal model
#' mediators <- cbind(colorad$blur, colorad$blur_squared)
#' colnames(mediators) <- c("blur", "blur_squared")
#' colorad$mediators <- mediators
#' \donttest{
#' # Build and analyze the model for the outcome variable
#' model <- BANOVA.model('Binomial')
#' banova_binom_model <- BANOVA.build(model)
#' res_1 <- BANOVA.run(y ~ typic, ~ color + blur + blur_squared, fit = banova_binom_model,
#' data = colorad, id = 'id', num_trials = as.integer(16),
#' iter = 2000, thin = 1, chains = 2)
#' # Build and analyze the model for the mediators
#' model <- BANOVA.model('multiNormal')
#' banova_multi_norm_model <- BANOVA.build(model)
#' res_2 <- BANOVA.run(mediators ~ typic, ~ color, fit = banova_multi_norm_model,
#' data = colorad, id = 'id', iter = 2000, thin = 1, chains = 2)
#'
#' # Calculate (moderated) effects of "typic" mediated by "blur" and "blur_squared"
#' results <- BANOVA.multi.mediation(res_1, res_2, xvar='typic', mediators=c("blur", "blur_squared"))
#' }
#' @author Anna Kopyakova
#' @export
#results <- BANOVA.multi.mediation(res_1, res_2, xvar='typic', mediators=c("blur", "blur_squared"))
BANOVA.multi.mediation <- function(sol_1, sol_2, xvar, mediators, individual = FALSE){
#adapts the design matrix of a multivariate sol_2 to work with BANOVA.mediaation
adapt.design.matrix <- function(dMatrice, mediator){
d_temp <- dMatrice
#X
attributes(d_temp$X)$varValues[[1]] <- attributes(dMatrice$X)$varValues[[1]][, mediator]
attr(attributes(d_temp$X)$varValues[[1]], "var_names") <- mediator
#y
d_temp$y <- dMatrice$y[,mediator]
attr(d_temp$y, "names") <- attr(dMatrice$y, "dimnames")[[1]]
return(d_temp)
}
#adapts the mf1 of a multivariate sol_2 to work with BANOVA.mediaation
adapt.mf1 <- function(mf, mediator){
temp_mf <- mf
mediator_of_interest <- mf[,1][, mediator, drop = F]
#data frame
temp_mf[, 1] <- mediator_of_interest
colnames(temp_mf)[1] <- mediator
#terms attribute
if (!is.null(rownames(attr(attr(temp_mf, "terms"),'factors'))[1])){
rownames(attr(attr(temp_mf, "terms"),'factors'))[1] <- mediator
}
attr(attr(temp_mf, 'terms'),'dataClasses')[1] <- "numeric"
names(attr(attr(temp_mf, 'terms'),'dataClasses'))[1] <- mediator
return(temp_mf)
}
#print results to the console
print.result <- function(list_with_results, extra_title = NULL, final_results, list_name,
extra_list_name = NULL, skip_n_last_cols = 0, return_table_index = F,
print_effect_sizes = F){
check.if.tables.are.identical <- function(table1, table2){
rownames(table1) <- NULL
rownames(table2) <- NULL
return(identical(table1, table2))
}
print.table <- function(new_table, skip_n_last_cols, extra_title, prev_table = 0, i){
#BANOVA.mediation reports multiple tables for cases with multiple interacting factors.
#When a factor interacts with a continious variable the table reports results centered at
#zero of the continious variable, it is not relevant here
check.table.columns <- function(new_table, skip_n_last_cols){
remove_table <- F
n_columns <- ncol(new_table)
if (is.null(ncol(new_table))){
#if the table is a vector
n_cols_to_check <- length(new_table) - skip_n_last_cols
if (n_cols_to_check != 0){
for (j in 1:n_cols_to_check){
if (all(new_table[j] == '0') || all(new_table[j] == 0))
remove_table <- T
}
}
} else {
#otherwise
n_cols_to_check <- n_columns - skip_n_last_cols
for (j in 1:n_cols_to_check){
if (all(new_table[, j] == '0') || all(new_table[, j] == 0))
remove_table <- T
}
}
return(remove_table)
}
remove_table <- F
if (i > 1){
remove_table <- check.table.columns(new_table, skip_n_last_cols)
}
#if the table is not removed print it
if (!remove_table){
if (!check.if.tables.are.identical(prev_table, new_table)){
if(!is.null(extra_title)){
#if multiple tables are printed for one subsection (i.e. indirect effects)
# extra title is printed
cat(extra_title)
}
print(noquote(new_table), row.names = F, right=T)
if(!print_effect_sizes){
cat("\n")
}
}
}
return(list(remove_table = remove_table, prev_table = new_table))
}
results_list <- list()
num_tables <- length(list_with_results) #number of tables reported by BANOVA.mediation
prev_table <- 0
counter <- 1
used_tables_index <- c()
for (i in 1:num_tables){
#extract a table
new_table <- list_with_results[[i]]
table_name <- names(list_with_results)[i]
if (!is.null(table_name)){
table_name <- gsub("_", " ", table_name)
extra_title <- paste0(table_name, "\n")
} else {
extra_title <- NULL
}
#print a table
temp_result <- print.table(new_table, skip_n_last_cols, extra_title, prev_table, i)
#extract an indicator of whether the table was skipped or not
remove_table <- temp_result$remove_table
if (!remove_table){
#if the table is not skipped prepared it to be returned
if (!check.if.tables.are.identical(prev_table, new_table)){
if (print_effect_sizes){
cat("effect size:", intermediate_results[[mediator]]$effect_size[[i]])
cat("\n\n")
}
results_list[[counter]] <- new_table
used_tables_index <- c(used_tables_index, i)
if (num_tables > 1){
counter <- counter + 1
prev_table <- temp_result$prev_table
}
}
}
}
#Prepare final results
results_list_length <- length(results_list)
counter <- 1
for (i in 1:results_list_length){
if(!is.null(extra_list_name)){
if (results_list_length > 1){
final_results[[list_name]][[extra_list_name]][[counter]] <- results_list[[i]]
} else {
final_results[[list_name]][[extra_list_name]] <- results_list[[1]]
}
} else {
if (results_list_length > 1){
final_results[[list_name]][[counter]] <- results_list[[i]]
} else {
final_results[[list_name]] <- results_list[[1]]
}
}
counter <- counter + 1
}
if (return_table_index){
return(list(final_results = final_results, used_tables_index = used_tables_index))
} else {
return(final_results)
}
}
calculate.total.indirect.effects <- function(used_tables_index){
ind_eff_samples <- list()
#Exract relevant samples of indirect effects
for (mediator in mediators){
used_tables <- used_tables_index[[mediator]]
ind_eff_samples[[mediator]] <- intermediate_results[[mediator]]$indirect_effects_samples[used_tables]
}
num_tables <- length(used_tables_index[[1]])
total_indir_eff_samples_list <- list()
total_indir_eff_table_list <- list()
if (individual){
#for individual effects the samples must be extracted in a special way
for (i in 1:num_tables){
for (mediator in mediators){
temp <- ind_eff_samples[[mediator]][[i]]
temp_dim <- dim(temp)
row_counter <- c(1:temp_dim[1])
num_rows <- length(row_counter)
temp_smpl_indicator <- startsWith(colnames(temp), "s_")
ind_eff_samples_reshaped <- data.frame(matrix(NA, nrow = temp_dim[1]*temp_dim[3],
ncol = temp_dim[2]),
stringsAsFactors = F)
colnames(ind_eff_samples_reshaped) <- colnames(temp)
id <- c()
for(j in 1:temp_dim[3]){
selected_rows <- data.frame(temp[, , j, drop = F], stringsAsFactors = F)
colnames(selected_rows) <-colnames(temp)
#covert factors to numeric values
selected_rows[, temp_smpl_indicator] <- (sapply(selected_rows[, temp_smpl_indicator], as.numeric))
ind_eff_samples_reshaped[row_counter+num_rows*(j-1), ] <- selected_rows
id <- c(id, rep(j, num_rows))
}
ind_eff_samples[[mediator]][[i]] <- data.frame(id, ind_eff_samples_reshaped)
}
}
}
for (i in 1:num_tables){
ind_eff_num_samples <- c()
#Find common samples
for (mediator in mediators){
num_samples <- dim(ind_eff_samples[[mediator]][[i]])[2]
ind_eff_num_samples <- c(ind_eff_num_samples, num_samples)
}
common_samples <- min(ind_eff_num_samples)
#Prepare information to combine tables
#extract samples for first mediator
combined_table <- ind_eff_samples[[1]][[i]][, 1:common_samples]
#find column names of the columns with samples
smpl_indicator <- startsWith(colnames(combined_table), "s_")
smpl_columns <- colnames(combined_table)[smpl_indicator]
num_non_smpl_columns <- sum(!smpl_indicator) + 1
#find common columns
common_columns <- colnames(combined_table)[!smpl_indicator]
if ("(Intercept)" %in% common_columns){
common_columns <- common_columns[!common_columns %in% "(Intercept)"] #drop the intercept
}
for (n in 2:num_mediators){
common_columns <- intersect(common_columns, colnames(ind_eff_samples[[n]][[i]])[!smpl_indicator])
}
#Combine tables
for (n in 2:num_mediators){
temp_table1 <- combined_table[, 1:common_samples]
temp_table2 <- ind_eff_samples[[n]][[i]][, 1:common_samples]
combined_samples <- merge(temp_table1[, c(common_columns, smpl_columns)],
temp_table2[, c(common_columns, smpl_columns)],
by = common_columns)
temp1 <- combined_samples[, paste0(smpl_columns, ".x")]
temp2 <- combined_samples[, paste0(smpl_columns, ".y")]
combined_table[, num_non_smpl_columns:common_samples] <- temp1 + temp2
}
total_indirect_effects_samples <- combined_table[, c(smpl_columns)]
if(is.numeric(sol_1$data[, xvar])){
common_columns <- common_columns[common_columns != xvar]
}
num_common_columns <- length(common_columns)
#Prepare final results
total_indirect_effects <- data.frame(matrix(NA, nrow = nrow(combined_table), ncol = num_common_columns+4))
colnames(total_indirect_effects) <- c(common_columns, "mean","2.5%","97.5%","p.value")
total_indirect_effects[, 1:num_common_columns] <- combined_table[, common_columns]
total_indirect_effects[, "mean"] <- round(apply(total_indirect_effects_samples, 1, mean), 4)
quantiles <- round(apply(total_indirect_effects_samples, 1, quantile,
probs = c(0.025, 0.975), type = 3, na.rm = FALSE), 4)
total_indirect_effects[, "2.5%"] <- quantiles["2.5%",]
total_indirect_effects[, "97.5%"] <- quantiles["97.5%",]
p_values <- round(pValues(t(total_indirect_effects_samples)), 4)
total_indirect_effects[, "p.value"] <- apply(p_values, 1,
FUN = function(x) ifelse(x == 0, '<0.0001', x))
#Prepare the total indirect samples and results to be returned
temp_effects <- data.frame(combined_table[, common_columns], total_indirect_effects_samples)
colnames(temp_effects) <- c(common_columns, colnames(total_indirect_effects_samples))
if (individual){
temp_effects <- temp_effects[order(temp_effects$id),]
rownames(temp_effects) <- NULL
}
total_indir_eff_samples_list[[i]] <- temp_effects
total_indir_eff_table_list[[i]] <- total_indirect_effects
}
return(list(total_indirect_effects = total_indir_eff_table_list,
total_indirect_effects_samples = total_indir_eff_samples_list))
}
#arrange the direct effects outputted by BANOVA.medition into a data frame
prepare.direct.effects.df <- function(){
#Extract infromation about direct effects
dir_eff_list <- intermediate_results[[1]]$direct_effects_samples
dir_eff_list <- dir_eff_list[[length(dir_eff_list)]]
dir_effect_names <- dir_eff_list$index_name
dir_eff_samples <- dir_eff_list$samples
dim_dir_eff_samples <- dim(dir_eff_samples)
if(individual){
row_counter <- c(1:dim_dir_eff_samples[1])
num_rows <- length(row_counter)
dir_eff_samples_reshaped <- data.frame(matrix(NA, nrow = dim_dir_eff_samples[1]*dim_dir_eff_samples[3],
ncol = dim_dir_eff_samples[2]))
id <- c()
for(j in 1:dim_dir_eff_samples[3]){
selected_rows <- data.frame(dir_eff_samples[, , j])
#covert factors to numeric values
#selected_rows[, temp_smpl_indicator] <- lapply(selected_rows[, temp_smpl_indicator], as.numeric.factor)
#selected_rows[, temp_smpl_indicator] <- as.data.frame(sapply(selected_rows[, temp_smpl_indicator], as.numeric))
dir_eff_samples_reshaped[row_counter+num_rows*(j-1), ] <- selected_rows
id <- c(id, rep(j, num_rows))
}
dir_eff_samples_df <- data.frame(id, dir_eff_samples_reshaped)
} else {
dir_eff_samples_df <- data.frame(matrix(dir_eff_samples,
dim_dir_eff_samples[1]*dim_dir_eff_samples[2],
dim_dir_eff_samples[3]))
}
#Drop the intercept name
temp_colnames <- colnames(dir_effect_names)
if ("(Intercept)" %in% colnames(dir_effect_names)){
dir_effect_names <- dir_effect_names[,!colnames(dir_effect_names) %in% "(Intercept)", drop = F]
if (is.null(dim(dir_effect_names))){
dir_effect_names <- as.data.frame(as.matrix(dir_effect_names))
colnames(dir_effect_names) <- temp_colnames[!temp_colnames %in% "(Intercept)"]
}
}
dir_eff_samples_df <- data.frame(dir_effect_names, dir_eff_samples_df, stringsAsFactors = F)
return(dir_eff_samples_df)
}
#calculate total effects of a causal variable - not used.
#This function is correct only for sol_1 with Normal dependent variables
combine_direct_and_indirect_effects <- function(dir_eff_samples_df, total_indir_eff_samples_list){
total_eff_table_list <- list()
num_indir_eff_tables <- length(total_indir_eff_samples_list)
for (i in 1:num_indir_eff_tables){
indir_eff_samples_df <- data.frame(total_indir_eff_samples_list[[i]])
#find column names of the columns with samples based on indirect effects
smpl_indicator <- startsWith(colnames(indir_eff_samples_df), "s_")
smpl_col_names <- colnames(indir_eff_samples_df)[smpl_indicator]
#Find common samples
common_samples <- min(ncol(dir_eff_samples_df), ncol(indir_eff_samples_df))
dir_eff_samples_df <- dir_eff_samples_df[, 1:common_samples]
indir_eff_samples_df <- indir_eff_samples_df[, 1:common_samples]
#Prepare information to combine tables
colnames_dir_eff <- colnames(dir_eff_samples_df)
colnames_indir_eff <- colnames(indir_eff_samples_df)
common_columns <- intersect(colnames_dir_eff, colnames_indir_eff)
num_common_columns <- length(common_columns)
smpl_index <- (num_common_columns+1):common_samples
colnames(dir_eff_samples_df)[!colnames_dir_eff%in%common_columns] <-
colnames_indir_eff[!colnames_dir_eff%in%common_columns]
#Combine tables
total_effect_samples <- merge(dir_eff_samples_df, indir_eff_samples_df,
by = common_columns)
temp1 <- total_effect_samples[, paste0(smpl_col_names, ".x")]
temp2 <- total_effect_samples[, paste0(smpl_col_names, ".y")]
total_effect_samples[, smpl_index] <- temp1 + temp2
#Prepare final results
total_effects <- data.frame(matrix(NA, nrow = nrow(total_effect_samples), ncol = num_common_columns+4))
colnames(total_effects) <- c(common_columns, "mean","2.5%","97.5%","p.value")
total_effects[, 1:num_common_columns] <- total_effect_samples[, common_columns]
total_effects[, "mean"] <- round(apply(total_effect_samples[, smpl_index], 1, mean), 4)
quantiles <- round(apply(total_effect_samples[, smpl_index], 1, quantile,
probs = c(0.025, 0.975), type = 3, na.rm = FALSE), 4)
total_effects[, "2.5%"] <- quantiles["2.5%",]
total_effects[, "97.5%"] <- quantiles["97.5%",]
p_values <- round(pValues(t(total_effect_samples[, smpl_index])), 4)
total_effects[, "p.value"] <- apply(p_values, 1,
FUN = function(x) ifelse(x == 0, '<0.0001', x))
if (individual){
total_effects <- total_effects[order(total_effects$id),]
rownames(total_effects) <- NULL
}
total_eff_table_list[[i]] <- total_effects
}
return(total_eff_table_list)
}
#print tables with total (indirect) effects
print.tables.with.total.effects <- function(list_with_tables, num_tables){
for (i in 1:num_tables){
table <- list_with_tables[[i]]
print(noquote(table), row.names = F, right=T)
cat('\n')
}
}
#add tables with total (indirect) effects to the final return list
save.tables.with.total.effects <- function(list_with_tables, num_tables, final_list_name){
if (num_tables > 1){
final_results[[final_list_name]] <- list_with_tables
} else{
final_results[[final_list_name]] <- list_with_tables[[1]]
}
return(final_results)
}
#for tables with individual total (indirect) effects add an original id as a column
add.an.original.id <- function(list_with_tables, id_map, id_last = F){
for (i in 1:length(list_with_tables)){
table <- list_with_tables[[i]]
original_id <- id_map[table$id]
if(id_last){
table[, ncol(table)+1] <- original_id
table <- table[, !colnames(table) %in% "id"] #drop the first id
colnames(table)[ncol(table)] <- "id" #rename the last column
} else {
table$id <- original_id
}
list_with_tables[[i]] <- table
}
return(list_with_tables)
}
#####MAIN FUNCTION######
#Check the class of the model with multiple dependent variables
if(sol_2$model_name != "BANOVA.multiNormal")
stop('The mediator must follow the multivariate Normal distribution, use BANOVA multiNormal models instead.')
#Initialize variables
num_mediators <- length(mediators)
intermediate_results <- list()
final_results <- list()
#Adapt the output of BANOVA.multiNormal to fit BANOVA.mediation
temp_solution <- list()
temp_solution$samples_cutp_param <- sol_2$samples_cutp_param
temp_solution$data <- sol_2$data
temp_solution$num_trials <- sol_2$num_trials
temp_solution$model_code <- sol_2$model_code
temp_solution$single_level <- sol_2$single_level
temp_solution$stan_fit <- sol_2$stan_fit
temp_solution$contrast <- sol_2$contrast
temp_solution$new_id <- sol_2$new_id
temp_solution$old_id <- sol_2$old_id
temp_solution$call <- sol_2$call
temp_solution$model_name <- 'BANOVA.Normal'
temp_solution$samples_l2_sigma_param <- sol_2$samples_l2_sigma_param
class(temp_solution) <- "BANOVA"
names(sol_2$R2) <- names(sol_2$anova.tables.list)
names(sol_2$tau_ySq) <- names(sol_2$anova.tables.list)
for (mediator in mediators){
temp_solution$anova.table <- sol_2$anova.tables.list[[mediator]]
temp_solution$coef.tables <- sol_2$coef.tables.list[[mediator]]
temp_solution$pvalue.table <- sol_2$pvalue.tables.list[[mediator]]
temp_solution$conv <- sol_2$conv.list[[mediator]]
temp_solution$samples_l1_param <- sol_2$samples_l1.list[[mediator]]
temp_solution$samples_l2_param <- sol_2$samples_l2.list[[mediator]]
temp_solution$R2 <- sol_2$R2[[mediator]]
temp_solution$tau_ySq <- sol_2$tau_ySq[[mediator]]
temp_solution$dMatrice <- adapt.design.matrix(sol_2$dMatrice, mediator)
temp_solution$mf1 <- adapt.mf1(sol_2$mf1, mediator)
temp_solution$mf2 <- sol_2$mf2
if(individual){
stan_fit <- rstan::extract(sol_2$stan_fit, permuted = T)
if (sol_1$single_level || sol_2$single_level){
stop("It seems to be a between-subject design, set individual = FALSE instead.")
} else {
if (sol_2$single_level){
samples_beta1 <- stan_fit$beta1
} else {
samples_beta1 <- stan_fit$beta1[, , which(sol_2$names_of_dependent_variables == mediator), ]
}
dim_beta1 = dim(samples_beta1)
if (length(dim_beta1) == 2){
dim(samples_beta1) <- c(dim_beta1[1],dim_beta1[2],1)
}
sol <- BANOVA.mediation(sol_1, sol_2 = temp_solution, xvar=xvar, mediator=mediator,
individual = individual, return_posterior_samples = T,
multi_samples_beta1_raw_m = samples_beta1)
}
} else {
sol <- BANOVA.mediation(sol_1, sol_2 = temp_solution, xvar=xvar, mediator=mediator,
individual = individual, return_posterior_samples = T)
}
intermediate_results[[mediator]] <- sol
}
#####Individual effects - only for multilevel models#####
if(individual){
#calculate id map
id_map <- idmap(sol_1$old_id, sol_1$new_id)
used_tables_index <- list()
#######Prepare and save direct and indirect effects#######
cat(paste(strrep("-", 100), '\n'))
cat(paste("Indirect effects of the causal variable", xvar, "on the outcome variables\n\n"))
for (mediator in mediators){
#Individual direct effects of the causal variable on the outcome
final_results[["dir_effects"]][[mediator]] <- intermediate_results[[mediator]][["dir_effects"]]
final_results[["individual_direct"]][[mediator]] <- intermediate_results[[mediator]][["individual_direct"]]
#Individual direct effects of the mediator variables on the outcome
final_results[["m1_effects"]][[mediator]] <- intermediate_results[[mediator]][["m1_effects"]]
#Individual direct effects of the causal variable on mediator variables
final_results[["m2_effects"]][[mediator]] <- intermediate_results[[mediator]][["m2_effects"]]
#######Individual indirect effects of the causal variable#######
final_results[["indir_effects"]][[mediator]] <- intermediate_results[[mediator]][["indir_effects"]]
final_results[["individual_indirect"]][[mediator]] <- intermediate_results[[mediator]][["individual_indirect"]]
#######Report individual indirect effects of the causal variable#######
table_name <- names(intermediate_results[[mediator]]$indir_effects)
if (!is.null(table_name)){
string1 <- strsplit(table_name, xvar, fixed = F)[[1]][1]
string1 <- gsub("_", " ", string1)
string2 <- strsplit(table_name, mediator, fixed = F)[[1]][2]
string2 <- gsub("_", " ", string2)
table_name <- paste0(string1, xvar, " through ", mediator, string2, "\n")
}
temp_result <- print.result(list_with_results = intermediate_results[[mediator]]$individual_indirect,
final_results = final_results,
extra_title = table_name,
list_name = "individual_indirect", extra_list_name = mediator,
skip_n_last_cols = 6, return_table_index = T)
final_results[["individual_indirect"]][[mediator]] <- temp_result[[1]]$individual_indirect[[mediator]]
used_tables_index[[mediator]] <- temp_result$used_tables_index
final_results$effect_sizes[[mediator]] <- intermediate_results[[mediator]]$effect_size
}
#######Report total individual indirect effects of the causal variable#######
total_indirect_effects_results <- calculate.total.indirect.effects(used_tables_index)
num_tables_with_indirect_effects <- length(used_tables_index[[1]])
#add an original id to the table
total_indirect_effects_results$total_indirect_effects <-
add.an.original.id(total_indirect_effects_results$total_indirect_effects, id_map, T)
#print and save total individual indirect effects
cat(paste(strrep("-", 100), '\n'))
cat(paste("Total individual indirect effects of the causal variable", xvar,
"on the outcome variables\n\n"))
print.tables.with.total.effects(total_indirect_effects_results$total_indirect_effects,
num_tables_with_indirect_effects)
final_results <- save.tables.with.total.effects(total_indirect_effects_results$total_indirect_effects,
num_tables_with_indirect_effects,
"total_indir_effects")
} ######Genral effects#####
else{
#######Report direct effects of the causal variable on the outcome#######
cat(paste(strrep("-", 100), '\n'))
cat(paste("Direct effects of the causal variable", xvar, "on the outcome variable\n\n"))
final_results <- print.result(list_with_results = intermediate_results[[1]]$dir_effect,
final_results = final_results,
list_name = "dir_effects", skip_n_last_cols = 3)
#######Report direct effects of the mediator variables on the outcome#######
mediator_names <- paste(mediators, collapse=" and ")
cat(paste(strrep("-", 100), '\n'))
cat(paste("Direct effects of mediators", mediator_names, "on the outcome variable\n\n"))
for (mediator in mediators){
final_results <- print.result(list_with_results = intermediate_results[[mediator]]$m1_effects,
final_results = final_results,
list_name = "m1_effects", extra_list_name = mediator,
skip_n_last_cols = 3)
}
#######Report direct effects of the causal variable on mediator variables#######
cat(paste(strrep("-", 100), '\n'))
cat(paste("Direct effects of the causal variable", xvar, "on the mediator variables\n\n"))
for (mediator in mediators){
final_results <- print.result(list_with_results = intermediate_results[[mediator]]$m2_effects,
final_results = final_results,
list_name = "m2_effects", extra_list_name = mediator,
skip_n_last_cols = 3)
}
#######Report indirect effects of the causal variable and effect size#######
cat(paste(strrep("-", 100), '\n'))
cat(paste("Indirect effects of the causal variable", xvar, "on the outcome variables\n\n"))
used_tables_index <- list()
for (mediator in mediators){
temp_result <- print.result(list_with_results = intermediate_results[[mediator]]$indir_effects,
final_results = final_results,
list_name = "indir_effects", extra_list_name = mediator,
skip_n_last_cols = 3, return_table_index = T,
print_effect_sizes = T)
final_results <- temp_result$final_results
used_tables_index[[mediator]] <- temp_result$used_tables_index
final_results$effect_sizes[[mediator]] <-
intermediate_results[[mediator]]$effect_size[temp_result$used_tables_index]
}
#######Report total indirect effects of the causal variable#######
total_indirect_effects_results <- calculate.total.indirect.effects(used_tables_index)
num_tables_with_indirect_effects <- length(used_tables_index[[1]])
cat(paste(strrep("-", 100), '\n'))
cat(paste("Total indirect effects of the causal variable", xvar,
"on the outcome variables\n\n"))
print.tables.with.total.effects(total_indirect_effects_results$total_indirect_effects,
num_tables_with_indirect_effects)
final_results <- save.tables.with.total.effects(total_indirect_effects_results$total_indirect_effects,
num_tables_with_indirect_effects,
"total_indir_effects")
}
final_results$xvar <- xvar
final_results$mediators <- mediators
final_results$individual <- individual
class(final_results) <- 'BANOVA.multi.mediation'
return(final_results)
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/BANOVA.multi.mediation.R |
BANOVA.ordMultiNormal <-
function(l1_formula = 'NA', l2_formula = 'NA', data, id, l1_hyper, l2_hyper, burnin, sample, thin, adapt, conv_speedup, jags){
cat('Model initializing...\n')
if (l1_formula == 'NA'){
stop("Formula in level 1 is missing or not correct!")
}else{
mf1 <- model.frame(formula = l1_formula, data = data)
y <- model.response(mf1)
# check y, if it is integers
if (!inherits(y, 'integer')){
warning("The response variable must be integers (data class also must be 'integer')..")
y <- as.integer(as.character(y))
warning("The response variable has been converted to integers..")
}
}
single_level = F
if (l2_formula == 'NA'){
single_level = T
DV_sort <- sort(unique(y))
n_categories <- length(DV_sort)
if (n_categories < 3) stop('The number of categories must be greater than 2!')
if (DV_sort[1] != 1 || DV_sort[n_categories] != n_categories) stop('Check if response variable follows categorical distribution!')
n.cut <- n_categories - 1
# check each column in the dataframe should have the class 'factor' or 'numeric', no other classes such as 'matrix'...
for (i in 1:ncol(data)){
if(!inherits(data[,i], 'factor') && !inherits(data[,i], 'numeric') && !inherits(data[,i], 'integer')) stop("data class must be 'factor', 'numeric' or 'integer'")
# checking numerical predictors, converted to categorical variables if the number of levels is <= 3
if ((inherits(data[,i], 'numeric') | inherits(data[,i], 'integer')) & length(unique(data[,i])) <= 3){
data[,i] <- as.factor(data[,i])
warning("Variables(levels <= 3) have been converted to factors")
}
}
n <- nrow(data)
uni_id <- unique(id)
num_id <- length(uni_id)
new_id <- rep(0, length(id)) # store the new id from 1,2,3,...
for (i in 1:length(id))
new_id[i] <- which(uni_id == id[i])
id <- new_id
dMatrice <- design.matrix(l1_formula, l2_formula, data = data, id = id)
JAGS.model <- JAGSgen.ordmultiNormal(dMatrice$X, dMatrice$Z, n.cut, l1_hyper, l2_hyper, conv_speedup)
JAGS.data <- dump.format(list(n = n, y = y, X = dMatrice$X, n.cut = n.cut))
result <- run.jags (model = JAGS.model$sModel, data = JAGS.data, inits = JAGS.model$inits, n.chains = 1,
monitor = c(JAGS.model$monitorl1.parameters, JAGS.model$monitorl2.parameters, JAGS.model$monitor.cutp),
burnin = burnin, sample = sample, thin = thin, adapt = adapt, jags = jags, summarise = FALSE,
method="rjags")
samples <- result$mcmc[[1]]
# find the correct samples, in case the order of monitors is shuffled by JAGS
n_p_l1 <- length(JAGS.model$monitorl1.parameters)
index_l1_param<- array(0,dim = c(n_p_l1,1))
for (i in 1:n_p_l1)
index_l1_param[i] <- which(colnames(result$mcmc[[1]]) == JAGS.model$monitorl1.parameters[i])
if (length(index_l1_param) > 1)
samples_l1_param <- result$mcmc[[1]][,index_l1_param]
else
samples_l1_param <- matrix(result$mcmc[[1]][,index_l1_param], ncol = 1)
colnames(samples_l1_param) <- colnames(result$mcmc[[1]])[index_l1_param]
n_p_cutp <- length(JAGS.model$monitor.cutp)
index_cutp_param<- array(0,dim = c(n_p_cutp,1))
for (i in 1:n_p_cutp)
index_cutp_param[i] <- which(colnames(result$mcmc[[1]]) == JAGS.model$monitor.cutp[i])
if (length(index_cutp_param) > 1)
samples_cutp_param <- result$mcmc[[1]][,index_cutp_param]
else
samples_cutp_param <- matrix(result$mcmc[[1]][,index_cutp_param], ncol = 1)
cat('Constructing ANOVA/ANCOVA tables...\n')
dMatrice$Z <- array(1, dim = c(1,1), dimnames = list(NULL, ' '))
attr(dMatrice$Z, 'assign') <- 0
attr(dMatrice$Z, 'varNames') <- " "
samples_l2_param <- NULL
anova.table <- table.ANCOVA(samples_l2_param, dMatrice$Z, dMatrice$X, samples_l1_param, error = pi^2/6) # for ancova models
coef.tables <- table.coefficients(samples_l1_param, JAGS.model$monitorl1.parameters, colnames(dMatrice$Z), colnames(dMatrice$X),
attr(dMatrice$Z, 'assign') + 1, attr(dMatrice$X, 'assign') + 1, samples_cutp_param)
pvalue.table <- table.pvalue(coef.tables$coeff_table, coef.tables$row_indices, l1_names = attr(dMatrice$Z, 'varNames'),
l2_names = attr(dMatrice$X, 'varNames'))
conv <- conv.geweke.heidel(samples_l1_param, colnames(dMatrice$Z), colnames(dMatrice$X))
mf2 <- NULL
class(conv) <- 'conv.diag'
cat('Done.\n')
}else{
mf2 <- model.frame(formula = l2_formula, data = data)
DV_sort <- sort(unique(y))
n_categories <- length(DV_sort)
if (n_categories < 2) stop('The number of categories must be greater than 1!')
if (DV_sort[1] != 1 || DV_sort[n_categories] != n_categories) stop('Check if response variable follows categorical distribution!')
n.cut <- n_categories - 1
# check each column in the dataframe should have the class 'factor' or 'numeric', no other classes such as 'matrix'...
for (i in 1:ncol(data)){
if(!inherits(data[,i], 'factor') && !inherits(data[,i], 'numeric') && !inherits(data[,i], 'integer')) stop("data class must be 'factor', 'numeric' or 'integer'")
#response_name <- attr(mf1,"names")[attr(attr(mf1, "terms"),"response")]
# checking missing predictors, already checked in design matrix
# if(i != which(colnames(data) == response_name) & sum(is.na(data[,i])) > 0) stop("Data type error, NAs/missing values included in independent variables")
#if(i != which(colnames(data) == response_name) & class(data[,i]) == 'numeric')
# data[,i] = data[,i] - mean(data[,i])
# checking numerical predictors, converted to categorical variables if the number of levels is <= 3
if ((inherits(data[,i], 'numeric') | inherits(data[,i], 'integer')) & length(unique(data[,i])) <= 3){
data[,i] <- as.factor(data[,i])
warning("Variables(levels <= 3) have been converted to factors")
}
}
n <- nrow(data)
uni_id <- unique(id)
num_id <- length(uni_id)
new_id <- rep(0, length(id)) # store the new id from 1,2,3,...
for (i in 1:length(id))
new_id[i] <- which(uni_id == id[i])
id <- new_id
dMatrice <- design.matrix(l1_formula, l2_formula, data = data, id = id)
JAGS.model <- JAGSgen.ordmultiNormal(dMatrice$X, dMatrice$Z, n.cut, l2_hyper = l2_hyper, conv_speedup = conv_speedup)
JAGS.data <- dump.format(list(n = n, id = id, M = num_id, y = y, X = dMatrice$X, Z = dMatrice$Z, n.cut = n.cut))
result <- run.jags (model = JAGS.model$sModel, data = JAGS.data, inits = JAGS.model$inits, n.chains = 1,
monitor = c(JAGS.model$monitorl1.parameters, JAGS.model$monitorl2.parameters, JAGS.model$monitor.cutp),
burnin = burnin, sample = sample, thin = thin, adapt = adapt, jags = jags, summarise = FALSE,
method="rjags")
samples <- result$mcmc[[1]]
# find the correct samples, in case the order of monitors is shuffled by JAGS
n_p_l2 <- length(JAGS.model$monitorl2.parameters)
index_l2_param<- array(0,dim = c(n_p_l2,1))
for (i in 1:n_p_l2)
index_l2_param[i] <- which(colnames(result$mcmc[[1]]) == JAGS.model$monitorl2.parameters[i])
if (length(index_l2_param) > 1)
samples_l2_param <- result$mcmc[[1]][,index_l2_param]
else
samples_l2_param <- matrix(result$mcmc[[1]][,index_l2_param], ncol = 1)
colnames(samples_l2_param) <- colnames(result$mcmc[[1]])[index_l2_param]
n_p_l1 <- length(JAGS.model$monitorl1.parameters)
index_l1_param<- array(0,dim = c(n_p_l1,1))
for (i in 1:n_p_l1)
index_l1_param[i] <- which(colnames(result$mcmc[[1]]) == JAGS.model$monitorl1.parameters[i])
if (length(index_l1_param) > 1)
samples_l1_param <- result$mcmc[[1]][,index_l1_param]
else
samples_l1_param <- matrix(result$mcmc[[1]][,index_l1_param], ncol = 1)
colnames(samples_l1_param) <- colnames(result$mcmc[[1]])[index_l1_param]
n_p_cutp <- length(JAGS.model$monitor.cutp)
index_cutp_param<- array(0,dim = c(n_p_cutp,1))
for (i in 1:n_p_cutp)
index_cutp_param[i] <- which(colnames(result$mcmc[[1]]) == JAGS.model$monitor.cutp[i])
if (length(index_cutp_param) > 1)
samples_cutp_param <- result$mcmc[[1]][,index_cutp_param]
else
samples_cutp_param <- matrix(result$mcmc[[1]][,index_cutp_param], ncol = 1)
#anova.table <- table.ANOVA(samples_l1_param, dMatrice$X, dMatrice$Z)
cat('Constructing ANOVA/ANCOVA tables...\n')
anova.table <- table.ANCOVA(samples_l1_param, dMatrice$X, dMatrice$Z, samples_l2_param) # for ancova models
coef.tables <- table.coefficients(samples_l2_param, JAGS.model$monitorl2.parameters, colnames(dMatrice$X), colnames(dMatrice$Z),
attr(dMatrice$X, 'assign') + 1, attr(dMatrice$Z, 'assign') + 1, samples_cutp_param)
pvalue.table <- table.pvalue(coef.tables$coeff_table, coef.tables$row_indices, l1_names = attr(dMatrice$X, 'varNames'),
l2_names = attr(dMatrice$Z, 'varNames'))
conv <- conv.geweke.heidel(samples_l2_param, colnames(dMatrice$X), colnames(dMatrice$Z))
class(conv) <- 'conv.diag'
cat('Done...\n')
}
return(list(anova.table = anova.table,
coef.tables = coef.tables,
pvalue.table = pvalue.table,
conv = conv,
dMatrice = dMatrice, samples_l1_param = samples_l1_param, samples_l2_param = samples_l2_param, samples_cutp_param = samples_cutp_param, data = data,
mf1 = mf1, mf2 = mf2,JAGSmodel = JAGS.model$sModel, single_level = single_level, model_name = "BANOVA.ordMultinomial"))
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/BANOVA.ordMultiNormal.R |
BANOVA.ordMultinomial<-
function(l1_formula = 'NA', l2_formula = 'NA', data, id, l1_hyper = c(0.0001, 100), l2_hyper = c(1,1,0.0001,100), burnin = 5000, sample = 2000, thin = 10, adapt = 0, conv_speedup = F, jags = runjags.getOption('jagspath')){
# if (jags == 'JAGS not found') stop('Please install the JAGS software (Version 3.4 or above). Check http://mcmc-jags.sourceforge.net/')
sol <- BANOVA.ordMultiNormal(l1_formula, l2_formula, data, id, l1_hyper = l1_hyper, l2_hyper = l2_hyper, burnin = burnin, sample = sample, thin = thin, adapt = adapt, conv_speedup = conv_speedup, jags = jags)
sol$call <- match.call()
class(sol) <- 'BANOVA.ordMultinomial'
sol
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/BANOVA.ordMultinomial.R |
#' run a BANOVA model
#'
#' @return A BANOVA stan model.
#'
#' @examples
#' \dontrun{
#'
#' }
#'
BANOVA.run <- function (l1_formula = 'NA',
l2_formula = 'NA',
fit = NULL, # BANOVA.build object, if it is specified, then directly use the stan model included
model_name = 'NA',
dataX = NULL,
dataZ = NULL,
data = NULL,
y_value = NULL,
id,
iter = 2000,
num_trials = 1,
contrast = NULL, # 1.1.2
y_lowerBound = -Inf,
y_upperBound = Inf,
...
){
# auxiliary function for conversion of effect or dummy coded numeric vectors to factors
convert.numeric.2.factor <- function(data_vec){
levels <- unique(data_vec)
dummy_condition <- (length(levels) == 2) && (0 %in% levels) && (1 %in% levels)
effect_condition <- sum(levels) == 0
if (effect_condition || dummy_condition){
#if factors are effect or dummy coded, levels count from the postive to negative values,
# so (1, 0, -1) or (1, 0), where "1" is level 1, "0" is level 2, and "-1" is level 3
lvl <- as.numeric(sort(levels, decreasing = T))
data_vec <- factor(data_vec, levels = lvl, labels = lvl)
} else {
data_vec <- as.factor(data_vec)
}
return(data_vec)
}
check.numeric.variables <- function(y_var){
if (!inherits(y_var, 'numeric')){
warning("The response variable must be numeric (data class also must be 'numeric')")
y_var <- as.numeric(y_var)
warning("The response variable has been converted to numeric")
}
return(y_var)
}
# data sanity check
if (!is.null(data)){
if (!is.data.frame(data)) stop("data needs to be a data frame!")
}
if (l1_formula == 'NA'){
stop("Formula in level 1 is missing or not correct!")
}else{
single_level = F
if (is(fit, "BANOVA.build"))
model_name = fit$model_name
# validate y
if (model_name == 'Multinomial'){
if (is.null(y_value)) stop("y_value (the dependent variable) must be provided!")
y <- y_value
mf1 <- model.frame(formula = l1_formula, data = dataX[[1]])
}else{
mf1 <- model.frame(formula = l1_formula, data = data)
y <- model.response(mf1)
}
if (model_name %in% c('Normal', 'T')){
y <- check.numeric.variables(y)
}else if (model_name %in% c('Poisson', 'Binomial', 'Bernoulli', 'Multinomial', 'ordMultinomial')){
if (!inherits(y, 'integer')){
warning("The response variable must be integers (data class also must be 'integer')..")
y <- as.integer(as.character(y))
warning("The response variable has been converted to integers..")
}
if (model_name == 'ordMultinomial'){
DV_sort <- sort(unique(y))
n_categories <- length(DV_sort)
if (n_categories < 3) stop('The number of categories must be greater than 2!')
if (DV_sort[1] != 1 || DV_sort[n_categories] != n_categories) stop('Check if response variable follows categorical distribution!')
n.cut <- n_categories - 1
}
if (model_name == 'Multinomial'){
DV_sort <- sort(unique(y))
n_categories <- length(DV_sort)
if (n_categories < 3) stop('The number of categories must be greater than 2!')
if (DV_sort[1] != 1 || DV_sort[n_categories] != n_categories) stop('Check if response variable follows categorical distribution!')
}
} else if (model_name == "multiNormal") {
if (is.null(ncol(y))) stop('The number of dependent variables must be greater than 1!')
if (is.null(colnames(y))) stop(paste0('Please, specify the names of dependent variables!\n',
'See Examples in help(BANOVA.run) for the expected specification of the dependent variables.'))
num_dv <- ncol(y)
for (l in 1:num_dv){
y[,l] <- check.numeric.variables(y[,l])
}
} else if (model_name == 'truncNormal'){
y <- check.numeric.variables(y)
#check the specified bounds
if (y_lowerBound > y_upperBound){
stop(paste0("The lower bound should be below upper bound!\n",
"Current lower bound of y is ", y_lowerBound, ", and upper bound is ", y_upperBound))
}
if (y_lowerBound == y_upperBound){
stop(paste0("The lower bound should be different from upper bound!\n",
"Current lower bound of y is ", y_lowerBound, ", and upper bound is ", y_upperBound))
}
#check if there is an unbounded tail
no_lower_bound = 0
no_upper_bound = 0
if (y_lowerBound == -Inf) no_lower_bound = 1
if (y_upperBound == Inf) no_upper_bound = 1
if (no_lower_bound == 1 & no_upper_bound == 1){
stop(paste0("If the dependent variable is unbounded, please use Normal distributoin!\n",
"Current lower bound of y is ", y_lowerBound, ", and upper bound is ", y_upperBound))
}
#check the values of the dependent variable
min_y <- min(y)
max_y <- max(y)
if (min_y < y_lowerBound){
stop(paste0("At least one value of the dependent variable exceeds the specified lower bound!\n",
"The lowest value of y is ", min_y, ", while specified lower bound is ", y_lowerBound))
}
if (max_y > y_upperBound){
stop(paste0("At least one value of the dependent variable exceeds the specified upper bound!\n",
"The highest value of y is ", max_y, ", while specified lower bound is ", y_upperBound))
}
#check how well the boundaries cover the data
three_sd_y <- 3*sd(y)
if(y_lowerBound!=(-Inf) && y_lowerBound<(min_y-three_sd_y)){
warning("The specified lower bound is more than three standard deviations away from the lowest value of y.\nThis may cause problems with initialization of starting values in the MCMC chains.")
}
if(y_upperBound!=(Inf) && y_upperBound>(max_y+three_sd_y)){
warning("The specified upper bound is more than three standard deviations away from the highest value of y.\nThis may cause problems with initialization of starting values in the MCMC chains.")
}
} else{
stop(model_name, " is not supported currently!")
}
}
if (is.character(id) && length(id) == 1){
if (id %in% colnames(data))
old_id = data[, id]
else
stop(id, ' is not found in the input data, please assign values directly!')
}else{
if (model_name != 'Multinomial') {
stop('id ambiguous!')
}else{
old_id = id
}
}
if (l2_formula == 'NA'){
# single level models
single_level = T
if (is(fit, "BANOVA.build")){
fit_single_level = fit$single_level
if (single_level != fit_single_level) stop("Please check the single level settings(T/F)!")
}
if (model_name == "Multinomial"){
# check each column in the dataframe should have the class 'factor' or 'numeric', no other classes such as 'matrix'...
# for (i in 1:ncol(dataZ)){
# if(class(dataZ[,i]) != 'factor' && class(dataZ[,i]) != 'numeric' && class(dataZ[,i]) != 'integer') stop("data class must be 'factor', 'numeric' or 'integer'")
# if ((class(dataZ[,i]) == 'numeric' | class(dataZ[,i]) == 'integer') & length(unique(dataZ[,i])) <= 3){
# dataZ[,i] <- as.factor(dataZ[,i])
# warning("Between-subject variables(levels <= 3) have been converted to factors")
# }
# }
for (i in 1:length(dataX))
for (j in 1:ncol(dataX[[i]])){
if(!inherits(dataX[[i]][,j], 'factor') && !inherits(dataX[[i]][,j], 'numeric') && !inherits(dataX[[i]][,j], 'integer')) stop("data class must be 'factor', 'numeric' or 'integer'")
if ((inherits(dataX[[i]][,j], 'numeric') | inherits(dataX[[i]][,j], 'integer')) & length(unique(dataX[[i]][,j])) <= 3){
#convert the column to factors
dataX[[i]][,j] <- convert.numeric.2.factor(dataX[[i]][,j])
warning("Within-subject variables(levels <= 3) have been converted to factors")
}
}
n <- length(dataX)
uni_id <- unique(old_id)
num_id <- length(uni_id)
new_id <- rep(0, length(old_id)) # store the new id from 1,2,3,...
for (i in 1:length(old_id))
new_id[i] <- which(uni_id == old_id[i])
id <- new_id
dMatrice <- multi.design.matrix(l1_formula, l2_formula, dataX = dataX, id = id)
# create 3-dimensional matrix of X for stan data
X_new <- array(0, dim = c(n, n_categories, ncol(dMatrice$X_full[[1]])))
for (i in 1:n_categories){
X_new[,i,] <- dMatrice$X_full[[i]]
}
pooled_data_dict <- list(N = dim(X_new)[1],
J = dim(X_new)[3],
n_cat = dim(X_new)[2],
X = X_new,
y = y)
if (!is(fit, "BANOVA.build")){
fit <- get_BANOVA_stan_model(model_name, single_level)
}else{
# overwrite the model name and single level using the attributes from the fit
model_name <- fit$model_name
single_level <- fit$single_level
}
#library(rstan)
stan.fit <- rstan::sampling(fit$stanmodel, data = pooled_data_dict, iter=iter, ...)
### find samples ###
# beta1 J
fit_beta <- rstan::extract(stan.fit, permuted = T)
R2 = NULL
tau_ySq = NULL
beta1_dim <- dim(fit_beta$beta1)
beta1_names <- c()
for (i in 1:beta1_dim[2]) #J
beta1_names <- c(beta1_names, paste("beta1_",i, sep = ""))
samples_l1_param <- array(0, dim = c(beta1_dim[1], beta1_dim[2]), dimnames = list(NULL, beta1_names))
for (i in 1:beta1_dim[2])
samples_l1_param[, i] <- fit_beta$beta1[, i]
samples_l2_sigma_param = NA
samples_cutp_param = array(dim = 0)
cat('Constructing ANOVA/ANCOVA tables...\n')
dMatrice$Z <- array(1, dim = c(1,1), dimnames = list(NULL, ' '))
attr(dMatrice$Z, 'assign') <- 0
attr(dMatrice$Z, 'varNames') <- " "
samples_l2_param <- NULL
# print one table for each alternative
anova.table <- list()
for (i in 1:n_categories)
anova.table[[i]] <- table.ANCOVA(samples_l2_param, dMatrice$Z, dMatrice$X_full[[i]], samples_l1_param, error = pi^2/6, multi = T, n_cat = n_categories, choice = i-1, y_val = y_value, model = model_name) #intercept_1 doesn't exist
coef.tables <- table.coefficients(samples_l1_param, beta1_names, colnames(dMatrice$Z), colnames(dMatrice$X_full[[1]]),
attr(dMatrice$Z, 'assign') + 1, attr(dMatrice$X_full[[1]], 'assign'), samples_cutp_param )
pvalue.table <- table.pvalue(coef.tables$coeff_table, coef.tables$row_indices, l1_names = attr(dMatrice$Z, 'varNames'),
l2_names = attr(dMatrice$X_full[[1]], 'varNames'))
conv <- conv.geweke.heidel(samples_l1_param, colnames(dMatrice$Z), colnames(dMatrice$X_full[[1]]))
}else{
#check only relevant columns
data_colnames <- colnames(data)
var_names <- colnames(mf1)[-1]# exclude dv, as it was checked before
# check each column in the dataframe should have the class 'factor' or 'numeric', no other classes such as 'matrix'...
for (i in 1:ncol(data)){
if (data_colnames[i] %in% var_names){
if(!inherits(data[,i], 'factor') && !inherits(data[,i], 'numeric') && !inherits(data[,i], 'integer')) stop("data class must be 'factor', 'numeric' or 'integer'")
# checking numerical predictors, converted to categorical variables if the number of levels is <= 3
if ((inherits(data[,i], 'numeric') | inherits(data[,i], 'integer')) & length(unique(data[,i])) <= 3){
#convert the column to factors
data[,i] <- convert.numeric.2.factor(data[,i])
warning("Variables(levels <= 3) have been converted to factors")
}
}
}
n <- nrow(data)
uni_id <- unique(old_id)
num_id <- length(uni_id)
new_id <- rep(0, length(old_id)) # store the new id from 1,2,3,...
for (i in 1:length(old_id))
new_id[i] <- which(uni_id == old_id[i])
id <- new_id
dMatrice <- design.matrix(l1_formula, l2_formula, data = data, id = id, contrast = contrast)
if (model_name == "Binomial"){
trials <- num_trials
if (length(trials) == 1) trials <- rep(num_trials, n)
if (length(trials) != n) stop('The length of num_trials must be equal to the number of observations!')
# handle missing values
if (sum(y > num_trials, na.rm = T) > 0) stop('The number of trials is less than observations!')
pooled_data_dict <- list(N = nrow(dMatrice$X),
J = ncol(dMatrice$X),
trials = trials,
X = dMatrice$X,
y = y)
}else if (model_name == "ordMultinomial"){
pooled_data_dict <- list(cat = n.cut + 1,
N = nrow(dMatrice$X),
J = ncol(dMatrice$X),
X = dMatrice$X,
Z = dMatrice$Z,
y = y)
}else if (model_name == 'multiNormal'){
pooled_data_dict <- list(L = num_dv,
N = nrow(dMatrice$X),
J = ncol(dMatrice$X),
X = dMatrice$X,
y = y)
}else if (model_name == 'truncNormal'){
pooled_data_dict <- list(L = y_lowerBound,
U = y_upperBound,
no_lower_bound = no_lower_bound,
no_upper_bound = no_upper_bound,
N = nrow(dMatrice$X),
J = ncol(dMatrice$X),
X = dMatrice$X,
y = y)
}else{
pooled_data_dict <- list(N = nrow(dMatrice$X),
J = ncol(dMatrice$X),
X = dMatrice$X,
y = y)
}
if (!is(fit, "BANOVA.build")){
fit <- get_BANOVA_stan_model(model_name, single_level)
}else{
# overwrite the model name and single level using the attributes from the fit
model_name <- fit$model_name
single_level <- fit$single_level
}
stan.fit <- rstan::sampling(fit$stanmodel, data = pooled_data_dict, iter=iter, ...)
### find samples ###
# beta1 J
fit_beta <- rstan::extract(stan.fit, permuted = T)
if (model_name != "multiNormal"){
# For R2 of models with Normal distribution
R2 = NULL
if (!is.null(fit_beta$r_2)){
R2 <- mean(fit_beta$r_2)
R2 <- round(R2, 4)
}
# For the calculation of effect sizes in mediation
tau_ySq = NULL
beta1_dim <- dim(fit_beta$beta1)
beta1_names <- c()
for (i in 1:beta1_dim[2]) #J
beta1_names <- c(beta1_names, paste("beta1_",i, sep = ""))
samples_l1_param <- array(0, dim = c(beta1_dim[1], beta1_dim[2]), dimnames = list(NULL, beta1_names))
for (i in 1:beta1_dim[2])
samples_l1_param[, i] <- fit_beta$beta1[, i]
samples_l2_sigma_param = NA
if (model_name == 'Poisson'){
samples_l2_sigma_param <- 0
}
samples_cutp_param = array(dim = 0)
if (model_name == 'ordMultinomial'){
c_dim <- dim(fit_beta$c_trans)
c_names <- c()
for (i in 2:c_dim[2])
c_names <- c(c_names, paste("c",i, sep = "_"))
# c_trans[1] == 0
samples_cutp_param <- array(0, dim = c(c_dim[1], c_dim[2] - 1), dimnames = list(NULL, c_names))
for (i in 2:c_dim[2])
samples_cutp_param[, i-1] <- fit_beta$c_trans[,i]
}
cat('Constructing ANOVA/ANCOVA tables...\n')
dMatrice$Z <- array(1, dim = c(1,1), dimnames = list(NULL, ' '))
attr(dMatrice$Z, 'assign') <- 0
attr(dMatrice$Z, 'varNames') <- " "
samples_l2_param <- NULL
if (model_name == 'Poisson'){
anova.table <- table.ANCOVA(samples_l2_param, dMatrice$Z, dMatrice$X, samples_l1_param, y_val = array(y, dim = c(length(y), 1)), error = pi^2/3, model = model_name)
}else if (model_name %in% c('Normal', 'T', 'truncNormal')){
anova.table <- table.ANCOVA(samples_l2_param, dMatrice$Z, dMatrice$X, samples_l1_param, array(y, dim = c(length(y), 1)), model = model_name) # for ancova models
if (!is.null(fit_beta$tau_ySq)){
tau_ySq <- mean(fit_beta$tau_ySq)
}
}else if (model_name == 'Bernoulli' || model_name == 'Binomial'){
anova.table <- table.ANCOVA(samples_l2_param, dMatrice$Z, dMatrice$X, samples_l1_param, y_val = array(y, dim = c(length(y), 1)), error = pi^2/3, num_trials = num_trials, model = model_name)
tau_ySq = pi^2/3
}else if (model_name == 'ordMultinomial'){
anova.table <- table.ANCOVA(samples_l2_param, dMatrice$Z, dMatrice$X, samples_l1_param, y_val = array(y, dim = c(length(y), 1)), error = pi^2/6, model = model_name)
tau_ySq = pi^2/6
}
coef.tables <- table.coefficients(samples_l1_param, beta1_names, colnames(dMatrice$Z), colnames(dMatrice$X),
attr(dMatrice$Z, 'assign') + 1, attr(dMatrice$X, 'assign') + 1, samples_cutp_param )
pvalue.table <- table.pvalue(coef.tables$coeff_table, coef.tables$row_indices, l1_names = attr(dMatrice$Z, 'varNames'),
l2_names = attr(dMatrice$X, 'varNames'))
conv <- conv.geweke.heidel(samples_l1_param, colnames(dMatrice$Z), colnames(dMatrice$X))
mf2 <- NULL
class(conv) <- 'conv.diag'
cat('Done.\n')
} else {
dMatrice$Z <- array(1, dim = c(1,1), dimnames = list(NULL, ' '))
attr(dMatrice$Z, 'assign') <- 0
attr(dMatrice$Z, 'varNames') <- " "
mlvResult <- results.BANOVA.mlvNormal(fit_beta, dep_var_names = colnames(y), dMatrice, single_level)
mf2 = NULL
}
}
}else{
if (model_name == "Multinomial"){
if (is.null(dataX) || is.null(dataZ)) stop("dataX or dataZ must be specified!")
mf1 <- model.frame(formula = l1_formula, data = dataX[[1]])
mf2 <- model.frame(formula = l2_formula, data = dataZ)
# check each column in the dataframe should have the class 'factor' or 'numeric', no other classes such as 'matrix'...
for (i in 1:ncol(dataZ)){
if(!inherits(dataZ[,i], 'factor') && !inherits(dataZ[,i], 'numeric') && !inherits(dataZ[,i], 'integer')) stop("data class must be 'factor', 'numeric' or 'integer'")
# checking numerical predictors, converted to categorical variables if the number of levels is <= 3
if ((inherits(dataZ[,i], 'numeric') | inherits(dataZ[,i], 'integer')) & length(unique(dataZ[,i])) <= 3){
#convert the column to factors
dataZ[,i] <- convert.numeric.2.factor(dataZ[,i])
warning("Between-subject variables(levels <= 3) have been converted to factors")
}
}
for (i in 1:length(dataX))
for (j in 1:ncol(dataX[[i]])){
if(!inherits(dataX[[i]][,j], 'factor') && !inherits(dataX[[i]][,j], 'numeric') && !inherits(dataX[[i]][,j], 'integer')) stop("data class must be 'factor', 'numeric' or 'integer'")
# checking numerical predictors, converted to categorical variables if the number of levels is <= 3
if ((inherits(dataX[[i]][,j], 'numeric') | inherits(dataX[[i]][,j], 'integer')) & length(unique(dataX[[i]][,j])) <= 3){
#convert the column to factors
dataX[[i]][,j] <- convert.numeric.2.factor(dataX[[i]][,j])
warning("Within-subject variables(levels <= 3) have been converted to factors")
}
}
n <- nrow(dataZ)
uni_id <- unique(old_id)
num_id <- length(uni_id)
new_id <- rep(0, length(old_id)) # store the new id from 1,2,3,...
for (i in 1:length(old_id))
new_id[i] <- which(uni_id == old_id[i])
id <- new_id
dMatrice <- multi.design.matrix(l1_formula, l2_formula, dataX = dataX, dataZ = dataZ, id = id)
# create 3-dimensional matrix of X for stan data
X_new <- array(0, dim = c(n, n_categories, ncol(dMatrice$X_full[[1]])))
for (i in 1:n_categories){
X_new[,i,] <- dMatrice$X_full[[i]]
}
pooled_data_dict <- list(N = dim(X_new)[1],
J = dim(X_new)[3],
n_cat = dim(X_new)[2],
M = nrow(dMatrice$Z),
K = ncol(dMatrice$Z),
X = X_new,
Z = dMatrice$Z,
id = id,
y = y)
}else{
if (is.null(data)) stop("data must be specified!")
mf2 <- model.frame(formula = l2_formula, data = data)
#check only relevant columns
data_colnames <- colnames(data)
var_names <- c(colnames(mf1), colnames(mf2))[-1] # exclude dv, as it was checked before
# check each column in the dataframe should have the class 'factor' or 'numeric', no other classes such as 'matrix'...
for (i in 1:ncol(data)){
if (data_colnames[i] %in% var_names){
if(!inherits(data[,i], 'factor') && !inherits(data[,i], 'numeric') && !inherits(data[,i], 'integer')) stop("data class must be 'factor', 'numeric' or 'integer'")
# checking numerical predictors, converted to categorical variables if the number of levels is <= 3
if ((inherits(data[,i], 'numeric') | inherits(data[,i], 'integer')) & length(unique(data[,i])) <= 3){
#convert the column to factors
data[,i] <- convert.numeric.2.factor(data[,i])
warning("Variables(levels <= 3) have been converted to factors")
}
}
}
n <- nrow(data)
uni_id <- unique(old_id)
num_id <- length(uni_id)
new_id <- rep(0, length(old_id)) # store the new id from 1,2,3,...
for (i in 1:length(old_id))
new_id[i] <- which(uni_id == old_id[i])
id <- new_id
dMatrice <- design.matrix(l1_formula, l2_formula, data = data, id = id, contrast = contrast)
if (model_name == "Binomial"){
trials <- num_trials
if (length(trials) == 1) trials <- rep(num_trials, n)
if (length(trials) != n) stop('The length of num_trials must be equal to the number of observations!')
# handle missing values
if (sum(y > num_trials, na.rm = T) > 0) stop('The number of trials is less than observations!')
pooled_data_dict <- list(N = nrow(dMatrice$X),
J = ncol(dMatrice$X),
M = nrow(dMatrice$Z),
K = ncol(dMatrice$Z),
trials = trials,
X = dMatrice$X,
Z = dMatrice$Z,
id = id,
y = y)
}else if(model_name == 'ordMultinomial'){
pooled_data_dict <- list(cat = n.cut + 1,
N = nrow(dMatrice$X),
J = ncol(dMatrice$X),
M = nrow(dMatrice$Z),
K = ncol(dMatrice$Z),
X = dMatrice$X,
Z = dMatrice$Z,
id = id,
y = y)
}else if(model_name == 'multiNormal'){
pooled_data_dict <- list(L = num_dv,
N = nrow(dMatrice$X),
J = ncol(dMatrice$X),
M = nrow(dMatrice$Z),
K = ncol(dMatrice$Z),
X = dMatrice$X,
Z = dMatrice$Z,
id = id,
y = y)
}else if (model_name == 'truncNormal'){
pooled_data_dict <- list(L = y_lowerBound,
U = y_upperBound,
no_lower_bound = no_lower_bound,
no_upper_bound = no_upper_bound,
N = nrow(dMatrice$X),
J = ncol(dMatrice$X),
M = nrow(dMatrice$Z),
K = ncol(dMatrice$Z),
X = dMatrice$X,
Z = dMatrice$Z,
id = id,
y = y)
}else{
pooled_data_dict <- list(N = nrow(dMatrice$X),
J = ncol(dMatrice$X),
M = nrow(dMatrice$Z),
K = ncol(dMatrice$Z),
X = dMatrice$X,
Z = dMatrice$Z,
id = id,
y = y)
}
}
# get the stan model stored in the package if model is not specified
if (!is(fit, "BANOVA.build")){
fit <- get_BANOVA_stan_model(model_name, single_level)
}else{
# overwrite the model name and single level using the attributes from the fit
model_name <- fit$model_name
single_level <- fit$single_level
}
stan.fit <- rstan::sampling(fit$stanmodel, data = pooled_data_dict, iter=iter, verbose=TRUE, ...)
### find samples ###
#Sizes for all models except for Multivariate:beta1 JxM, beta2 KxJ
#Sizes for Multivariate Normal model: beta1 MxLxJ, beta2 lxKxJ
fit_beta <- rstan::extract(stan.fit, permuted = T)
if (model_name != "multiNormal"){
# For R2 of models with Normal distribution
R2 = NULL
if (!is.null(fit_beta$r_2)){
R2 <- mean(fit_beta$r_2)
R2 <- round(R2, 4)
}
# For the calculation of effect sizes in mediation
tau_ySq = NULL
if (model_name %in% c('Normal', 'T', 'truncNormal')){
if (!is.null(fit_beta$tau_ySq)){
tau_ySq <- mean(fit_beta$tau_ySq)
}
}else if (model_name == 'Bernoulli' || model_name == 'Binomial'){
tau_ySq = pi^2/3
}else if (model_name == 'ordMultinomial' || model_name == 'Multinomial'){
tau_ySq = pi^2/6
}else{
tau_ySq = 0
}
beta1_dim <- dim(fit_beta$beta1)
beta2_dim <- dim(fit_beta$beta2)
beta1_names <- c()
for (i in 1:beta1_dim[2]) #J
for (j in 1:beta1_dim[3]) #M
beta1_names <- c(beta1_names, paste("beta1_",i,"_",j, sep = ""))
samples_l1_param <- array(0, dim = c(beta1_dim[1], beta1_dim[2]*beta1_dim[3]), dimnames = list(NULL, beta1_names))
for (i in 1:beta1_dim[2])
for (j in 1:beta1_dim[3])
samples_l1_param[, (i-1) * beta1_dim[3] + j] <- fit_beta$beta1[, i, j]
beta2_names <- c()
for (i in 1:beta2_dim[3]) #J
for (j in 1:beta2_dim[2]) #K
beta2_names <- c(beta2_names, paste("beta2_",i,"_",j, sep = ""))
samples_l2_param <- array(0, dim = c(beta2_dim[1], beta2_dim[2]*beta2_dim[3]), dimnames = list(NULL, beta2_names))
for (i in 1:beta2_dim[3])
for (j in 1:beta2_dim[2])
samples_l2_param[, (i-1) * beta2_dim[2] + j] <- fit_beta$beta2[, j, i]
samples_l2_sigma_param = NA
if (model_name == 'Poisson'){
tau_beta1Sq_dim <- dim(fit_beta$tau_beta1Sq)
tau_beta1Sq_names <- c()
for (i in 1:tau_beta1Sq_dim[2])
tau_beta1Sq_names <- c(tau_beta1Sq_names, paste("tau_beta1Sq",i, sep = "_"))
samples_l2_sigma_param <- array(0, dim = c(tau_beta1Sq_dim[1], tau_beta1Sq_dim[2]), dimnames = list(NULL, tau_beta1Sq_names))
for (i in 1:tau_beta1Sq_dim[2])
samples_l2_sigma_param[, i] <- sqrt(fit_beta$tau_beta1Sq[,i])
}
samples_cutp_param = array(dim = 0)
if (model_name == 'ordMultinomial'){
c_dim <- dim(fit_beta$c_trans)
c_names <- c()
for (i in 2:c_dim[2])
c_names <- c(c_names, paste("c",i, sep = "_"))
# c_trans[1] == 0
samples_cutp_param <- array(0, dim = c(c_dim[1], c_dim[2] - 1), dimnames = list(NULL, c_names))
for (i in 2:c_dim[2])
samples_cutp_param[, i-1] <- fit_beta$c_trans[,i]
}
cat('Constructing ANOVA/ANCOVA tables...\n')
if (model_name == 'Multinomial'){
anova.table <- table.ANCOVA(samples_l1_param, dMatrice$X_full[[1]], dMatrice$Z, samples_l2_param, l1_error = tau_ySq) # for ancova models
coef.tables <- table.coefficients(samples_l2_param, beta2_names, colnames(dMatrice$X_full[[1]]), colnames(dMatrice$Z),
attr(dMatrice$X_full[[1]], 'assign'), attr(dMatrice$Z, 'assign') + 1, samples_cutp_param)
pvalue.table <- table.pvalue(coef.tables$coeff_table, coef.tables$row_indices, l1_names = attr(dMatrice$X_full[[1]], 'varNames'),
l2_names = attr(dMatrice$Z, 'varNames'))
conv <- conv.geweke.heidel(samples_l2_param, colnames(dMatrice$X_full[[1]]), colnames(dMatrice$Z))
}else{
anova.table <- table.ANCOVA(samples_l1_param, dMatrice$X, dMatrice$Z, samples_l2_param, l1_error = tau_ySq) # for ancova models
coef.tables <- table.coefficients(samples_l2_param, beta2_names, colnames(dMatrice$X), colnames(dMatrice$Z),
attr(dMatrice$X, 'assign') + 1, attr(dMatrice$Z, 'assign') + 1, samples_cutp_param)
pvalue.table <- table.pvalue(coef.tables$coeff_table, coef.tables$row_indices, l1_names = attr(dMatrice$X, 'varNames'),
l2_names = attr(dMatrice$Z, 'varNames'))
conv <- conv.geweke.heidel(samples_l2_param, colnames(dMatrice$X), colnames(dMatrice$Z))
}
class(conv) <- 'conv.diag'
cat('Done.\n')
} else {
mlvResult <- results.BANOVA.mlvNormal(fit_beta, dep_var_names = colnames(y), dMatrice)
}
}
if (model_name == 'Multinomial'){
sol <- list(anova.table = anova.table,
coef.tables = coef.tables,
pvalue.table = pvalue.table,
conv = conv,
dMatrice = dMatrice,
samples_l1_param = samples_l1_param,
samples_l2_param = samples_l2_param,
samples_l2_sigma_param = samples_l2_sigma_param,
samples_cutp_param = samples_cutp_param,
data = data,
dataX = dataX,
dataZ = dataZ,
mf1 = mf1,
mf2 = mf2,
n_categories = n_categories,
model_code = fit$stanmodel@model_code,
single_level = single_level,
stan_fit = stan.fit,
R2 = R2,
tau_ySq = tau_ySq,
model_name = paste('BANOVA', model_name, sep = "."),
contrast = contrast,
new_id = new_id,
old_id = old_id)
}else if (model_name == "multiNormal"){
sol <- list(anova.table = mlvResult$combined.anova,
coef.tables = mlvResult$combined.coef,
pvalue.table = mlvResult$combined.pvalue,
conv = mlvResult$combined.conv,
correlation.matrix = mlvResult$correlation.matrix,
covariance.matrix = mlvResult$covariance.matrix,
test.standard.deviations.of.dep.var = mlvResult$dep_var_sd,
test.residual.correlation = mlvResult$dep_var_corr,
dMatrice = dMatrice,
samples_l1_param = mlvResult$combined.samples.l1,
samples_l2_param = mlvResult$combined.samples.l2,
samples_l2_sigma_param = NA,
samples_cutp_param = array(dim = 0),
data = data,
num_trials = num_trials,
mf1 = mf1,
mf2 = mf2,
model_code = fit$stanmodel@model_code,
single_level = single_level,
stan_fit = stan.fit,
R2 = mlvResult$R2,
tau_ySq = mlvResult$tau_ySq,
model_name = paste('BANOVA', model_name, sep = "."),
contrast = contrast,
new_id = new_id,
old_id = old_id,
samples_l1.list = mlvResult$samples_l1.list,
samples_l2.list = mlvResult$samples_l2.list,
anova.tables.list = mlvResult$anova.tables.list,
coef.tables.list = mlvResult$coef.tables.list,
pvalue.tables.list = mlvResult$pvalue.tables.list,
conv.list = mlvResult$conv.list,
num_depenent_variables = mlvResult$num_depenent_variables,
names_of_dependent_variables = mlvResult$names_of_dependent_variables)
} else {
sol <- list(anova.table = anova.table,
coef.tables = coef.tables,
pvalue.table = pvalue.table,
conv = conv,
dMatrice = dMatrice,
samples_l1_param = samples_l1_param,
samples_l2_param = samples_l2_param,
samples_l2_sigma_param = samples_l2_sigma_param,
samples_cutp_param = samples_cutp_param,
data = data,
num_trials = num_trials,
mf1 = mf1,
mf2 = mf2,
model_code = fit$stanmodel@model_code,
single_level = single_level,
stan_fit = stan.fit,
R2 = R2,
tau_ySq = tau_ySq,
model_name = paste('BANOVA', model_name, sep = "."),
contrast = contrast,
new_id = new_id,
old_id = old_id)
}
sol$call <- match.call()
class(sol) <- "BANOVA"
sol
}
# Load BANOVA compiled model
get_BANOVA_stan_model <- function(model, single_level) {
if (model == 'NA') stop("a model name must be provided!")
if (single_level)
name <- paste('single', 'BANOVA.RData', sep = '_')
else
name <- 'BANOVA.RData'
stanmodel <- tryCatch({
model_file <- system.file('libs', Sys.getenv('R_ARCH'), name,
package = 'BANOVA',
mustWork = TRUE)
load(model_file)
if(single_level)
obj <- paste(model, 'Normal_stanmodel_1', sep = '_')
else
obj <- paste(model, 'Normal_stanmodel', sep = '_')
stanm <- eval(parse(text = obj))
stanm
}, error = function(cond) {
compile_BANOVA_stan_model(model, single_level)
})
return(stanmodel)
}
# Compile BANOVA stan model
compile_BANOVA_stan_model <- function(model, single_level) {
if (single_level)
name <- paste('stan/single_', model, '.stan', sep = '')
else
name <- paste('stan/',model, '_Normal.stan', sep = '')
model <- BANOVA.model(model, single_level)
stanmodel <- BANOVA.build(model)
return(stanmodel)
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/BANOVA.run.R |
#' Simple effects calculation
#'
#' \code{BANOVA.simple} is a function for probing interaction effects in models where
#' both moderator and explanatory variables are factors with an arbitrary number
#' of levels. The function estimates and tests simple or partial effects, also known as simple main
#' or conditional effects. Both single-level and multi-level models with any of the distributions accommodated in
#' the package can be analyzed.
#' @usage BANOVA.simple(BANOVA_output, base = NULL, quantiles = c(0.025, 0.975),
#' dep_var_name = NULL, return_posterior_samples = FALSE)
#' @param BANOVA_output an object of class "BANOVA" returned by BANOVA.run function with
#' an outcome of the hierarchical Bayesian ANOVA analysis.
#' @param base a character string which specifies the name of the mediator variable used as a base
#' for calculation.
#' @param quantiles a numeric vector with quantiles for the posterior interval of the simple effects.
#' Must include two elements with values between 0 and 1 in ascending order, default c(0.025, 0.975)
#' @param dep_var_name a character string with a name of the dependent variable, for the Multinomial model only,
#' default NULL.
#' @param return_posterior_samples logical indicator of whether samples of the posterior simple effects
#' distributions should be returned, default \code{FALSE}.
#' @return Returns a list with the summary tables of the results; optionally returns the
#' samples drawn from the posterior simple effects distributions.
#
#' \item{\code{results_summary}}{a list of tables with summaries of the posterior simple effects distributions
#' for all factors and their combinations that are interacting with a moderating variable.}
#' \item{\code{samples_simple_effects}}{if \code{return_posterior_samples} is set to \code{TRUE}
#' a list of tables with samples of the posterior simple effects is returned. The tables include results
#' for all levels of all factors and their combinations that are interacting with a moderating variable.}
#' @details The function identifies all factors and their combinations that are interacting with a moderating of "base"
#' variable. For each interaction, it determines all possible level combinations of the involved regressors,
#' which are further used to combine the posterior samples of the selected regression coefficients to calculate
#' simple effects.
#'
#' When the default effect coding scheme is used the simple effects are calculated for all levels of the
#' interacting variables, as specified in the data. If a user specifies different contrasts for any of the interacting
#' variables the simple effects for these variables are reported for the user-defined
#' regressors. This distinction is reflected in the labels of the reported results: in the default case labels from the
#' original factors are displayed; in the case of user-defined contrasts, the name of the regressor is displayed instead.
#'
#' The summary of the posterior distribution of each simple effect contains the mean,
#' standard deviation, posterior interval, which by default reports a central 95\% interval,
#' but can also be specified by the user, and a two-sided Bayesian p-value.
#'
#' Note that for a Multinomial model intercepts and between-subject regressors have choice specific
#' coefficients and thus simple effects are reported for each possible choice outcome. To perform the
#' calculation for a Multinomial model an additional argument \code{dep_var_name} with a name of the
#' dependent variable must be specified.
#' @examples
#' # Use the colorad data set
#' data(colorad)
#' \donttest{
#' # Build and analyze the model
#' model <- BANOVA.model('Binomial')
#' banova_model <- BANOVA.build(model)
#' res_1 <- BANOVA.run(y ~ typic, ~ color*blurfac, fit = banova_model,
#' data = colorad, id = 'id', num_trials = as.integer(16),
#' iter = 2000, thin = 1, chains = 2)
#' # Calculate simple effects with "blurfac" as a moderating vriable
#' simple_effects <- BANOVA.simple(BANOVA_output = res_1, base = "blurfac")
#' }
#' @author Anna Kopyakova
#' @export
BANOVA.simple <- function(BANOVA_output = "NA", base = NULL, quantiles = c(0.025, 0.975), dep_var_name = NULL,
return_posterior_samples = FALSE){
check.quantiles <- function(){
#quantiles must be real numbers
if(!is(quantiles, "numeric")){
stop('The "quantiles" must be of a class numeric, which mean you need to specify
this argument as a vector with two real numbers between 0 and 1, in an ascending order')
}
#check if specified quantiles are each in range betrween 0 and 1
if (sum(quantiles < 1) != 2){
stop('Each specified quantile value must be below 1. Please check the "quantiles" argument')
} else if (sum(quantiles > 0) != 2){
stop('Each specified quantile value must be above 0. Please check the "quantiles" argument')
}
}
# update.regressor.names changes names of the regressors in the two-level models, as if they would
# be regressors in a single-level models. It removes "(Intercept)" in the interacting regressors.
update.regressor.names <- function(names_regressors_output){
if (BANOVA_output$model_name == "BANOVA.Multinomial"){
#Multinomial model has choice specific intercepts and thus generic name is not needed
name_regressors_updated <- c()
} else {
name_regressors_updated <- c(intercept_name)
}
for (regressor_name in names_regressors_output){
#split the name into interacting variables
name_string <- strsplit(regressor_name, ":")[[1]]
#remove spaces around the strings
string_elements <- c()
for (j in name_string){
string_elements <- c(string_elements, gsub(" ", "", j))
}
#select all interacting variables except for the intercept
non_intercept_vars <- string_elements[string_elements != intercept_name]
if (length(non_intercept_vars) > 1){
#if there are at least 2 interacting variables concatenate them via ":"
variable <- paste0(non_intercept_vars, collapse = ":")
name_regressors_updated <- c(name_regressors_updated, variable)
} else {
#if a single variable is left add it to the updated regressor names
name_regressors_updated <- c(name_regressors_updated, non_intercept_vars)
}
}
return(name_regressors_updated)
}
# make.formula combines regressors in the fist and second levels of the two-level models into one
make.formula <- function(pvalue.table, dep_var){
# select names of level one variables
l1_variables <- rownames(pvalue.table)
if (BANOVA_output$model_name == "BANOVA.Multinomial"){
# For Multinomial models choice specific intercepts are skipped from a variable list
l1_variables <- l1_variables[-c(1:(n_categories-1))]
} else {
if (length(l1_variables) == 1){
l1_variables <- c() # if there is only the intercept keep an empty string
} else {
# if other variables are present remove the intercept
l1_variables <- l1_variables[which(l1_variables != intercept_name)]
}
}
# select names of level two variables
l2_variables <- colnames(pvalue.table)
# if there is only the intercept keep an empty string
if (length(l2_variables) == 1){
l2_variables <- c()
} else {
# if other variables are present remove the intercept
l2_variables <- l2_variables[which(l2_variables != intercept_name)]
}
# combine the variables in a single string separated by "+"
single_vars <- paste0(c(l1_variables, l2_variables), collapse = " + ")
# if there are non intercept variables in the first level create their interaction with second
# level variables
interaction_var_list <- c()
if (length(l1_variables) != 0){
for (i in l2_variables){
for (j in l1_variables){
term <- paste0(j, ":", i)
interaction_var_list <- c(interaction_var_list, term)
}
}
}
# combine the interactions of first and second level variables in a single string separated by "+"
interaction_vars <- paste0(interaction_var_list, collapse = " + ")
# conbine all variables
if(interaction_vars == ""){
all_terms <- single_vars
} else {
all_terms <- paste0(c(single_vars, interaction_vars), collapse = " + ")
}
#create a final formula
formula <- paste0(dep_var, " ~ ", all_terms)
return(formula)
}
perform.calculation <- function(){
# build.title creates title for the tables with results
build.title <- function(){
non_base_string <- ""
and <- ""
for (i in 1:length(non_base_vars_names)){
if (i > 1){
and = ":"
}
non_base_string <- paste0(non_base_string, and, non_base_vars_names[i])
}
title <- paste0("Simple effects of ", non_base_string, " at each level of ", base, " factor" )
return(title)
}
# create.table creates tables with results used for printing
create.table <- function(remove_last_level = F){
# is.effect.coded checks if the user specified contrasts are a variation of effect coding scheme
is.effect.coded <- function(coding_matrix){
#if a contrast with only one column is used it must be converted to a matrix
if (inherits(coding_matrix, "numeric")){
coding_matrix <- as.matrix(coding_matrix)
}
n = dim(coding_matrix)[1]
k = dim(coding_matrix)[2]
default_contrasts = contr.sum(n)
#check if there is the same number of regressor in the coding schemes
if (ncol(default_contrasts) == k){
#check if the contrast is exactly the same as default
if (all(default_contrasts == coding_matrix)){
return(T)
} else {
#check if all elements in the matrices are the same
condition2 = all(sort(default_contrasts) == sort(coding_matrix))
#columns sum up to zero
condition3 = all(colSums(coding_matrix) == 0)
#the same level must be considered as a reference
condition4 = sum(rowSums(coding_matrix == -1) == k) == 1
#only one row should sum to k (the reference row)
condition5 = sum(abs(rowSums(coding_matrix)) == k) == 1
if (condition2 && condition3 && condition4 && condition5){
return(T)
}
}
}
return(F)
}
# fill in the results
result_table <- matrix(NA, nrow = n_cases, ncol = ncol(table))
result_table <- table
Q_1 <- paste0(" Quantile ", min(quantiles))
Q_2 <- paste0(" Quantile ", max(quantiles))
colnames(result_table) <- c(" Simple effect", " SD", Q_1, Q_2, " p-value")
colnames_return_table <- c("Simple effect", "SD", paste0("Quantile ", min(quantiles)),
paste0("Quantile ", max(quantiles)), "p-value")
# fill in the level indices
index_table_names <- list(NULL, colnames = c(base, non_base_vars_names))
index_table <- matrix(NA, nrow = nrow(effect_matrix), ncol = n_selected_vars,
dimnames = index_table_names)
# if user defines contrasts different labelling is used
# the unspecified levels of the variable must be skipped from the table, as it is not meaningful
contrasts <- BANOVA_output$contrast
if (!is.null(contrasts)){
variables_with_contrasts <- names(contrasts)
index_table <- matrix(as.factor(level_index[, index_table_names[["colnames"]]]),
ncol = n_selected_vars, dimnames = index_table_names)
# update default index_table for the variables with user defined contrasts
for (var in variables_with_contrasts){
if (var %in% index_table_names[["colnames"]]){
if (!is.effect.coded(contrasts[[var]])){
# level labels in the table are strins with variable name and regressor number
index_table[, var] <- matrix(as.factor(level_index_strings[, var]), ncol = length(var),
dimnames = list(NULL, var))
remove_last_level <- TRUE
}
}
}
} else {
#default index_table
index_table <- matrix(as.factor(level_index[, index_table_names[[2]]]), ncol = n_selected_vars,
dimnames = index_table_names)
}
# combine tables
result <- cbind(index_table, result_table)
rownames(result) <- rep('', n_cases)
# drop last level(s) if user defines contrasts
if (remove_last_level){
for (var in variables_with_contrasts){
if (var %in% colnames(index_table)){
levels_factor <- unique(index_table[, var])
n_contrasts <- dim(as.matrix(contrasts[[var]]))[2]
last_levels <- levels_factor[(n_contrasts+1):length(levels_factor)]
for (level in last_levels){
result <- result[result[, var] != level,]
}
}
}
}
return(list(result = result, colnames_return_table = colnames_return_table))
}
##### Main calculation ####
var_names <- attr(design_matrix, "varNames")
var_interactions <- attr(design_matrix, "interactions")
var_classes <- attr(design_matrix, "dataClasses")
var_levels_index <- attr(design_matrix, "assign")
interactions_index <- attr(design_matrix, "interactions_index")
n_regressors <- ncol(design_matrix)
var_values <- attr(design_matrix, "varValues")
var_index <- c(1:(length(var_names)))
# check if the base variable is in the model
if (!(base %in% var_names)){
stop("The specified base variable is not in the model. Please check the base argument.")
}
# check the classes of interacting variables
if (var_classes[base] != "factor"){
stop("Base variable must be a factor")
}
# check if there are interactions between factor variables
if (length(var_interactions) == 0){
stop("There are no interactions between factor variables.")
} else {
if (!single_level_multinomial){
var_values[[1]] <- NULL # remove y var
var_index <- var_index-1 #move the index such that counting starts from zero
#allign var_interactions indices with var_levels_index
for (i in 1: length(var_interactions))
var_interactions[[i]] <- var_interactions[[i]] - 1
}
}
# find base variables and indices of it's levels
base_index <- var_index[var_names == base]
base_levels_names <- names_regressors[var_levels_index == base_index]
# find which variables base interacts with
base_interactions <- c()
for (i in 1:length(var_interactions)){
interaction <- var_interactions[[i]]
if (base %in% names(interaction)){
base_interactions <- c(base_interactions, i)
}
}
if(return_posterior_samples){
simple_effect_return <- list()
}
# for each combination of interactions (block) with the base variable
for(block in base_interactions){
selected_vars <- var_interactions[[block]] # variables in the interaction
selected_vars_values <- var_values[selected_vars] # select values of relevant variables
n_selected_vars <- length(selected_vars) # number of variables included in an interaction
n_non_base_vars <- n_selected_vars-1 # number of non-base variables
# obtain effect matrix with intercept, regressors of the interacting variables, and thier interactions
effect_matrix <- effect.matrix.interaction(interaction_factors = selected_vars_values, assign = var_levels_index,
selected_vars, index_inter_factor = interactions_index[block],
numeric_index = attr(design_matrix, 'numeric_index'),
contrast = NULL)
n_cases <- nrow(effect_matrix) # number of possible combinations of caseses
# order the effect matrix
level_index <- attr(effect_matrix,"levels") # combinations of levels in the effect matrix
vars_names <- colnames(level_index) # names of selected variables
non_base_vars_names <- vars_names[vars_names != base] # names of selected non-base variables
if(!is.null(BANOVA_output$contrast)){
# if user defines contrasts then it might be that a different number of regressors are analyzed
# remove columns of effect matrix that correspond to non existing coefficients
keep_columns <- intersect(colnames(coefficients), colnames(effect_matrix))
effect_matrix <- effect_matrix[,keep_columns]
}
# create a level_index tables with string labels (as is in the BANOVA.run: var_name1, var_name2,...)
level_index_strings <- level_index
for (i in 1:ncol(level_index_strings)){
factor_levels <- unique(level_index_strings[,i])
num_levels <- length(factor_levels)
for (j in 1:num_levels){
level_index_strings[,i][level_index_strings[,i] == factor_levels[j]] <- paste0(vars_names[i], j)
}
}
#order of the base variable (for a two way interaction)
base_order <- order(level_index_strings[, base])
temp_index <- level_index_strings
level_index_temp <- level_index
effect_matrix_temp <- effect_matrix
if (n_non_base_vars != 1){
#first order in the non base variables if there are more than one of them
for (i in 0:(n_non_base_vars-1)){
order_index <- order(temp_index[, non_base_vars_names[n_non_base_vars-i]])
temp_index <- temp_index[order_index, ]
effect_matrix_temp <- effect_matrix_temp[order_index, ]
level_index_temp <- level_index_temp[order_index, ]
level_index_strings <- level_index_strings[order_index, ]
}
base_order <- order(temp_index[ ,base])
}
#order the effect matrix on the base variable
effect_matrix <- effect_matrix_temp[base_order, ]
level_index <- level_index_temp[base_order, ]
level_index_strings <- level_index_strings[base_order, ]
#intercept and the levels of the base variable should not be included in the simple effects
effect_matrix[, intercept_name] <- 0
effect_matrix[, base_levels_names] <- 0
coef_temp <- coefficients[, colnames(effect_matrix)] #coefficients of relevant regressors
if(return_posterior_samples){
simple_effect_samlpes <- matrix(NA, nrow = nrow(coefficients), ncol = n_cases)
}
table <- matrix(NA, nrow = n_cases, ncol = 5)
for (j in 1:n_cases){
simple_effects <- coef_temp %*% (effect_matrix[j,])
mean <- apply(simple_effects, 2, mean)
sd <- apply(simple_effects, 2, sd)
quantile_025 <- apply(simple_effects, 2, quantile, probs = min(quantiles), type = 3, na.rm = FALSE)
quantile_975 <- apply(simple_effects, 2, quantile, probs = max(quantiles), type = 3, na.rm = FALSE)
p_value <- pValues(simple_effects)
table[j,] <- cbind(mean, sd, pmin(quantile_025, quantile_975), pmax(quantile_025, quantile_975),
p_value)
if(return_posterior_samples){
simple_effect_samlpes[,j] <- simple_effects
}
}
# Format the tables
table <- format(round(table, 4), nsmall = 4)
title <- build.title()
create_table_result <- create.table()
table <- create_table_result$result
if(is.null(nrow(table))){
table <- t(as.matrix(table, nrow = 1))
dimnames(table)[[1]] <- ""
}
return_table <- data.frame(table)
table <- as.table(table)
#format pValues
n_columns <- ncol(table)
p_values <- as.numeric(table[, n_columns])
table[, n_columns] <- ifelse(round(p_values, 4) == 0, '<0.0001', table[, n_columns])
# Print results
cat('\n')
cat(title)
cat('\n\n')
print(table, right=T, digits = 4)
# Prepare values to be returned
var_names <- names(selected_vars)
n_vars <- length(var_names)
rownames(table) <- NULL
colnames(return_table)[(n_vars+1):ncol(return_table)] <- create_table_result$colnames_return_table
sol_tables[[title]] <- return_table
#Prepare optional posterior samples
if(return_posterior_samples){
var_names <- c(base, var_names[var_names != base])
interaction <- paste0(c(base, var_names[var_names != base]), collapse = ":")
label <- paste0("Simple effects for ", interaction)
var_name_levels <- matrix(NA, nrow = n_cases, ncol = n_vars)
for(i in 1:n_vars){
var <- var_names[i]
var_name_level <- paste(var, table[,var], sep=":")
var_name_level <- paste0("(", var_name_level, ")")
var_name_levels[, i] <- var_name_level
}
colnames(simple_effect_samlpes) <- apply(var_name_levels, 1, paste0, collapse = ":")
simple_effect_return[[label]] <- simple_effect_samlpes
}
}
if(return_posterior_samples){
return(list(results_summary = sol_tables, samples_simple_effects = simple_effect_return))
} else {
return(list(results_summary = sol_tables))
}
}
#MAIN FUNCTION----
#Perform input checks
if (!is(BANOVA_output, "BANOVA")){
stop('"BANOVA_output" must be of a class "BANOVA", which is an outup of BANOVA.run function')
}
if (!is(base, "character")){
stop('"base" must be of a class "character", which mean you need to pass it as a string')
}
check.quantiles()
sol_tables <- list()
model_name <- BANOVA_output$model_name
single_level_multinomial <- FALSE
# Multinomial models ----
if (model_name == "BANOVA.Multinomial"){
intercept_name <- ("(Intercept)")
if (BANOVA_output$single_level){
# for a single level model design matrix is extracted from BANOVA_output
single_level_multinomial = TRUE
design_matrix <- BANOVA_output$dMatrice$X_full[[1]]
names_regressors <- colnames(design_matrix)
coefficients <- BANOVA_output$samples_l1_param #select semples of the lvl1 parameters
colnames(coefficients) <- names_regressors
colnames(coefficients)[1] <- intercept_name
} else {
n_categories <- BANOVA_output$n_categories
l1_vars <- BANOVA_output$dMatrice$X_original_choice # list of length n_categories
l2_vars <- BANOVA_output$mf2 # matrix with between subject variables
n_l2_regs <- ncol(BANOVA_output$dMatrice$Z_full) # number of lel2 regressors
# check and select the dependent variable
if (is.null(dep_var_name)){
stop("The label for the dependent variable is not specified")
} else if (!is(dep_var_name, "character")) {
stop('The label for the dependent variable must be of a class "character",
which mean you need to pass it as a string')
}
dep_var <- as.data.frame(BANOVA_output$data[, dep_var_name])
colnames(dep_var) <- dep_var_name
# create a temporary data frame for used to create a design matrix
l1_df <- as.data.frame(l1_vars[[1]]) #needed to create a formula
data_temp <- cbind(l1_df, l2_vars, dep_var)
# create a formula
formula <- make.formula(BANOVA_output$pvalue.table, dep_var_name)
design_matrics <- design.matrix(l1_formula = formula, l2_formula = 'NA', data = data_temp,
contrast = BANOVA_output$contrast)
design_matrix <- design_matrics$X
names_regressors <- colnames(design_matrix)
# select original coefficients and rename them
original_coefficients <- BANOVA_output$samples_l2_param #select semples of the lvl2 parameters
all_reg_names <- update.regressor.names(rownames(BANOVA_output$coef.tables$coeff_table))
colnames(original_coefficients) <- all_reg_names
# select coefficients that are not choice specific
common_coefficients <- data.frame(original_coefficients[, intersect(names_regressors, all_reg_names)])
colnames(common_coefficients) <- intersect(names_regressors, all_reg_names)
for (k in 1:n_categories){
sol_tables <- list()
# select coefficients relevant for this choice
if (k > 1){
index <- c(1:n_l2_regs) + n_l2_regs*(k-2)
coefficients_choice_specific <- original_coefficients[,index]
} else {
coefficients_choice_specific <- original_coefficients[,c(1:n_l2_regs)]
coefficients_choice_specific[,] <- 0
}
colnames(coefficients_choice_specific) <- setdiff(names_regressors, all_reg_names)
coefficients <- as.matrix(cbind(coefficients_choice_specific, common_coefficients))
label <- paste0("For choice ", k, " simple effects are:")
cat(label)
cat('\n')
perform.calculation()
cat('\n')
}
}
} else if (model_name == "BANOVA.multiNormal"){
intercept_name <- colnames(BANOVA_output$pvalue.table)[1] #how intercept is labeled
results <- list()
names_dv <- BANOVA_output$names_of_dependent_variables
if (BANOVA_output$single_level){
design_matrix <- BANOVA_output$dMatrice$X
names_regressors <- colnames(design_matrix)
for (i in 1:BANOVA_output$num_depenent_variables){
name <- names_dv[i]
coefficients <- BANOVA_output$samples_l1.list[[i]] #select semples of the lvl1 parameters
colnames(coefficients) <- names_regressors
title <- paste0("\nSimple effects for ", name,"\n")
cat(title)
results[[name]] <- perform.calculation()
}
} else{
dep_var_label <- colnames(BANOVA_output$mf1)[1] #name of the matrix with dep vars
dep_var_matrix <- BANOVA_output$data[, dep_var_label] #matrix with dep vars
combined_data <- cbind(BANOVA_output$data, dep_var_matrix) #data set with y as a matrix and columns
for (i in 1:BANOVA_output$num_depenent_variables){
name <- names_dv[i]
# for a two level model design matrix is created by "rewriting" two equations into one
formula <- make.formula(BANOVA_output$pvalue.tables.list[[i]],
BANOVA_output$names_of_dependent_variables[[i]])
design_matrics <- design.matrix(l1_formula = formula, l2_formula = 'NA', data = combined_data,
contrast = BANOVA_output$contrast)
design_matrix <- design_matrics$X
names_regressors <- colnames(design_matrix)
coefficients <- BANOVA_output$samples_l2.list[[i]] #select semples of the lvl2 parameters
colnames(coefficients) <- update.regressor.names(rownames(BANOVA_output$coef.tables.list[[i]]$coeff_table))
title <- paste0("\nSimple effects for ", name,"\n")
cat(title)
results[[name]] <- perform.calculation()
}
}
return(results)
}
# All other models ----
else {
intercept_name <- colnames(BANOVA_output$pvalue.table)[1] #how intercept is labeled
if (BANOVA_output$single_level){
# for a single level model design matrix is extracted from BANOVA_output
design_matrix <- BANOVA_output$dMatrice$X
names_regressors <- colnames(design_matrix)
coefficients <- BANOVA_output$samples_l1_param #select semples of the lvl1 parameters
colnames(coefficients) <- names_regressors
} else {
# for a two level model design matrix is created by "rewriting" two equations into one
formula <- make.formula(pvalue.table = BANOVA_output$pvalue.table,
dep_var = colnames(BANOVA_output$mf1)[1])
design_matrics <- design.matrix(l1_formula = formula, l2_formula = 'NA', data = BANOVA_output$data,
contrast = BANOVA_output$contrast)
design_matrix <- design_matrics$X
names_regressors <- colnames(design_matrix)
coefficients <- BANOVA_output$samples_l2_param #select semples of the lvl2 parameters
colnames(coefficients) <- update.regressor.names(rownames(BANOVA_output$coef.tables$coeff_table))
}
perform.calculation()
}
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/BANOVA.simple.R |
BAnova <-
function(x){
if (length(x$anova.table) >2){
for (i in 1:length(x$anova.table)){
cat('\nChoice: ', i, '\n')
print(x$anova.table[[i]])
}
}else{
print(x$anova.table)
}
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/BAnova.R |
JAGSgen.PNormal <-
function (X, Z, l2_hyper, conv_speedup){
if (is.null(Z)){
num_l1_v <- ncol(X)
inits <- new.env() # store initial values for BUGS model
monitorl1.parameters <- character() # store monitors for level 1 parameters, which will be used in the computation of sum of squares
monitorl2.parameters <- NULL # store monitors for level 2 parameters
monitorl2.sigma.parameters <- NULL
### generate the code for BUGS model
sModel <- paste("model{", sep="")
### level 1 likelihood
sModel <- paste(sModel,"
for (i in 1:n){
y[i] ~ dpois(y.hat[i])
log(y.hat[i]) <-")
for (i in 1:num_l1_v){
if (i != num_l1_v)
sModel <- paste(sModel,"beta",i,"*","X[i,",i,"]+",sep="")
else
sModel <- paste(sModel,"beta",i,"*","X[i,",i,"]",sep="")
monitorl1.parameters<-c(monitorl1.parameters, paste("beta",i,sep=""))
}
sModel <- paste(sModel,"
}",sep="")
for (j in 1:num_l1_v){
sModel <- paste(sModel,"
beta",j,"~dnorm(0,",l2_hyper[3],")",sep="")
s<-paste("inits$","beta",j,"<-rnorm(1)",sep="")
eval(parse(text=s))
}
sModel<- paste(sModel,"
}")
}else{
num_l1_v <- ncol(X)
num_l2_v <- ncol(Z)
num_id <- nrow(Z)
inits <- new.env() # store initial values for BUGS model
monitorl1.parameters <- character() # store monitors for level 1 parameters, which will be used in the computation of sum of squares
monitorl2.parameters <- character() # store monitors for level 2 parameters
monitorl2.sigma.parameters <- character()
### generate the code for BUGS model
sModel <- paste("model{", sep="")
### level 1 likelihood
sModel <- paste(sModel,"
for (i in 1:n){
y[i] ~ dpois(y.hat[i])
log(y.hat[i]) <-")
for (i in 1:num_l1_v){
if (i != num_l1_v)
sModel <- paste(sModel,"beta",i,"[id[i]]","*","X[i,",i,"]+",sep="")
else
sModel <- paste(sModel,"beta",i,"[id[i]]","*","X[i,",i,"]",sep="")
for (j in 1:num_id)
monitorl1.parameters<-c(monitorl1.parameters, paste("beta",i,"[",j,"]",sep=""))
}
#sModel <- paste(sModel,"#+epsilon[i]
# #epsilon[i] ~ dnorm(0,tau.eps)", sep = "")
sModel <- paste(sModel,"
}",sep="")
#tau.eps ~ dgamma(1, 1)
#sigma.eps <- pow(tau.eps, -0.5)",sep="")
#inits$epsilon <- rnorm(nrow(X))
#inits$sigma.eps <- 1
### level 2 likelihood
for (i in 1:num_l1_v){
if (!conv_speedup){
sModel <- paste(sModel,"
for (i in 1:M){
","beta",i,"[i]~dnorm(mu.beta",i,"[i]",",tau.beta",i,")
mu.beta",i,"[i]<- ",sep="")
for (j in 1:num_l2_v){
if (j != num_l2_v)
sModel <- paste(sModel,"beta",i,'_',j,"*Z[i,",j,"]+",sep="")
else
sModel <- paste(sModel,"beta",i,'_',j,"*Z[i,",j,"]",sep="")
}
sModel <- paste(sModel,"
}",sep="")
sModel <- paste(sModel,"
tau.beta",i,"~dgamma(", l2_hyper[1],",", l2_hyper[2],")
sigma.beta",i,"<-pow(tau.beta",i,",-0.5)",sep="")
monitorl2.sigma.parameters <- c(monitorl2.sigma.parameters, paste("sigma.beta",i,sep=""))
# generate inits for betas
s <- paste("inits$","beta",i,"<-rep(",1/max(X[,i]), ",", num_id,")",sep="")
s1 <- paste("inits$","tau.beta",i,"<-runif(",1,")",sep="")
eval(parse(text = s))
eval(parse(text = s1))
}else{
sModel <- paste(sModel,"
for (i in 1:M){
","beta",i,".raw[i]~dnorm(mu.beta",i,".raw[i]",",tau.beta",i,".raw)
beta",i,"[i] <- xi",i,"*beta",i,".raw[i]
mu.beta",i,".raw[i]<- 1/xi",i,"*(",sep="")
for (j in 1:num_l2_v){
if (j != num_l2_v)
sModel <- paste(sModel,"beta",i,'_',j,"*Z[i,",j,"]+",sep="")
else
sModel <- paste(sModel,"beta",i,'_',j,"*Z[i,",j,"])",sep="")
}
sModel <- paste(sModel,"
}",sep="")
sModel <- paste(sModel,"
xi",i,"~dunif(0, 100)
tau.beta",i,".raw~dgamma(", l2_hyper[1],",", l2_hyper[2],")
sigma.beta",i,"<-xi",i,"*pow(tau.beta",i,".raw,-0.5)",sep="")
monitorl2.sigma.parameters <- c(monitorl2.sigma.parameters, paste("sigma.beta",i,sep=""))
# generate inits for betas
s <- paste("inits$","beta",i,".raw<-rep(",1/max(X[,i]), ",", num_id,")",sep="")
s1 <- paste("inits$","tau.beta",i,".raw<-runif(",1,")",sep="")
sxi <- paste("inits$","xi",i,"<-runif(",1,")",sep="")
eval(parse(text = s))
eval(parse(text = s1))
eval(parse(text = sxi))
}
### level 2 priors
for (j in 1:num_l2_v){
sModel <- paste(sModel,"
beta",i,'_',j,"~dnorm(0,",l2_hyper[3],")",sep="")
s<-paste("inits$","beta",i,'_',j,"<-",1/max(Z[,j]),sep="")
eval(parse(text=s))
monitorl2.parameters <- c(monitorl2.parameters,paste("beta",i,'_',j,sep=""))
}
}
sModel<- paste(sModel,"
}")
}
tmp <- as.list(inits)
tmp$.RNG.name = "base::Super-Duper"
tmp$.RNG.seed = sample(.Machine$integer.max, 1)
sol.inits <- dump.format(tmp)
results <- list(inits = sol.inits, monitorl1.parameters = monitorl1.parameters,
monitorl2.parameters = monitorl2.parameters,
monitorl2.sigma.parameters = monitorl2.sigma.parameters,
sModel = sModel)
return(results)
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/JAGSgen.PNormal.R |
JAGSgen.TNormal <-
function (X, Z, l1_hyper, l2_hyper, conv_speedup){
if (is.null(Z)){
num_l1_v <- ncol(X)
inits <- new.env() # store initial values for BUGS model
monitorl1.parameters <- character() # store monitors for level 1 parameters, which will be used in the computation of sum of squares
monitorl2.parameters <- NULL # store monitors for level 2 parameters
### generate the code for BUGS model
sModel <- paste("model{", sep="")
### level 1 likelihood
sModel <- paste(sModel,"
for (i in 1:n){
y[i] ~ dt(y.hat[i],tau.y,df)
"," y.hat[i] <-")
for (i in 1:num_l1_v){
if (i != num_l1_v)
sModel <- paste(sModel,"beta",i,"*","X[i,",i,"]+",sep="")
else
sModel <- paste(sModel,"beta",i,"*","X[i,",i,"]",sep="")
monitorl1.parameters<-c(monitorl1.parameters, paste("beta",i,sep=""))
}
sModel <- paste(sModel,"
}
tau.y ~ dgamma(", l1_hyper[1],",", l1_hyper[2],")
sigma.y <- pow(tau.y, -0.5)
df ~ dpois(",l1_hyper[3],")",sep="")
inits$tau.y <- 1
inits$df <- 1
for (j in 1:num_l1_v){
sModel <- paste(sModel,"
beta",j,"~dnorm(0,",l1_hyper[4],")",sep="")
s<-paste("inits$","beta",j,"<-rnorm(1)",sep="")
eval(parse(text=s))
}
sModel<- paste(sModel,"
}")
}else{
num_l1_v <- ncol(X)
num_l2_v <- ncol(Z)
num_id <- nrow(Z)
inits <- new.env() # store initial values for BUGS model
monitorl1.parameters <- character() # store monitors for level 1 parameters, which will be used in the computation of sum of squares
monitorl2.parameters <- character() # store monitors for level 2 parameters
### generate the code for BUGS model
sModel <- paste("model{", sep="")
### level 1 likelihood
sModel <- paste(sModel,"
for (i in 1:n){
y[i] ~ dt(y.hat[i],tau.y,df)
"," y.hat[i] <-")
for (i in 1:num_l1_v){
if (i != num_l1_v)
sModel <- paste(sModel,"beta",i,"[id[i]]","*","X[i,",i,"]+",sep="")
else
sModel <- paste(sModel,"beta",i,"[id[i]]","*","X[i,",i,"]",sep="")
for (j in 1:num_id)
monitorl1.parameters<-c(monitorl1.parameters, paste("beta",i,"[",j,"]",sep=""))
}
sModel <- paste(sModel,"
}
tau.y ~ dgamma(", l1_hyper[1],",", l1_hyper[2],")
sigma.y <- pow(tau.y, -0.5)
df ~ dpois(",l1_hyper[3],")",sep="")
inits$tau.y <- 1
inits$df <- 1
### level 2 likelihood
for (i in 1:num_l1_v){
if (!conv_speedup){
sModel <- paste(sModel,"
for (i in 1:M){
","beta",i,"[i]~dnorm(mu.beta",i,"[i]",",tau.beta",i,")
mu.beta",i,"[i]<- ",sep="")
for (j in 1:num_l2_v){
if (j != num_l2_v)
sModel <- paste(sModel,"beta",i,'_',j,"*Z[i,",j,"]+",sep="")
else
sModel <- paste(sModel,"beta",i,'_',j,"*Z[i,",j,"]",sep="")
}
sModel <- paste(sModel,"
}",sep="")
sModel <- paste(sModel,"
tau.beta",i,"~dgamma(", l2_hyper[1],",", l2_hyper[2],")
sigma.beta",i,"<-pow(tau.beta",i,",-0.5)",sep="")
# generate inits for betas
s <- paste("inits$","beta",i,"<-rnorm(",num_id,")",sep="")
s1 <- paste("inits$","tau.beta",i,"<-runif(",1,")",sep="")
eval(parse(text = s))
eval(parse(text = s1))
}else{
sModel <- paste(sModel,"
for (i in 1:M){
","beta",i,".raw[i]~dnorm(mu.beta",i,".raw[i]",",tau.beta",i,".raw)
beta",i,"[i] <- xi",i,"*beta",i,".raw[i]
mu.beta",i,".raw[i]<- 1/xi",i,"*(",sep="")
for (j in 1:num_l2_v){
if (j != num_l2_v)
sModel <- paste(sModel,"beta",i,'_',j,"*Z[i,",j,"]+",sep="")
else
sModel <- paste(sModel,"beta",i,'_',j,"*Z[i,",j,"])",sep="")
}
sModel <- paste(sModel,"
}",sep="")
sModel <- paste(sModel,"
xi",i,"~dunif(0, 100)
tau.beta",i,".raw~dgamma(", l2_hyper[1],",", l2_hyper[2],")
sigma.beta",i,"<-xi",i,"*pow(tau.beta",i,".raw,-0.5)",sep="")
# generate inits for betas
s <- paste("inits$","beta",i,".raw<-rnorm(",num_id,")",sep="")
s1 <- paste("inits$","tau.beta",i,".raw<-runif(",1,")",sep="")
sxi <- paste("inits$","xi",i,"<-runif(",1,")",sep="")
eval(parse(text = s))
eval(parse(text = s1))
eval(parse(text = sxi))
}
### level 2 priors
for (j in 1:num_l2_v){
sModel <- paste(sModel,"
beta",i,'_',j,"~dnorm(0,",l2_hyper[3],")",sep="")
s<-paste("inits$","beta",i,'_',j,"<-rnorm(1)",sep="")
eval(parse(text=s))
monitorl2.parameters <- c(monitorl2.parameters,paste("beta",i,'_',j,sep=""))
}
}
sModel<- paste(sModel,"
}")
}
tmp <- as.list(inits)
tmp$.RNG.name = "base::Super-Duper"
tmp$.RNG.seed = sample(.Machine$integer.max, 1)
sol.inits <- dump.format(tmp)
results <- list(inits = sol.inits, monitorl1.parameters = monitorl1.parameters,
monitorl2.parameters = monitorl2.parameters, sModel = sModel)
return(results)
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/JAGSgen.TNormal.R |
JAGSgen.bernNormal <-
function (X, Z, l2_hyper, conv_speedup){
if (is.null(Z)){
num_l1_v <- ncol(X)
inits <- new.env() # store initial values for BUGS model
monitorl1.parameters <- character() # store monitors for level 1 parameters, which will be used in the computation of sum of squares
monitorl2.parameters <- NULL # store monitors for level 2 parameters
### generate the code for BUGS model
sModel <- paste("model{", sep="")
### level 1 likelihood
sModel <- paste(sModel,"
for (i in 1:n){
y[i] ~ dbern(y.hat[i])
y.hat[i] <- max(0,min(1,P[i]))
"," logit(P[i]) <-")
for (i in 1:num_l1_v){
if (i != num_l1_v)
sModel <- paste(sModel,"beta",i,"*","X[i,",i,"]+",sep="")
else
sModel <- paste(sModel,"beta",i,"*","X[i,",i,"]",sep="")
monitorl1.parameters<-c(monitorl1.parameters, paste("beta",i,sep=""))
}
sModel <- paste(sModel,"
}",sep="")
for (j in 1:num_l1_v){
sModel <- paste(sModel,"
beta",j,"~dnorm(0,",l2_hyper[3],")",sep="")
s<-paste("inits$","beta",j,"<-rnorm(1)",sep="")
eval(parse(text=s))
}
sModel<- paste(sModel,"
}")
}else{
num_l1_v <- ncol(X)
num_l2_v <- ncol(Z)
num_id <- nrow(Z)
inits <- new.env() # store initial values for BUGS model
monitorl1.parameters <- character() # store monitors for level 1 parameters, which will be used in the computation of sum of squares
monitorl2.parameters <- character() # store monitors for level 2 parameters
### generate the code for BUGS model
sModel <- paste("model{", sep="")
### level 1 likelihood
sModel <- paste(sModel,"
for (i in 1:n){
y[i] ~ dbern(y.hat[i])
y.hat[i] <- max(0,min(1,P[i]))
"," logit(P[i]) <-")
for (i in 1:num_l1_v){
if (i != num_l1_v)
sModel <- paste(sModel,"beta",i,"[id[i]]","*","X[i,",i,"]+",sep="")
else
sModel <- paste(sModel,"beta",i,"[id[i]]","*","X[i,",i,"]",sep="")
for (j in 1:num_id)
monitorl1.parameters<-c(monitorl1.parameters, paste("beta",i,"[",j,"]",sep=""))
}
sModel <- paste(sModel,"
}",sep="")
### level 2 likelihood
for (i in 1:num_l1_v){
if (!conv_speedup){
sModel <- paste(sModel,"
for (i in 1:M){
","beta",i,"[i]~dnorm(mu.beta",i,"[i]",",tau.beta",i,")
mu.beta",i,"[i]<- ",sep="")
for (j in 1:num_l2_v){
if (j != num_l2_v)
sModel <- paste(sModel,"beta",i,'_',j,"*Z[i,",j,"]+",sep="")
else
sModel <- paste(sModel,"beta",i,'_',j,"*Z[i,",j,"]",sep="")
}
sModel <- paste(sModel,"
}",sep="")
sModel <- paste(sModel,"
tau.beta",i,"~dgamma(", l2_hyper[1],",", l2_hyper[2],")
sigma.beta",i,"<-pow(tau.beta",i,",-0.5)",sep="")
# generate inits for betas
s <- paste("inits$","beta",i,"<-rep(",1/max(X[,i]), ",", num_id,")",sep="")
s1 <- paste("inits$","tau.beta",i,"<-runif(",1,")",sep="")
eval(parse(text = s))
eval(parse(text = s1))
}else{
sModel <- paste(sModel,"
for (i in 1:M){
","beta",i,".raw[i]~dnorm(mu.beta",i,".raw[i]",",tau.beta",i,".raw)
beta",i,"[i] <- xi",i,"*beta",i,".raw[i]
mu.beta",i,".raw[i]<- 1/xi",i,"*(",sep="")
for (j in 1:num_l2_v){
if (j != num_l2_v)
sModel <- paste(sModel,"beta",i,'_',j,"*Z[i,",j,"]+",sep="")
else
sModel <- paste(sModel,"beta",i,'_',j,"*Z[i,",j,"])",sep="")
}
sModel <- paste(sModel,"
}",sep="")
sModel <- paste(sModel,"
xi",i,"~dunif(0, 100)
tau.beta",i,".raw~dgamma(", l2_hyper[1],",", l2_hyper[2],")
sigma.beta",i,"<-xi",i,"*pow(tau.beta",i,".raw,-0.5)",sep="")
# generate inits for betas
s <- paste("inits$","beta",i,".raw<-rep(",1/max(X[,i]), ",", num_id,")",sep="")
s1 <- paste("inits$","tau.beta",i,".raw<-runif(",1,")",sep="")
sxi <- paste("inits$","xi",i,"<-runif(",1,")",sep="")
eval(parse(text = s))
eval(parse(text = s1))
eval(parse(text = sxi))
}
### level 2 priors
for (j in 1:num_l2_v){
sModel <- paste(sModel,"
beta",i,'_',j,"~dnorm(0,",l2_hyper[3],")",sep="")
s<-paste("inits$","beta",i,'_',j,"<-",1/max(Z[,j]),sep="")
eval(parse(text=s))
monitorl2.parameters <- c(monitorl2.parameters,paste("beta",i,'_',j,sep=""))
}
}
sModel<- paste(sModel,"
}")
}
tmp <- as.list(inits)
tmp$.RNG.name = "base::Super-Duper"
tmp$.RNG.seed = sample(.Machine$integer.max, 1)
sol.inits <- dump.format(tmp)
results <- list(inits = sol.inits, monitorl1.parameters = monitorl1.parameters,
monitorl2.parameters = monitorl2.parameters, sModel = sModel)
return(results)
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/JAGSgen.bernNormal.R |
JAGSgen.binNormal <-
function (X, Z, l2_hyper, conv_speedup){
if (is.null(Z)){
num_l1_v <- ncol(X)
inits <- new.env() # store initial values for BUGS model
monitorl1.parameters <- character() # store monitors for level 1 parameters, which will be used in the computation of sum of squares
monitorl2.parameters <- NULL # store monitors for level 2 parameters
### generate the code for BUGS model
sModel <- paste("model{", sep="")
### level 1 likelihood
sModel <- paste(sModel,"
for (i in 1:n){
y[i] ~ dbin(y.hat[i], N[i])
y.hat[i] <- max(0,min(1,P[i]))
"," logit(P[i]) <-")
for (i in 1:num_l1_v){
if (i != num_l1_v)
sModel <- paste(sModel,"beta",i,"*","X[i,",i,"]+",sep="")
else
sModel <- paste(sModel,"beta",i,"*","X[i,",i,"]",sep="")
monitorl1.parameters<-c(monitorl1.parameters, paste("beta",i,sep=""))
}
sModel <- paste(sModel,"
}",sep="")
for (j in 1:num_l1_v){
sModel <- paste(sModel,"
beta",j,"~dnorm(0,",l2_hyper[3],")",sep="")
s<-paste("inits$","beta",j,"<-rnorm(1)",sep="")
eval(parse(text=s))
}
sModel<- paste(sModel,"
}")
}else{
num_l1_v <- ncol(X)
num_l2_v <- ncol(Z)
num_id <- nrow(Z)
inits <- new.env() # store initial values for BUGS model
monitorl1.parameters <- character() # store monitors for level 1 parameters, which will be used in the computation of sum of squares
monitorl2.parameters <- character() # store monitors for level 2 parameters
### generate the code for BUGS model
sModel <- paste("model{", sep="")
### level 1 likelihood
sModel <- paste(sModel,"
for (i in 1:n){
y[i] ~ dbin(y.hat[i], N[i])
y.hat[i] <- max(0,min(1,P[i]))
"," logit(P[i]) <-")
for (i in 1:num_l1_v){
if (i != num_l1_v)
sModel <- paste(sModel,"beta",i,"[id[i]]","*","X[i,",i,"]+",sep="")
else
sModel <- paste(sModel,"beta",i,"[id[i]]","*","X[i,",i,"]",sep="")
for (j in 1:num_id)
monitorl1.parameters<-c(monitorl1.parameters, paste("beta",i,"[",j,"]",sep=""))
}
sModel <- paste(sModel,"
}",sep="")
### level 2 likelihood
for (i in 1:num_l1_v){
if (!conv_speedup){
sModel <- paste(sModel,"
for (i in 1:M){
","beta",i,"[i]~dnorm(mu.beta",i,"[i]",",tau.beta",i,")
mu.beta",i,"[i]<- ",sep="")
for (j in 1:num_l2_v){
if (j != num_l2_v)
sModel <- paste(sModel,"beta",i,'_',j,"*Z[i,",j,"]+",sep="")
else
sModel <- paste(sModel,"beta",i,'_',j,"*Z[i,",j,"]",sep="")
}
sModel <- paste(sModel,"
}",sep="")
sModel <- paste(sModel,"
tau.beta",i,"~dgamma(", l2_hyper[1],",", l2_hyper[2],")
sigma.beta",i,"<-pow(tau.beta",i,",-0.5)",sep="")
# generate inits for betas
s <- paste("inits$","beta",i,"<-rep(",1/max(X[,i]), ",", num_id,")",sep="")
s1 <- paste("inits$","tau.beta",i,"<-runif(",1,")",sep="")
eval(parse(text = s))
eval(parse(text = s1))
}else{
sModel <- paste(sModel,"
for (i in 1:M){
","beta",i,".raw[i]~dnorm(mu.beta",i,".raw[i]",",tau.beta",i,".raw)
beta",i,"[i] <- xi",i,"*beta",i,".raw[i]
mu.beta",i,".raw[i]<- 1/xi",i,"*(",sep="")
for (j in 1:num_l2_v){
if (j != num_l2_v)
sModel <- paste(sModel,"beta",i,'_',j,"*Z[i,",j,"]+",sep="")
else
sModel <- paste(sModel,"beta",i,'_',j,"*Z[i,",j,"])",sep="")
}
sModel <- paste(sModel,"
}",sep="")
sModel <- paste(sModel,"
xi",i,"~dunif(0, 100)
tau.beta",i,".raw~dgamma(", l2_hyper[1],",", l2_hyper[2],")
sigma.beta",i,"<-xi",i,"*pow(tau.beta",i,".raw,-0.5)",sep="")
# generate inits for betas
s <- paste("inits$","beta",i,".raw<-rep(",1/max(X[,i]), ",", num_id,")",sep="")
s1 <- paste("inits$","tau.beta",i,".raw<-runif(",1,")",sep="")
sxi <- paste("inits$","xi",i,"<-runif(",1,")",sep="")
eval(parse(text = s))
eval(parse(text = s1))
eval(parse(text = sxi))
}
### level 2 priors
for (j in 1:num_l2_v){
sModel <- paste(sModel,"
beta",i,'_',j,"~dnorm(0,",l2_hyper[3],")",sep="")
s<-paste("inits$","beta",i,'_',j,"<-",1/max(Z[,j]),sep="")
eval(parse(text=s))
monitorl2.parameters <- c(monitorl2.parameters,paste("beta",i,'_',j,sep=""))
}
}
sModel<- paste(sModel,"
}")
}
tmp <- as.list(inits)
tmp$.RNG.name = "base::Super-Duper"
tmp$.RNG.seed = sample(.Machine$integer.max, 1)
sol.inits <- dump.format(tmp)
results <- list(inits = sol.inits, monitorl1.parameters = monitorl1.parameters,
monitorl2.parameters = monitorl2.parameters, sModel = sModel)
return(results)
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/JAGSgen.binNormal.R |
JAGSgen.multiNormal <-
function (X, Z, l2_hyper, conv_speedup){
if (is.null(Z)){
num_l1_v <- ncol(X[,,1])
inits <- new.env() # store initial values for BUGS model
monitorl1.parameters <- character() # store monitors for level 1 parameters, which will be used in the computation of sum of squares
monitorl2.parameters <- NULL # store monitors for level 2 parameters
### generate the code for BUGS model
sModel <- paste("model{", sep="")
### level 1 likelihood
sModel <- paste(sModel,"
for (i in 1:n){
y[i] ~ dcat(P[i,1:n_choice])
for (j in 1:n_choice){
mu[i,j] <-")
for (i in 1:num_l1_v){
if (i != num_l1_v)
sModel <- paste(sModel,"beta",i,"*","X[i,",i,",j]+",sep="")
else
sModel <- paste(sModel,"beta",i,"*","X[i,",i,",j]",sep="")
monitorl1.parameters<-c(monitorl1.parameters, paste("beta",i,sep=""))
}
sModel <- paste(sModel,"
emu[i,j] <- exp(mu[i,j])
P[i,j] <- emu[i,j]/sum(emu[i,1:n_choice])",sep="")
sModel <- paste(sModel,"
}
}",sep="")
for (j in 1:num_l1_v){
sModel <- paste(sModel,"
beta",j,"~dnorm(0,",l2_hyper[3],")",sep="")
s<-paste("inits$","beta",j,"<-rnorm(1)",sep="")
eval(parse(text=s))
}
sModel<- paste(sModel,"
}")
}else{
num_l1_v <- ncol(X[,,1])
num_l2_v <- ncol(Z)
num_id <- nrow(Z)
inits <- new.env() # store initial values for BUGS model
monitorl1.parameters <- character() # store monitors for level 1 parameters, which will be used in the computation of sum of squares
monitorl2.parameters <- character() # store monitors for level 2 parameters
### generate the code for BUGS model
sModel <- paste("model{", sep="")
### level 1 likelihood
sModel <- paste(sModel,"
for (i in 1:n){
y[i] ~ dcat(P[i,1:n_choice])
for (j in 1:n_choice){
mu[i,j] <-")
for (i in 1:num_l1_v){
if (i != num_l1_v)
sModel <- paste(sModel,"beta",i,"[id[i]]","*","X[i,",i,",j]+",sep="")
else
sModel <- paste(sModel,"beta",i,"[id[i]]","*","X[i,",i,",j]",sep="")
for (j in 1:num_id)
monitorl1.parameters<-c(monitorl1.parameters, paste("beta",i,"[",j,"]",sep=""))
}
sModel <- paste(sModel,"
emu[i,j] <- exp(mu[i,j])
P[i,j] <- emu[i,j]/sum(emu[i,1:n_choice])",sep="")
sModel <- paste(sModel,"
}
}",sep="")
### level 2 likelihood
for (i in 1:num_l1_v){
if (!conv_speedup){
sModel <- paste(sModel,"
for (i in 1:M){
","beta",i,"[i]~dnorm(mu.beta",i,"[i]",",tau.beta",i,")
mu.beta",i,"[i]<- ",sep="")
for (j in 1:num_l2_v){
if (j != num_l2_v)
sModel <- paste(sModel,"beta",i,'_',j,"*Z[i,",j,"]+",sep="")
else
sModel <- paste(sModel,"beta",i,'_',j,"*Z[i,",j,"]",sep="")
}
sModel <- paste(sModel,"
}",sep="")
sModel <- paste(sModel,"
tau.beta",i,"~dgamma(", l2_hyper[1],",", l2_hyper[2],")
sigma.beta",i,"<-pow(tau.beta",i,",-0.5)",sep="")
# generate inits for betas
s <- paste("inits$","beta",i,"<-rep(",1/max(X[,i,]), ",", num_id,")",sep="")
s1 <- paste("inits$","tau.beta",i,"<-runif(",1,")",sep="")
eval(parse(text = s))
eval(parse(text = s1))
}else{
sModel <- paste(sModel,"
for (i in 1:M){
","beta",i,".raw[i]~dnorm(mu.beta",i,".raw[i]",",tau.beta",i,".raw)
beta",i,"[i] <- xi",i,"*beta",i,".raw[i]
mu.beta",i,".raw[i]<- 1/xi",i,"*(",sep="")
for (j in 1:num_l2_v){
if (j != num_l2_v)
sModel <- paste(sModel,"beta",i,'_',j,"*Z[i,",j,"]+",sep="")
else
sModel <- paste(sModel,"beta",i,'_',j,"*Z[i,",j,"])",sep="")
}
sModel <- paste(sModel,"
}",sep="")
sModel <- paste(sModel,"
xi",i,"~dunif(0, 100)
tau.beta",i,".raw~dgamma(", l2_hyper[1],",", l2_hyper[2],")
sigma.beta",i,"<- xi",i,"*pow(tau.beta",i,".raw,-0.5)",sep="")
# generate inits for betas
s <- paste("inits$","beta",i,".raw<-rep(",1/max(X[,i]), ",", num_id,")",sep="")
s1 <- paste("inits$","tau.beta",i,".raw<-runif(",1,")",sep="")
sxi <- paste("inits$","xi",i,"<-runif(",1,")",sep="")
eval(parse(text = s))
eval(parse(text = s1))
eval(parse(text = sxi))
}
### level 2 priors
for (j in 1:num_l2_v){
sModel <- paste(sModel,"
beta",i,'_',j,"~dnorm(0,",l2_hyper[3],")",sep="")
s<-paste("inits$","beta",i,'_',j,"<-",1/max(Z[,j]),sep="")
eval(parse(text=s))
monitorl2.parameters <- c(monitorl2.parameters,paste("beta",i,'_',j,sep=""))
}
}
sModel<- paste(sModel,"
}")
}
tmp <- as.list(inits)
tmp$.RNG.name = "base::Super-Duper"
tmp$.RNG.seed = sample(.Machine$integer.max, 1)
sol.inits <- dump.format(tmp)
results <- list(inits = sol.inits, monitorl1.parameters = monitorl1.parameters,
monitorl2.parameters = monitorl2.parameters, sModel = sModel)
return(results)
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/JAGSgen.multiNormal.R |
JAGSgen.normalNormal <-
function (X, Z, l1_hyper = NULL, l2_hyper = NULL, conv_speedup = F){
if (is.null(Z)){
# one level model
num_l1_v <- ncol(X)
inits <- new.env() # store initial values for BUGS model
monitorl1.parameters <- character() # store monitors for level 1 parameters, which will be used in the computation of sum of squares
monitorl2.parameters <- NULL # store monitors for level 2 parameters, NULL for one level models
# check l1_hyper
if(is.null(l1_hyper)){
l1_hyper = c(1, 1, 0.0001)
}else{
if (length(l1_hyper) != 3){
stop("l1_hyper must be of length 3 for single level models!")
}
}
### generate the code for BUGS model
sModel <- paste("
model{", sep="")
### level 1 likelihood
sModel <- paste(sModel,"
for (i in 1:n){
y[i] ~ dnorm(y.hat[i],tau.y)
y.hat[i] <-")
for (i in 1:num_l1_v){
if (i != num_l1_v)
sModel <- paste(sModel,"beta",i,"*","X[i,",i,"]+",sep="")
else
sModel <- paste(sModel,"beta",i,"*","X[i,",i,"]",sep="")
monitorl1.parameters<-c(monitorl1.parameters, paste("beta",i,sep=""))
}
sModel <- paste(sModel,"
}
tau.y ~ dgamma(", l1_hyper[1],",", l1_hyper[2],")
sigma.y <- pow(tau.y, -0.5)",sep="")
inits$tau.y <- 1
for (j in 1:num_l1_v){
sModel <- paste(sModel,"
beta",j,"~dnorm(0,",l1_hyper[3],")",sep="")
s<-paste("inits$","beta",j,"<-rnorm(1)",sep="")
eval(parse(text=s))
}
sModel<- paste(sModel,"
}")
}else{
num_l1_v <- ncol(X)
num_l2_v <- ncol(Z)
num_id <- nrow(Z)
inits <- new.env() # store initial values for BUGS model
monitorl1.parameters <- character() # store monitors for level 1 parameters, which will be used in the computation of sum of squares
monitorl2.parameters <- character() # store monitors for level 2 parameters
### generate the code for BUGS model
sModel <- paste("model{", sep="")
### level 1 likelihood
sModel <- paste(sModel,"
for (i in 1:n){
y[i] ~ dnorm(y.hat[i],tau.y)
y.hat[i] <-")
for (i in 1:num_l1_v){
if (i != num_l1_v)
sModel <- paste(sModel,"beta",i,"[id[i]]","*","X[i,",i,"]+",sep="")
else
sModel <- paste(sModel,"beta",i,"[id[i]]","*","X[i,",i,"]",sep="")
for (j in 1:num_id)
monitorl1.parameters<-c(monitorl1.parameters, paste("beta",i,"[",j,"]",sep=""))
}
sModel <- paste(sModel,"
}
tau.y ~ dgamma(", l1_hyper[1],",", l1_hyper[2],")
sigma.y <- pow(tau.y, -0.5)",sep="")
inits$tau.y <- 1
### level 2 likelihood
for (i in 1:num_l1_v){
if (!conv_speedup){
sModel <- paste(sModel,"
for (i in 1:M){
","beta",i,"[i]~dnorm(mu.beta",i,"[i]",",tau.beta",i,")
mu.beta",i,"[i]<- ",sep="")
for (j in 1:num_l2_v){
if (j != num_l2_v)
sModel <- paste(sModel,"beta",i,'_',j,"*Z[i,",j,"]+",sep="")
else
sModel <- paste(sModel,"beta",i,'_',j,"*Z[i,",j,"]",sep="")
}
sModel <- paste(sModel,"
}",sep="")
sModel <- paste(sModel,"
tau.beta",i,"~dgamma(", l2_hyper[1],",", l2_hyper[2],")
sigma.beta",i,"<-pow(tau.beta",i,",-0.5)",sep="")
# generate inits for betas
s <- paste("inits$","beta",i,"<-rnorm(",num_id,")",sep="")
s1 <- paste("inits$","tau.beta",i,"<-runif(",1,")",sep="")
eval(parse(text = s))
eval(parse(text = s1))
}else{
sModel <- paste(sModel,"
for (i in 1:M){
","beta",i,".raw[i]~dnorm(mu.beta",i,".raw[i]",",tau.beta",i,".raw)
beta",i,"[i] <- xi",i,"*beta",i,".raw[i]
mu.beta",i,".raw[i]<- 1/xi",i,"*(",sep="")
for (j in 1:num_l2_v){
if (j != num_l2_v)
sModel <- paste(sModel,"beta",i,'_',j,"*Z[i,",j,"]+",sep="")
else
sModel <- paste(sModel,"beta",i,'_',j,"*Z[i,",j,"])",sep="")
}
sModel <- paste(sModel,"
}",sep="")
sModel <- paste(sModel,"
xi",i,"~dunif(0, 100)
tau.beta",i,".raw~dgamma(", l2_hyper[1],",", l2_hyper[2],")
sigma.beta",i,"<-xi",i,"*pow(tau.beta",i,".raw,-0.5)",sep="")
# generate inits for betas
s <- paste("inits$","beta",i,".raw<-rnorm(",num_id,")",sep="")
s1 <- paste("inits$","tau.beta",i,".raw<-runif(",1,")",sep="")
sxi <- paste("inits$","xi",i,"<-runif(",1,")",sep="")
eval(parse(text = s))
eval(parse(text = s1))
eval(parse(text = sxi))
}
### level 2 priors
for (j in 1:num_l2_v){
sModel <- paste(sModel,"
beta",i,'_',j,"~dnorm(0,",l2_hyper[3],")",sep="")
s<-paste("inits$","beta",i,'_',j,"<-rnorm(1)",sep="")
eval(parse(text=s))
monitorl2.parameters <- c(monitorl2.parameters,paste("beta",i,'_',j,sep=""))
}
}
sModel<- paste(sModel,"
}")
}
tmp <- as.list(inits)
tmp$.RNG.name = "base::Super-Duper"
tmp$.RNG.seed = sample(.Machine$integer.max, 1)
sol.inits <- dump.format(tmp)
results <- list(inits = sol.inits, monitorl1.parameters = monitorl1.parameters,
monitorl2.parameters = monitorl2.parameters, sModel = sModel)
return(results)
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/JAGSgen.normalNormal.R |
JAGSgen.ordmultiNormal <-
function (X, Z, n.cut, l1_hyper = NULL, l2_hyper = NULL, conv_speedup){
if (is.null(Z)){
num_l1_v <- ncol(X)
inits <- new.env() # store initial values for BUGS model
monitorl1.parameters <- character() # store monitors for level 1 parameters, which will be used in the computation of sum of squares
monitorl2.parameters <- NULL # store monitors for level 2 parameters
# check l1_hyper
if(is.null(l1_hyper)){
l1_hyper = c(0.0001, 10)
}else{
if (length(l1_hyper) != 2){
stop("l1_hyper must be of length 2 for single level models!")
}
}
### generate the code for BUGS model
sModel <- paste("model{", sep="")
### level 1 likelihood
sModel <- paste(sModel,"
for (i in 1:n){
y[i] ~ dcat(P[i,])
P[i,1] <- 1 - Q[i,1]
for (i.cut in 2: n.cut) {
P[i,i.cut] <- Q[i,i.cut-1] - Q[i,i.cut]
}
P[i,n.cut+1] <- Q[i,n.cut]
for (i.cut in 1:n.cut){
logit(Q[i,i.cut]) <- z[i,i.cut]","
z[i,i.cut] <-")
for (i in 1:num_l1_v){
if (i != num_l1_v)
sModel <- paste(sModel,"beta",i,"*","X[i,",i,"]+",sep="")
else
sModel <- paste(sModel,"beta",i,"*","X[i,",i,"]",sep="")
monitorl1.parameters<-c(monitorl1.parameters, paste("beta",i,sep=""))
}
sModel <- paste(sModel,"-cutp[i.cut]*(1-equals(i.cut,1))
}",sep="")
sModel <- paste(sModel,"
}",sep="")
for (j in 1:num_l1_v){
sModel <- paste(sModel,"
beta",j,"~dnorm(0,",l1_hyper[1],")",sep="")
s<-paste("inits$","beta",j,"<-rnorm(1)",sep="")
eval(parse(text=s))
}
sModel <- paste(sModel,"
for (i.cut in 1: n.cut) {
cutp0[i.cut] ~ dnorm(0,tau.cut)
}
tau.cut ~ dunif(0,",l1_hyper[2],")
cutp[1:n.cut] <- sort(cutp0)",sep="")
sModel<- paste(sModel,"
}")
inits$cutp0=c(0,sort(runif(n.cut-1,0,6)))
monitor.cutp <- character()
for (i in 2:n.cut)
monitor.cutp <-c(monitor.cutp, paste('cutp[',i,']',sep=""))
}else{
num_l1_v <- ncol(X)
num_l2_v <- ncol(Z)
num_id <- nrow(Z)
inits <- new.env() # store initial values for BUGS model
monitorl1.parameters <- character() # store monitors for level 1 parameters, which will be used in the computation of sum of squares
monitorl2.parameters <- character() # store monitors for level 2 parameters
### generate the code for BUGS model
sModel <- paste("model{", sep="")
### level 1 likelihood
sModel <- paste(sModel,"
for (i in 1:n){
y[i] ~ dcat(P[i,])
P[i,1] <- 1 - Q[i,1]
for (i.cut in 2: n.cut) {
P[i,i.cut] <- Q[i,i.cut-1] - Q[i,i.cut]
}
P[i,n.cut+1] <- Q[i,n.cut]
for (i.cut in 1:n.cut){
logit(Q[i,i.cut]) <- z[i,i.cut]","
z[i,i.cut] <-")
for (i in 1:num_l1_v){
if (i != num_l1_v)
sModel <- paste(sModel,"beta",i,"[id[i]]","*","X[i,",i,"]+",sep="")
else
sModel <- paste(sModel,"beta",i,"[id[i]]","*","X[i,",i,"]",sep="")
for (j in 1:num_id)
monitorl1.parameters<-c(monitorl1.parameters, paste("beta",i,"[",j,"]",sep=""))
}
sModel <- paste(sModel,"-cutp[i.cut]*(1-equals(i.cut,1))
}",sep="")
sModel <- paste(sModel,"
}",sep="")
### level 2 likelihood
for (i in 1:num_l1_v){
if (!conv_speedup){
sModel <- paste(sModel,"
for (i in 1:M){
","beta",i,"[i]~dnorm(mu.beta",i,"[i]",",tau.beta",i,")
mu.beta",i,"[i]<- ",sep="")
for (j in 1:num_l2_v){
if (j != num_l2_v)
sModel <- paste(sModel,"beta",i,'_',j,"*Z[i,",j,"]+",sep="")
else
sModel <- paste(sModel,"beta",i,'_',j,"*Z[i,",j,"]",sep="")
}
sModel <- paste(sModel,"
}",sep="")
sModel <- paste(sModel,"
tau.beta",i,"~dgamma(", l2_hyper[1],",", l2_hyper[2],")
sigma.beta",i,"<-pow(tau.beta",i,",-0.5)",sep="")
# generate inits for betas
s <- paste("inits$","beta",i,"<-rep(",1/max(X[,i]), ",", num_id,")",sep="")
s1 <- paste("inits$","tau.beta",i,"<-runif(",1,")",sep="")
eval(parse(text = s))
eval(parse(text = s1))
}else{
sModel <- paste(sModel,"
for (i in 1:M){
","beta",i,".raw[i]~dnorm(mu.beta",i,".raw[i]",",tau.beta",i,".raw)
beta",i,"[i] <- xi",i,"*beta",i,".raw[i]
mu.beta",i,".raw[i]<- 1/xi",i,"*(",sep="")
for (j in 1:num_l2_v){
if (j != num_l2_v)
sModel <- paste(sModel,"beta",i,'_',j,"*Z[i,",j,"]+",sep="")
else
sModel <- paste(sModel,"beta",i,'_',j,"*Z[i,",j,"])",sep="")
}
sModel <- paste(sModel,"
}",sep="")
sModel <- paste(sModel,"
xi",i,"~dunif(0, 100)
tau.beta",i,".raw~dgamma(", l2_hyper[1],",", l2_hyper[2],")
sigma.beta",i,"<-xi",i,"*pow(tau.beta",i,".raw,-0.5)",sep="")
# generate inits for betas
s <- paste("inits$","beta",i,".raw<-rep(",1/max(X[,i]), ",", num_id,")",sep="")
s1 <- paste("inits$","tau.beta",i,".raw<-runif(",1,")",sep="")
sxi <- paste("inits$","xi",i,"<-runif(",1,")",sep="")
eval(parse(text = s))
eval(parse(text = s1))
eval(parse(text = sxi))
}
### level 2 priors
for (j in 1:num_l2_v){
sModel <- paste(sModel,"
beta",i,'_',j,"~dnorm(0,",l2_hyper[3],")",sep="")
s<-paste("inits$","beta",i,'_',j,"<-",1/max(Z[,j]),sep="")
eval(parse(text=s))
monitorl2.parameters <- c(monitorl2.parameters,paste("beta",i,'_',j,sep=""))
}
}
sModel <- paste(sModel,"
for (i.cut in 1: n.cut) {
cutp0[i.cut] ~ dnorm(0,tau.cut)
}
tau.cut ~ dunif(0,",l2_hyper[4],")
cutp[1:n.cut] <- sort(cutp0)",sep="")
sModel<- paste(sModel,"
}")
inits$cutp0=c(0,sort(runif(n.cut-1,0,6)))
monitor.cutp <- character()
for (i in 2:n.cut)
monitor.cutp <-c(monitor.cutp, paste('cutp[',i,']',sep=""))
}
tmp <- as.list(inits)
tmp$.RNG.name = "base::Super-Duper"
tmp$.RNG.seed = sample(.Machine$integer.max, 1)
sol.inits <- dump.format(tmp)
results <- list(inits = sol.inits, monitorl1.parameters = monitorl1.parameters,
monitorl2.parameters = monitorl2.parameters, monitor.cutp = monitor.cutp, sModel = sModel)
return(results)
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/JAGSgen.ordmultiNormal.R |
# this function outputs effects of the numeric variable (sum of all coefficients related to
# the interaction of the numeric variable and the factor for each combination of moderators)in the model sol_1
# calculate the interaction effects between the numeric variable and the factor at different levels of moderators
cal.flood.effects <-
function (sol_1, est_matrix, n_sample, factor_name, numeric_name, flood_values = list()){
table_list <- list()
table_list_index <- 1
model1_level1_var_matrix <- attr(attr(sol_1$mf1, 'terms'),'factors')
model1_level1_var_dataClasses <- attr(attr(sol_1$mf1, 'terms'),'dataClasses')
model1_level2_var_matrix <- attr(attr(sol_1$mf2, 'terms'),'factors')
model1_level2_var_dataClasses <- attr(attr(sol_1$mf2, 'terms'),'dataClasses')
# for each level of xvar, need to check xvar in level 1 or 2
# find the mediator in the model and all other variables interacts with the mediator at the same level(moderators)
# then find the coefficient of the mediator (for each combination of moderators) in model 1
# algo:
# e.g. (mediator, interactions) x (estimation matrix) x (all vars except xvar including other moderators), mediator(continuous, normal): value 1 since we only look at the coefficients
# or (all vars except xvar including other moderators) x (estimation matrix) x (mediator, interactions) if the mediator is at the btw. level
# then find the coefficient of the xvar in model 2 (for each combination of moderators)
# algo:
# e.g. (xvar, interactions) x (estimation matrix) x (all vars except xvar including other moderators)
# or (all vars except xvar including other moderators) x (estimation matrix) x (xvar, interactions) if the mediator is at the btw. level
# Finally, join these two tables by common moderators
# TODO: create a common function to deal with above two algos
### calculate mediation effects in model 1
#if (attr(xvar, 'class') == 'numeric' || attr(xvar, 'class') == 'integer'){
factor_in_l1 <- factor_name %in% rownames(model1_level1_var_matrix)
factor_in_l2 <- factor_name %in% rownames(model1_level2_var_matrix)
numeric_in_l1 <- numeric_name %in% rownames(model1_level1_var_matrix)
numeric_in_l2 <- numeric_name %in% rownames(model1_level2_var_matrix)
if (!factor_in_l1 & !factor_in_l2) stop(factor_name," is not included in the model!")
if (!numeric_in_l1 & !numeric_in_l2) stop(numeric_name," is not included in the model!")
# mediator is at level 1
if (factor_in_l1 & numeric_in_l2 ){
factor_assign <- which (rownames(model1_level1_var_matrix) == factor_name)
#numeric_assign <- which (rownames(model1_level2_var_matrix) == numeric_name)
interaction_list <- attr(sol_1$dMatrice$X, "interactions_num") # if the mediator is numeric
interaction_list_index <- attr(sol_1$dMatrice$X, "interactions_numeric_index")
factor_interaction_list <- list()
factor_interaction_list_index <- array()
j = 1
if (length(interaction_list) > 0){
for (i in 1:length(interaction_list)){
if (factor_assign %in% interaction_list[[i]]){
factor_interaction_list[[j]] = interaction_list[[i]]
factor_interaction_list_index[j] = interaction_list_index[i]
j = j + 1
}
}
}
interaction_list <- attr(sol_1$dMatrice$X, "interactions") # if the mediator is not numeric
interaction_list_index <- attr(sol_1$dMatrice$X, "interactions_index")
if (length(interaction_list) > 0){
for (i in 1:length(interaction_list)){
if (factor_assign %in% interaction_list[[i]]){
factor_interaction_list[[j]] = interaction_list[[i]]
factor_interaction_list_index[j] = interaction_list_index[i]
j = j + 1
}
}
}
################################################
# find the effects of the factor and the numeric
################################################
# for each interaction in factor_interaction_list create a moderated table (exclude main effects)
# calculate l2 matrix first using all params but xvar, also using l2 formula
# TOFIX: what about the case only intercept included
l2_values <- attr(sol_1$dMatrice$Z, 'varValues')
if (length(l2_values) == 0){
# only intercept included
l2_matrix <- model.matrix(~1)
l2_matrix <- rbind(l2_matrix, c(1))
attr(l2_matrix, "levels") <- l2_matrix
if (sol_1$single_level){
colnames(l2_matrix) <- c(" ")
}
}else{
num_l2_matrix <- effect.matrix.mediator(interaction_factors = l2_values,
matrix_formula=formula(attr(sol_1$mf2, 'terms')),
mediator=numeric_name,
flood_values = flood_values, contrast = sol_1$contrast)
l2_matrix <- effect.matrix.mediator(interaction_factors = l2_values,
matrix_formula=formula(attr(sol_1$mf2, 'terms')),
xvar=numeric_name, intercept_include = TRUE,
flood_values = flood_values, contrast = sol_1$contrast)
}
if (length(factor_interaction_list) > 0){
l1_values <- attr(sol_1$dMatrice$X, 'varValues')
factor_interaction_effect_matrix <- list()
for (i in 1:length(factor_interaction_list)){
# l1 matrix
# TO check:
# y var is also included in l1_values, interaction_list has considered this
factor_interaction_effect_matrix[[i]] <- effect.matrix.mediator(interaction_factors = l1_values[factor_interaction_list[[i]]],
mediator=factor_name, xvar=numeric_name,
flood_values = flood_values, contrast = sol_1$contrast)
est_samples <- array(0, dim = c(nrow(factor_interaction_effect_matrix[[i]]), nrow(l2_matrix), n_sample))
num_est_samples <- array(0, dim = c(nrow(factor_interaction_effect_matrix[[i]]), nrow(num_l2_matrix), n_sample))
for (n_s in 1:n_sample){
est_samples[,,n_s] <- factor_interaction_effect_matrix[[i]] %*% est_matrix[colnames(factor_interaction_effect_matrix[[i]]), colnames(l2_matrix), n_s] %*% t(l2_matrix)
num_est_samples[,,n_s] <- factor_interaction_effect_matrix[[i]] %*% est_matrix[colnames(factor_interaction_effect_matrix[[i]]), colnames(num_l2_matrix), n_s] %*% t(num_l2_matrix)
}
#table_m <- construct.table(est_samples, attr(factor_interaction_effect_matrix[[i]], 'levels'), attr(l2_matrix, 'levels'))
table_m <- construct.effect.table(est_samples, attr(factor_interaction_effect_matrix[[i]], 'levels'), attr(l2_matrix, 'levels'),
num_est_samples, attr(factor_interaction_effect_matrix[[i]], 'levels'), attr(num_l2_matrix, 'levels'), l1_values[factor_assign], numeric_name)
table_list[[table_list_index]] <- table_m
table_list_index = table_list_index + 1
}
}else{
l1_values <- attr(sol_1$dMatrice$X, 'varValues')
# no interaction with the mediator in level 1, only select the mediator
# TO check:
# y var is also included in l1_values, interaction_list has considered this
l1_matrix <- effect.matrix.mediator(l1_values[factor_assign],
mediator=factor_name,
flood_values = flood_values, contrast = sol_1$contrast)
est_samples <- array(0, dim = c(nrow(l1_matrix), nrow(l2_matrix), n_sample))
num_est_samples <- array(0, dim = c(nrow(l1_matrix), nrow(num_l2_matrix), n_sample))
for (n_s in 1:n_sample){
est_samples[,,n_s] <- l1_matrix %*% est_matrix[colnames(l1_matrix), colnames(l2_matrix), n_s] %*% t(l2_matrix)
num_est_samples[,,n_s] <- l1_matrix %*% est_matrix[colnames(l1_matrix), colnames(num_l2_matrix), n_s] %*% t(num_l2_matrix)
}
#table_m <- construct.table(est_samples, attr(l1_matrix, 'levels'), attr(l2_matrix, 'levels'))
table_m <- construct.effect.table(est_samples, attr(l1_matrix, 'levels'), attr(l2_matrix, 'levels'),
num_est_samples, attr(l1_matrix, 'levels'), attr(num_l2_matrix, 'levels'), l1_values[factor_assign], numeric_name)
table_list[[table_list_index]] <- table_m
table_list_index = table_list_index + 1
}
}
if (factor_in_l1 & numeric_in_l1 ){
# find if there are moderators interacts with the factor except the numeric
factor_assign <- which (rownames(model1_level1_var_matrix) == factor_name)
numeric_assign <- which (rownames(model1_level1_var_matrix) == numeric_name)
interaction_list <- attr(sol_1$dMatrice$X, "interactions_num") # if the factor is numeric
interaction_list_index <- attr(sol_1$dMatrice$X, "interactions_numeric_index")
factor_interaction_list <- list()
factor_interaction_list_index <- array()
j = 1
if (length(interaction_list) > 0){
for (i in 1:length(interaction_list)){
if (factor_assign %in% interaction_list[[i]] && !(numeric_assign %in% interaction_list[[i]])){
factor_interaction_list[[j]] = interaction_list[[i]]
factor_interaction_list_index[j] = interaction_list_index[i]
j = j + 1
}
}
}
interaction_list <- attr(sol_1$dMatrice$X, "interactions") # if the factor is not numeric
interaction_list_index <- attr(sol_1$dMatrice$X, "interactions_index")
if (length(interaction_list) > 0){
for (i in 1:length(interaction_list)){
if (factor_assign %in% interaction_list[[i]]){
factor_interaction_list[[j]] = interaction_list[[i]]
factor_interaction_list_index[j] = interaction_list_index[i]
j = j + 1
}
}
}
# for each interaction in factor_interaction_list create a moderated table (exclude main effects)
# calculate l2 matrix first using all params but xvar, also using l2 formula
l2_values <- attr(sol_1$dMatrice$Z, 'varValues')
if (length(l2_values) == 0){
# only intercept included
l2_matrix <- model.matrix(~1)
l2_matrix <- rbind(l2_matrix, c(1))
attr(l2_matrix, "levels") <- l2_matrix
if (sol_1$single_level){
colnames(l2_matrix) <- c(" ")
}
}else{
l2_matrix <- effect.matrix.mediator(interaction_factors = l2_values,
matrix_formula=formula(attr(sol_1$mf2, 'terms')),
flood_values = flood_values, contrast = sol_1$contrast)
}
if (length(factor_interaction_list) > 0){
#TODO: check if numeric varible in L1
l1_values <- attr(sol_1$dMatrice$X, 'varValues')
factor_interaction_effect_matrix <- list()
num_factor_interaction_effect_matrix <- list()
# remove y
# find the response variable
# vars <- as.character(attr(attr(sol_1$mf1, 'terms'), 'variables'))[-1]
# response_ind <- attr(attr(sol_1$mf1, 'terms'), 'response')
# response_name <- vars[response_ind]
# #remove the response value from l1_values
# to_rm_res <- 0
# for (i in 1:length(l1_values)){
# if (attr(l1_values[[i]], 'var_names') == response_name) to_rm_res <- i
# }
# num_l1_values <- l1_values
# num_l1_values[[to_rm_res]] <- NULL
for (i in 1:length(factor_interaction_list)){
# l1 matrix should include the effects of interactions contains both the numeric and factor
# TO check:
# y var is also included in l1_values, interaction_list has considered this
factor_interaction_effect_matrix[[i]] <- effect.matrix.mediator(interaction_factors = l1_values[factor_interaction_list[[i]]],
mediator=factor_name,
xvar=numeric_name,
flood_values = flood_values,
contrast = sol_1$contrast)
num_factor_interaction_effect_matrix[[i]] <- effect.matrix.mediator(interaction_factors = l1_values,
matrix_formula=formula(attr(sol_1$mf1, 'terms')),
mediator=factor_name,
xvar=numeric_name,
xvar_include = TRUE,
flood_values = flood_values,
contrast = sol_1$contrast)
est_samples <- array(0, dim = c(nrow(factor_interaction_effect_matrix[[i]]), nrow(l2_matrix), n_sample))
num_est_samples <- array(0, dim = c(nrow(num_factor_interaction_effect_matrix[[i]]), nrow(l2_matrix), n_sample))
if ("" %in% dimnames(est_matrix)[[2]]){
for (n_s in 1:n_sample){
est_samples[,,n_s] <- factor_interaction_effect_matrix[[i]] %*% est_matrix[colnames(factor_interaction_effect_matrix[[i]]), 1, n_s] %*% t(l2_matrix)
num_est_samples[,,n_s] <- num_factor_interaction_effect_matrix[[i]] %*% est_matrix[colnames(num_factor_interaction_effect_matrix[[i]]), 1, n_s] %*% t(l2_matrix)
}
}else{
for (n_s in 1:n_sample){
est_samples[,,n_s] <- factor_interaction_effect_matrix[[i]] %*% est_matrix[colnames(factor_interaction_effect_matrix[[i]]), colnames(l2_matrix), n_s] %*% t(l2_matrix)
num_est_samples[,,n_s] <- num_factor_interaction_effect_matrix[[i]] %*% est_matrix[colnames(num_factor_interaction_effect_matrix[[i]]), colnames(l2_matrix), n_s] %*% t(l2_matrix)
}
}
#table_m <- construct.table(est_samples, attr(factor_interaction_effect_matrix[[i]], 'levels'), attr(l2_matrix, 'levels'))
table_m <- construct.effect.table(est_samples, attr(factor_interaction_effect_matrix[[i]], 'levels'), attr(l2_matrix, 'levels'),
num_est_samples, attr(num_factor_interaction_effect_matrix[[i]], 'levels'), attr(l2_matrix, 'levels'), l1_values[factor_assign], numeric_name)
table_list[[table_list_index]] <- table_m
table_list_index = table_list_index + 1
}
}else{
l1_values <- attr(sol_1$dMatrice$X, 'varValues')
factor_values <- l1_values[factor_assign]
# no interaction with the mediator in level 1, only select the mediator
# check:
# y var is also included in l1_values, interaction_list has considered this
l1_matrix <- effect.matrix.mediator(l1_values[factor_assign],
mediator=factor_name,
flood_values = flood_values, contrast = sol_1$contrast)
# find the response variable
# vars <- as.character(attr(attr(sol_1$mf1, 'terms'), 'variables'))[-1]
# response_ind <- attr(attr(sol_1$mf1, 'terms'), 'response')
# response_name <- vars[response_ind]
# #remove the response value from l1_values
# to_rm_res <- 0
# for (i in 1:length(l1_values)){
# if (attr(l1_values[[i]], 'var_names') == response_name) to_rm_res <- i
# }
# l1_values[[to_rm_res]] <- NULL
num_l1_matrix <- effect.matrix.mediator(l1_values,
matrix_formula=formula(attr(sol_1$mf1, 'terms')),
mediator=factor_name,
xvar = numeric_name,
xvar_include = TRUE,
flood_values = flood_values,
contrast = sol_1$contrast)
est_samples <- array(0, dim = c(nrow(l1_matrix), nrow(l2_matrix), n_sample))
num_est_samples <- array(0, dim = c(nrow(num_l1_matrix), nrow(l2_matrix), n_sample))
if ("" %in% dimnames(est_matrix)[[2]]){
for (n_s in 1:n_sample){
est_samples[,,n_s] <- l1_matrix %*% est_matrix[colnames(l1_matrix), 1, n_s] %*% t(l2_matrix)
num_est_samples[,,n_s] <- num_l1_matrix %*% est_matrix[colnames(num_l1_matrix), 1, n_s] %*% t(l2_matrix)
}
}else{
for (n_s in 1:n_sample){
est_samples[,,n_s] <- l1_matrix %*% est_matrix[colnames(l1_matrix), colnames(l2_matrix), n_s] %*% t(l2_matrix)
num_est_samples[,,n_s] <- num_l1_matrix %*% est_matrix[colnames(num_l1_matrix), colnames(l2_matrix), n_s] %*% t(l2_matrix)
}
}
#table_m <- construct.table(est_samples, attr(l1_matrix, 'levels'), attr(l2_matrix, 'levels'))
table_m <- construct.effect.table(est_samples, attr(l1_matrix, 'levels'), attr(l2_matrix, 'levels'),
num_est_samples, attr(num_l1_matrix, 'levels'), attr(l2_matrix, 'levels'), factor_values, numeric_name)
table_list[[table_list_index]] <- table_m
table_list_index = table_list_index + 1
}
}
if (factor_in_l2 & numeric_in_l1 ){
# find if there are moderators interacts with the factor
factor_assign <- which (rownames(model1_level2_var_matrix) == factor_name)
#numeric_assign <- which (rownames(model1_level1_var_matrix) == numeric_name)
interaction_list <- attr(sol_1$dMatrice$Z, "interactions_num")
interaction_list_index <- attr(sol_1$dMatrice$Z, "interactions_numeric_index")
factor_interaction_list <- list()
factor_interaction_list_index <- array()
j = 1
if (length(interaction_list) > 0){
for (i in 1:length(interaction_list)){
if (factor_assign %in% interaction_list[[i]]){
factor_interaction_list[[j]] = interaction_list[[i]]
factor_interaction_list_index[j] = interaction_list_index[i]
j = j + 1
}
}
}
interaction_list <- attr(sol_1$dMatrice$X, "interactions") # if the factor is not numeric
interaction_list_index <- attr(sol_1$dMatrice$X, "interactions_index")
if (length(interaction_list) > 0){
for (i in 1:length(interaction_list)){
if (factor_assign %in% interaction_list[[i]]){
factor_interaction_list[[j]] = interaction_list[[i]]
factor_interaction_list_index[j] = interaction_list_index[i]
j = j + 1
}
}
}
l1_values <- attr(sol_1$dMatrice$X, 'varValues')
# vars <- as.character(attr(attr(sol_1$mf1, 'terms'), 'variables'))[-1]
# response_ind <- attr(attr(sol_1$mf1, 'terms'), 'response')
# response_name <- vars[response_ind]
# #remove the response value from l1_values
# to_rm_res <- 0
# for (i in 1:length(l1_values)){
# if (attr(l1_values[[i]], 'var_names') == response_name) to_rm_res <- i
# }
# l1_values[[to_rm_res]] <- NULL
if (length(l1_values) == 0){
# only intercept included
l1_matrix <- model.matrix(~1)
l1_matrix <- rbind(l1_matrix, c(1))
attr(l1_matrix, "levels") <- l1_matrix
}else{
num_l1_matrix <- effect.matrix.mediator(interaction_factors = l1_values,
matrix_formula=formula(attr(sol_1$mf1, 'terms')),
mediator=numeric_name,
flood_values = flood_values, contrast = sol_1$contrast)
l1_matrix <- effect.matrix.mediator(interaction_factors = l1_values,
matrix_formula=formula(attr(sol_1$mf1, 'terms')),
xvar=numeric_name,
intercept_include = TRUE,
flood_values = flood_values,
contrast = sol_1$contrast)
}
l2_values <- attr(sol_1$dMatrice$Z, 'varValues')
if (length(l2_values) == 0){
# only intercept included
num_l2_matrix <- model.matrix(~1)
num_l2_matrix <- rbind(num_l2_matrix, c(1))
attr(num_l2_matrix, "levels") <- num_l2_matrix
if (sol_1$single_level){
colnames(num_l2_matrix) <- c(" ")
}
}else{
num_l2_matrix <- effect.matrix.mediator(interaction_factors = l2_values,
matrix_formula=formula(attr(sol_1$mf2, 'terms')),
mediator = factor_name,
flood_values = flood_values,
contrast = sol_1$contrast)
}
num_est_samples <- array(0, dim = c(nrow(num_l1_matrix), nrow(num_l2_matrix), n_sample))
for (n_s in 1:n_sample){
num_est_samples[,,n_s] <- num_l1_matrix %*% est_matrix[colnames(num_l1_matrix), colnames(num_l2_matrix), n_s] %*% t(num_l2_matrix)
}
if (length(factor_interaction_list) > 0){
#l2_values <- attr(sol_1$dMatrice$Z, 'varValues')
factor_interaction_effect_matrix <- list()
for (i in 1:length(factor_interaction_list)){
# l2 matrix
factor_interaction_effect_matrix[[i]] <- effect.matrix.mediator(interaction_factors = l2_values[factor_interaction_list[[i]]],
mediator=factor_name,
xvar=numeric_name,
flood_values = flood_values,
contrast = sol_1$contrast)
est_samples <- array(0, dim = c(nrow(l1_matrix), nrow(factor_interaction_effect_matrix[[i]]), n_sample))
for (n_s in 1:n_sample){
est_samples[,,n_s] <- l1_matrix %*% est_matrix[colnames(l1_matrix), colnames(factor_interaction_effect_matrix[[i]]), n_s] %*% t(factor_interaction_effect_matrix[[i]])
}
#TODO use a list to store
#table_m <- construct.table(est_samples, attr(l1_matrix, 'levels'), attr(mediator_interaction_effect_matrix[[i]], 'levels'))
table_m <- construct.effect.table(est_samples, attr(l1_matrix, 'levels'), attr(factor_interaction_effect_matrix[[i]], 'levels'),
num_est_samples, attr(num_l1_matrix, 'levels'), attr(num_l2_matrix, 'levels'), l2_values[factor_assign], numeric_name)
table_list[[table_list_index]] <- table_m
table_list_index = table_list_index + 1
}
}else{
l2_values <- attr(sol_1$dMatrice$Z, 'varValues')
# no interaction with the mediator in level 2, only select the mediator
l2_matrix <- effect.matrix.mediator(l2_values[factor_assign],
mediator= factor_name,
flood_values = flood_values, contrast = sol_1$contrast)
est_samples <- array(0, dim = c(nrow(l1_matrix), nrow(l2_matrix), n_sample))
for (n_s in 1:n_sample){
est_samples[,,n_s] <- l1_matrix %*% est_matrix[colnames(l1_matrix), colnames(l2_matrix), n_s] %*% t(l2_matrix)
}
#table_m <- construct.table(est_samples, attr(l1_matrix, 'levels'), attr(l2_matrix, 'levels'))
table_m <- construct.effect.table(est_samples, attr(l1_matrix, 'levels'), attr(l2_matrix, 'levels'),
num_est_samples, attr(num_l1_matrix, 'levels'), attr(num_l2_matrix, 'levels'), l2_values[factor_assign], numeric_name)
table_list[[table_list_index]] <- table_m
table_list_index = table_list_index + 1
}
# est_samples <- array(0, dim = c(nrow(l1_matrix), nrow(l2_matrix), n_sample))
# for (n_s in 1:n_sample){
# est_samples[,,n_s] <- l1_matrix %*% est_matrix[colnames(l1_matrix), colnames(l2_matrix), n_s] %*% t(l2_matrix)
# }
# table_m <- construct.table(est_samples, attr(l1_matrix, 'levels'), attr(l2_matrix, 'levels'))
# table_list[[table_list_index]] <- table_m
# table_list_index = table_list_index + 1
}
if (factor_in_l2 & numeric_in_l2 ){
# find if there are moderators interacts with the factor except the numeric
# find if there are moderators interacts with the factor
factor_assign <- which (rownames(model1_level2_var_matrix) == factor_name)
numeric_assign <- which (rownames(model1_level2_var_matrix) == numeric_name)
interaction_list <- attr(sol_1$dMatrice$Z, "interactions_num")
interaction_list_index <- attr(sol_1$dMatrice$Z, "interactions_numeric_index")
factor_interaction_list <- list()
factor_interaction_list_index <- array()
j = 1
if (length(interaction_list) > 0){
for (i in 1:length(interaction_list)){
if (factor_assign %in% interaction_list[[i]] && !(numeric_assign %in% interaction_list[[i]])){
factor_interaction_list[[j]] = interaction_list[[i]]
factor_interaction_list_index[j] = interaction_list_index[i]
j = j + 1
}
}
}
interaction_list <- attr(sol_1$dMatrice$X, "interactions") # if the factor is not numeric
interaction_list_index <- attr(sol_1$dMatrice$X, "interactions_index")
if (length(interaction_list) > 0){
for (i in 1:length(interaction_list)){
if (factor_assign %in% interaction_list[[i]]){
factor_interaction_list[[j]] = interaction_list[[i]]
factor_interaction_list_index[j] = interaction_list_index[i]
j = j + 1
}
}
}
l1_values <- attr(sol_1$dMatrice$X, 'varValues')
# exclude y var
# find the response variable
# vars <- as.character(attr(attr(sol_1$mf1, 'terms'), 'variables'))[-1]
# response_ind <- attr(attr(sol_1$mf1, 'terms'), 'response')
# response_name <- vars[response_ind]
# #remove the response value from l1_values
# to_rm_res <- 0
# for (i in 1:length(l1_values)){
# if (attr(l1_values[[i]], 'var_names') == response_name) to_rm_res <- i
# }
# l1_values[[to_rm_res]] <- NULL
if (length(l1_values) == 0){
# only intercept included
l1_matrix <- model.matrix(~1)
l1_matrix <- rbind(l1_matrix, c(1))
attr(l1_matrix, "levels") <- l1_matrix
}else{
l1_matrix <- effect.matrix.mediator(interaction_factors = l1_values,
matrix_formula=formula(attr(sol_1$mf1, 'terms')),
flood_values = flood_values, contrast = sol_1$contrast)
}
l2_values <- attr(sol_1$dMatrice$Z, 'varValues')
num_l2_matrix <- effect.matrix.mediator(l2_values,
matrix_formula=formula(attr(sol_1$mf2, 'terms')),
mediator=factor_name,
xvar = numeric_name,
xvar_include = TRUE,
flood_values = flood_values,
contrast = sol_1$contrast)
num_est_samples <- array(0, dim = c(nrow(l1_matrix), nrow(num_l2_matrix), n_sample))
for (n_s in 1:n_sample)
num_est_samples[,,n_s] <- l1_matrix %*% est_matrix[colnames(l1_matrix), colnames(num_l2_matrix), n_s] %*% t(num_l2_matrix)
if (length(factor_interaction_list) > 0){
#l2_values <- attr(sol_1$dMatrice$Z, 'varValues')
factor_interaction_effect_matrix <- list()
for (i in 1:length(factor_interaction_list)){
# l2 matrix
factor_interaction_effect_matrix[[i]] <- effect.matrix.mediator(interaction_factors = l2_values[factor_interaction_list[[i]]],
mediator=factor_name,
xvar=numeric_name,
flood_values = flood_values,
contrast = sol_1$contrast)
est_samples <- array(0, dim = c(nrow(l1_matrix), nrow(factor_interaction_effect_matrix[[i]]), n_sample))
for (n_s in 1:n_sample){
est_samples[,,n_s] <- l1_matrix %*% est_matrix[colnames(l1_matrix), colnames(factor_interaction_effect_matrix[[i]]), n_s] %*% t(factor_interaction_effect_matrix[[i]])
}
#TODO use a list to store
#table_m <- construct.table(est_samples, attr(l1_matrix, 'levels'), attr(mediator_interaction_effect_matrix[[i]], 'levels'))
table_m <- construct.effect.table(est_samples, attr(l1_matrix, 'levels'), attr(factor_interaction_effect_matrix[[i]], 'levels'),
num_est_samples, attr(l1_matrix, 'levels'), attr(num_l2_matrix, 'levels'), l2_values[factor_assign], numeric_name)
table_list[[table_list_index]] <- table_m
table_list_index = table_list_index + 1
}
}else{
l2_values <- attr(sol_1$dMatrice$Z, 'varValues')
# no interaction with the mediator in level 2, only select the mediator
l2_matrix <- effect.matrix.mediator(l2_values[factor_assign],
mediator= factor_name,
flood_values = flood_values, contrast = sol_1$contrast)
est_samples <- array(0, dim = c(nrow(l1_matrix), nrow(l2_matrix), n_sample))
for (n_s in 1:n_sample){
est_samples[,,n_s] <- l1_matrix %*% est_matrix[colnames(l1_matrix), colnames(l2_matrix), n_s] %*% t(l2_matrix)
}
#table_m <- construct.table(est_samples, attr(l1_matrix, 'levels'), attr(l2_matrix, 'levels'))
table_m <- construct.effect.table(est_samples, attr(l1_matrix, 'levels'), attr(l2_matrix, 'levels'),
num_est_samples, attr(l1_matrix, 'levels'), attr(num_l2_matrix, 'levels'), l2_values[factor_assign], numeric_name)
table_list[[table_list_index]] <- table_m
table_list_index = table_list_index + 1
}
# l2_values <- attr(sol_1$dMatrice$Z, 'varValues')
# num_l2_matrix <- effect.matrix.mediator(l2_values, mediator=factor_name, xvar = numeric_name, xvar_include = TRUE)
# num_est_samples <- array(0, dim = c(nrow(l1_matrix), nrow(num_l2_matrix), n_sample))
# for (n_s in 1:n_sample)
# num_est_samples[,,n_s] <- l1_matrix %*% est_matrix[colnames(l1_matrix), colnames(num_l2_matrix), n_s] %*% t(num_l2_matrix)
#
# table_m <- construct.table(est_samples, attr(l1_matrix, 'levels'), attr(l2_matrix, 'levels'))
# table_list[[table_list_index]] <- table_m
# table_list_index = table_list_index + 1
}
return(table_list)
}
construct.effect.table <-
function (est_samples, row_name, col_name, num_est_samples, num_row_name, num_col_name, factor_values, numeric_name){
n_sample <- dim(est_samples)[3]
sample_names <- paste('sample_', 1:n_sample, sep = "")
table_f <- generate.table.samples(est_samples, row_name, col_name)
table_num <- generate.table.samples(num_est_samples, num_row_name, num_col_name)
names_to_merge <- intersect(c(colnames(row_name), colnames(col_name)), c(colnames(num_row_name), colnames(num_col_name)))
samples_tb <- merge(table_f$tb, table_num$tb, by = names_to_merge, all.x = TRUE, suffixes = c(".x",".y"))
names_union <- union(c(colnames(row_name), colnames(col_name)), c(colnames(num_row_name), colnames(num_col_name)))
# calculate floodlights
floodlight_table <- array(NA, dim = c(nrow(samples_tb), length(names_union) + 3), dimnames = list(rep("",nrow(samples_tb)), c(names_union,'mean', '2.5%', '97.5%')))
floodlight_table[, names_union] <- as.matrix(samples_tb[, names_union])
for (i in 1: nrow(samples_tb)){
sample_values <- -as.numeric(as.matrix(samples_tb[i, paste(sample_names, ".x", sep = "")]))/as.numeric(as.matrix(samples_tb[i, paste(sample_names, ".y", sep = "")]))
floodlight_table[i, 'mean'] <- round(mean(sample_values, na.rm = TRUE), digits = 4)
floodlight_table[i, '2.5%'] <- round(quantile(sample_values, probs = 0.025, na.rm = TRUE), digits = 4)
floodlight_table[i, '97.5%'] <- round(quantile(sample_values, probs = 0.975, na.rm = TRUE), digits = 4)
}
if (length(factor_values) > 1) stop("The format of the factor values error!")
factor_name <- attr(factor_values[[1]], "var_names")
# select only one value of the factor
num_levels <- length(unique(factor_values[[1]]))
if (num_levels > 2) stop("The number of levels of the factor is greater than 2. This is not supported yet.", call. = FALSE)
if (num_levels == 1) stop("The number of levels of the factor should be equal to two.", call. = FALSE)
floodlight_table <- subset(floodlight_table, floodlight_table[, factor_name] == as.character(factor_values[[1]][1]))
if (numeric_name %in% colnames(floodlight_table)) floodlight_table <- floodlight_table[, -which(colnames(floodlight_table) == numeric_name), drop = FALSE]
if (factor_name %in% colnames(floodlight_table)) floodlight_table <- floodlight_table[, -which(colnames(floodlight_table) == factor_name), drop = FALSE]
if ("(Intercept)" %in% colnames(floodlight_table)) floodlight_table <- floodlight_table[, -which(colnames(floodlight_table) == "(Intercept)"), drop = FALSE]
# attach a column named numeric : factor
rownames(floodlight_table) <- rep(paste(factor_name, ":", numeric_name), nrow(floodlight_table))
return(floodlight_table)
}
generate.table.samples <- function(est_samples, row_name, col_name){
n_sample <- dim(est_samples)[3]
table_f <- array(NA, dim = c(nrow(row_name) * nrow(col_name), ncol(row_name) + ncol(col_name) + n_sample),
dimnames = list(rep("", nrow(row_name) * nrow(col_name)), c(colnames(row_name), colnames(col_name), paste('sample_', 1:n_sample, sep = ""))))
table_f_index <- array(NA, dim = c(nrow(row_name) * nrow(col_name), 2),
dimnames = list(NULL, c('est_samples_row_index', 'est_samples_col_index')))
for (k1 in 1:nrow(row_name)){
temp <- ((k1-1) * nrow(col_name) + 1):((k1-1) * nrow(col_name) + nrow(col_name))
table_f[temp, 1:ncol(row_name)] <- t(replicate(nrow(col_name), row_name[k1, ]))
table_f[temp, (ncol(row_name) + 1) : (ncol(row_name) + ncol(col_name))] <- col_name
table_f_index[temp,1] <- k1
table_f_index[temp,2] <- 1:nrow(col_name)
r_ind <- temp[1] - 1
for (c_ind in 1:nrow(col_name)){
for(s_ind in 1:n_sample){
table_f[r_ind + c_ind, paste('sample_',s_ind, sep ="")] <- est_samples[k1,c_ind,s_ind]
}
}
}
return(list(tb = table_f, tb_ind <- table_f_index))
}
construct.table <-
function (est_samples, row_name, col_name){
means <- apply(est_samples, c(1,2), mean)
quantile_025 <- apply(est_samples, c(1,2), quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_samples, c(1,2), quantile, probs = 0.975, type = 3, na.rm = FALSE)
table_m <- array(NA, dim = c(nrow(row_name) * nrow(col_name), ncol(row_name) + ncol(col_name) + 3),
dimnames = list(rep("", nrow(row_name) * nrow(col_name)), c(colnames(row_name), colnames(col_name),'mean', '2.5%', '97.5%')))
table_m_index <- array(NA, dim = c(nrow(row_name) * nrow(col_name), 2),
dimnames = list(NULL, c('est_samples_row_index', 'est_samples_col_index')))
for (k1 in 1:nrow(row_name)){
temp <- ((k1-1) * nrow(col_name) + 1):((k1-1) * nrow(col_name) + nrow(col_name))
table_m[temp, 1:ncol(row_name)] <- t(replicate(nrow(col_name), row_name[k1, ]))
table_m[temp, (ncol(row_name) + 1) : (ncol(row_name) + ncol(col_name))] <- col_name
table_m_index[temp,1] <- k1
table_m_index[temp,2] <- 1:nrow(col_name)
table_m[temp, ncol(row_name) + ncol(col_name) + 1] <- round(means[k1,], digits = 4)
table_m[temp, ncol(row_name) + ncol(col_name) + 2] <- pmin(round(quantile_025[k1,], digits = 4), round(quantile_975[k1,], digits = 4))
table_m[temp, ncol(row_name) + ncol(col_name) + 3] <- pmax(round(quantile_025[k1,], digits = 4), round(quantile_975[k1,], digits = 4))
}
# reorder table_m column names, sort values column by column, keep the order of table_m_index
table_mediator <- list(table_m = table_m, index_name = table_m[, 1: (ncol(row_name) + ncol(col_name)), drop = F], index = table_m_index, samples = est_samples)
return(table_mediator )
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/cal.flood.effects.R |
# this function outputs effects of the mediator (sum of all coefficients related to
# the mediator for each combination of moderators except the xvar)in the model sol_1
cal.mediation.effects <-
function (sol_1, est_matrix, n_sample, mediator, xvar = NA){
table_list <- list()
table_list_index <- 1
model1_level1_var_matrix <- attr(attr(sol_1$mf1, 'terms'),'factors')
model1_level1_var_dataClasses <- attr(attr(sol_1$mf1, 'terms'),'dataClasses')
model1_level2_var_matrix <- attr(attr(sol_1$mf2, 'terms'),'factors')
model1_level2_var_dataClasses <- attr(attr(sol_1$mf2, 'terms'),'dataClasses')
# for each level of xvar, need to check xvar in level 1 or 2
# find the mediator in the model and all other variables interacts with the mediator at the same level(moderators)
# then find the coefficient of the mediator (for each combination of moderators) in model 1
# algo:
# e.g. (mediator, interactions) x (estimation matrix) x (all vars except xvar including other moderators), mediator(continuous, normal): value 1 since we only look at the coefficients
# or (all vars except xvar including other moderators) x (estimation matrix) x (mediator, interactions) if the mediator is at the btw. level
# then find the coefficient of the xvar in model 2 (for each combination of moderators)
# algo:
# e.g. (xvar, interactions) x (estimation matrix) x (all vars except xvar including other moderators)
# or (all vars except xvar including other moderators) x (estimation matrix) x (xvar, interactions) if the mediator is at the btw. level
# Finally, join these two tables by common moderators
# TODO: create a common function to deal with above two algos
### calculate mediation effects in model 1
#if (attr(xvar, 'class') == 'numeric' || attr(xvar, 'class') == 'integer'){
mediator_in_l1 <- mediator %in% rownames(model1_level1_var_matrix)
mediator_in_l2 <- mediator %in% rownames(model1_level2_var_matrix)
if (!mediator_in_l1 & !mediator_in_l2) stop(mediator," is not included in the model!")
# mediator is at level 1
if (mediator_in_l1){
# find if there are moderators interacts with the mediator
mediator_assign <- which (rownames(model1_level1_var_matrix) == mediator)
interaction_list <- attr(sol_1$dMatrice$X, "interactions_num") # if the mediator is numeric
interaction_list_index <- attr(sol_1$dMatrice$X, "interactions_numeric_index")
mediator_interaction_list <- list()
mediator_interaction_list_index <- array()
j = 1
if (length(interaction_list) > 0){
for (i in 1:length(interaction_list)){
if (mediator_assign %in% interaction_list[[i]]){
mediator_interaction_list[[j]] = interaction_list[[i]]
mediator_interaction_list_index[j] = interaction_list_index[i]
j = j + 1
}
}
}
interaction_list <- attr(sol_1$dMatrice$X, "interactions") # if the mediator is not numeric
interaction_list_index <- attr(sol_1$dMatrice$X, "interactions_index")
if (length(interaction_list) > 0){
for (i in 1:length(interaction_list)){
if (mediator_assign %in% interaction_list[[i]]){
mediator_interaction_list[[j]] = interaction_list[[i]]
mediator_interaction_list_index[j] = interaction_list_index[i]
j = j + 1
}
}
}
# for each interaction in mediator_interaction_list create a moderated mediation table (exclude main effects)
# calculate l2 matrix first using all params but xvar, also using l2 formula
# TOFIX: what about the case only intercept included
l2_values <- attr(sol_1$dMatrice$Z, 'varValues')
if (length(l2_values) == 0){
# only intercept included
l2_matrix <- model.matrix(~1)
l2_matrix <- rbind(l2_matrix, c(1))
attr(l2_matrix, "levels") <- l2_matrix
if (sol_1$single_level){
colnames(l2_matrix) <- c(" ")
}
}else{
l2_matrix <- effect.matrix.mediator(interaction_factors = l2_values, matrix_formula=formula(attr(sol_1$mf2, 'terms')), xvar=xvar, contrast = sol_1$contrast)
}
if (length(mediator_interaction_list) > 0){
l1_values <- attr(sol_1$dMatrice$X, 'varValues')
mediator_interaction_effect_matrix <- list()
for (i in 1:length(mediator_interaction_list)){
# l1 matrix
# TO check:
# y var is also included in l1_values, interaction_list has considered this
mediator_interaction_effect_matrix[[i]] <- effect.matrix.mediator(interaction_factors = l1_values[mediator_interaction_list[[i]]], mediator=mediator, xvar=xvar, contrast = sol_1$contrast)
est_samples <- array(0, dim = c(nrow(mediator_interaction_effect_matrix[[i]]), nrow(l2_matrix), n_sample))
for (n_s in 1:n_sample)
est_samples[,,n_s] <- mediator_interaction_effect_matrix[[i]] %*% est_matrix[colnames(mediator_interaction_effect_matrix[[i]]), colnames(l2_matrix), n_s] %*% t(l2_matrix)
table_m <- construct.table(est_samples, attr(mediator_interaction_effect_matrix[[i]], 'levels'), attr(l2_matrix, 'levels'))
table_list[[table_list_index]] <- table_m
table_list_index = table_list_index + 1
}
}else{
l1_values <- attr(sol_1$dMatrice$X, 'varValues')
# no interaction with the mediator in level 1, only select the mediator
# TO check:
# y var is also included in l1_values, interaction_list has considered this
l1_matrix <- effect.matrix.mediator(l1_values[mediator_assign], mediator=mediator, contrast = sol_1$contrast)
est_samples <- array(0, dim = c(nrow(l1_matrix), nrow(l2_matrix), n_sample))
for (n_s in 1:n_sample)
est_samples[,,n_s] <- l1_matrix %*% est_matrix[colnames(l1_matrix), colnames(l2_matrix), n_s] %*% t(l2_matrix)
table_m <- construct.table(est_samples, attr(l1_matrix, 'levels'), attr(l2_matrix, 'levels'))
table_list[[table_list_index]] <- table_m
table_list_index = table_list_index + 1
}
}
if (mediator_in_l2){
# find if there are moderators interacts with the mediator
mediator_assign <- which(rownames(model1_level2_var_matrix) == mediator)
interaction_list <- attr(sol_1$dMatrice$Z, "interactions_num")
interaction_list_index <- attr(sol_1$dMatrice$Z, "interactions_numeric_index")
mediator_interaction_list <- list()
mediator_interaction_list_index <- array()
j = 1
if (length(interaction_list) > 0){
for (i in 1:length(interaction_list)){
if (mediator_assign %in% interaction_list[[i]]){
mediator_interaction_list[[j]] = interaction_list[[i]]
mediator_interaction_list_index[j] = interaction_list_index[i]
j = j + 1
}
}
}
interaction_list <- attr(sol_1$dMatrice$Z, "interactions") # if the mediator is not numeric
interaction_list_index <- attr(sol_1$dMatrice$Z, "interactions_index")
if (length(interaction_list) > 0){
for (i in 1:length(interaction_list)){
if (mediator_assign %in% interaction_list[[i]]){
mediator_interaction_list[[j]] = interaction_list[[i]]
mediator_interaction_list_index[j] = interaction_list_index[i]
j = j + 1
}
}
}
# for each interaction in mediator_interaction_list create a moderated mediation table (exclude main effects)
# calculate l1 matrix first using all params but xvar, also using l1 formula
l1_values <- attr(sol_1$dMatrice$X, 'varValues')
# exclude y var
l1_values <- l1_values[-1]
if (length(l1_values) == 0){
# only intercept included
l1_matrix <- model.matrix(~1)
l1_matrix <- rbind(l1_matrix, c(1))
attr(l1_matrix, "levels") <- l1_matrix
}else{
form <- formula(attr(sol_1$mf1, 'terms'))
newform <- stats::update(form, NULL ~ .)
l1_matrix <- effect.matrix.mediator(interaction_factors = l1_values, matrix_formula=newform, xvar=xvar, contrast = sol_1$contrast)
}
if (length(mediator_interaction_list) > 0){
l2_values <- attr(sol_1$dMatrice$Z, 'varValues')
mediator_interaction_effect_matrix <- list()
for (i in 1:length(mediator_interaction_list)){
# l2 matrix
mediator_interaction_effect_matrix[[i]] <- effect.matrix.mediator(interaction_factors = l2_values[mediator_interaction_list[[i]]], mediator=mediator, xvar=xvar, contrast = sol_1$contrast)
est_samples <- array(0, dim = c(nrow(l1_matrix), nrow(mediator_interaction_effect_matrix[[i]]), n_sample))
for (n_s in 1:n_sample){
est_samples[,,n_s] <- l1_matrix %*% est_matrix[colnames(l1_matrix), colnames(mediator_interaction_effect_matrix[[i]]), n_s] %*% t(mediator_interaction_effect_matrix[[i]])
}
#TODO use a list to store
table_m <- construct.table(est_samples, attr(l1_matrix, 'levels'), attr(mediator_interaction_effect_matrix[[i]], 'levels'))
table_list[[table_list_index]] <- table_m
table_list_index = table_list_index + 1
}
}else{
l2_values <- attr(sol_1$dMatrice$Z, 'varValues')
# no interaction with the mediator in level 2, only select the mediator
l2_matrix <- effect.matrix.mediator(l2_values[mediator_assign], mediator=mediator, contrast = sol_1$contrast)
est_samples <- array(0, dim = c(nrow(l1_matrix), nrow(l2_matrix), n_sample))
for (n_s in 1:n_sample){
est_samples[,,n_s] <- l1_matrix %*% est_matrix[colnames(l1_matrix), colnames(l2_matrix), n_s] %*% t(l2_matrix)
}
table_m <- construct.table(est_samples, attr(l1_matrix, 'levels'), attr(l2_matrix, 'levels'))
table_list[[table_list_index]] <- table_m
table_list_index = table_list_index + 1
}
}
return(table_list)
}
construct.table <-
function (est_samples, row_name, col_name){
means <- apply(est_samples, c(1,2), mean)
quantile_025 <- apply(est_samples, c(1,2), quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_samples, c(1,2), quantile, probs = 0.975, type = 3, na.rm = FALSE)
table_m <- array(NA, dim = c(nrow(row_name) * nrow(col_name), ncol(row_name) + ncol(col_name) + 3),
dimnames = list(rep("", nrow(row_name) * nrow(col_name)), c(colnames(row_name), colnames(col_name),'mean', '2.5%', '97.5%')))
table_m_index <- array(NA, dim = c(nrow(row_name) * nrow(col_name), 2),
dimnames = list(NULL, c('est_samples_row_index', 'est_samples_col_index')))
for (k1 in 1:nrow(row_name)){
temp <- ((k1-1) * nrow(col_name) + 1):((k1-1) * nrow(col_name) + nrow(col_name))
table_m[temp, 1:ncol(row_name)] <- t(replicate(nrow(col_name), row_name[k1, ]))
table_m[temp, (ncol(row_name) + 1) : (ncol(row_name) + ncol(col_name))] <- col_name
table_m_index[temp,1] <- k1
table_m_index[temp,2] <- 1:nrow(col_name)
table_m[temp, ncol(row_name) + ncol(col_name) + 1] <- round(means[k1,], digits = 4)
table_m[temp, ncol(row_name) + ncol(col_name) + 2] <- pmin(round(quantile_025[k1,], digits = 4), round(quantile_975[k1,], digits = 4))
table_m[temp, ncol(row_name) + ncol(col_name) + 3] <- pmax(round(quantile_025[k1,], digits = 4), round(quantile_975[k1,], digits = 4))
}
# reorder table_m column names, sort values column by column, keep the order of table_m_index
table_mediator <- list(table_m = table_m, index_name = table_m[, 1: (ncol(row_name) + ncol(col_name)), drop = F], index = table_m_index, samples = est_samples)
return(table_mediator )
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/cal.mediation.effects.R |
# this function outputs effects of the mediator (sum of all coefficients related to
# the mediator for each combination of moderators except the xvar)in the model sol_1 at the individual level
cal.mediation.effects.individual <- function (sol_1,
est_matrix,
mediator,
xvar = NA,
is_mediator = F){
table_list <- list()
table_list_index <- 1
model1_level1_var_matrix <- attr(attr(sol_1$mf1, 'terms'),'factors')
model1_level1_var_dataClasses <- attr(attr(sol_1$mf1, 'terms'),'dataClasses')
model1_level2_var_matrix <- attr(attr(sol_1$mf2, 'terms'),'factors')
model1_level2_var_dataClasses <- attr(attr(sol_1$mf2, 'terms'),'dataClasses')
num_l1 = dim(est_matrix)[1]
n_sample = dim(est_matrix)[2]
num_id = dim(est_matrix)[3]
### calculate mediation effects in model 1
#if (attr(xvar, 'class') == 'numeric' || attr(xvar, 'class') == 'integer'){
mediator_in_l1 <- mediator %in% rownames(model1_level1_var_matrix)
mediator_in_l2 <- mediator %in% rownames(model1_level2_var_matrix)
if (!mediator_in_l1 & !mediator_in_l2) stop(mediator," is not included in the model!")
# mediator is at level 1
if (mediator_in_l1){
# find if there are moderators interacts with the mediator
mediator_assign <- which (rownames(model1_level1_var_matrix) == mediator)
interaction_list <- attr(sol_1$dMatrice$X, "interactions_num") # if the mediator is numeric
interaction_list_index <- attr(sol_1$dMatrice$X, "interactions_numeric_index")
mediator_interaction_list <- list()
mediator_interaction_list_index <- array()
j = 1
if (length(interaction_list) > 0){
for (i in 1:length(interaction_list)){
if (mediator_assign %in% interaction_list[[i]]){
mediator_interaction_list[[j]] = interaction_list[[i]]
mediator_interaction_list_index[j] = interaction_list_index[i]
j = j + 1
}
}
}
interaction_list <- attr(sol_1$dMatrice$X, "interactions") # if the mediator is not numeric
interaction_list_index <- attr(sol_1$dMatrice$X, "interactions_index")
if (length(interaction_list) > 0){
for (i in 1:length(interaction_list)){
if (mediator_assign %in% interaction_list[[i]]){
mediator_interaction_list[[j]] = interaction_list[[i]]
mediator_interaction_list_index[j] = interaction_list_index[i]
j = j + 1
}
}
}
if (length(mediator_interaction_list) > 0){
l1_values <- attr(sol_1$dMatrice$X, 'varValues')
mediator_interaction_effect_matrix <- list()
for (i in 1:length(mediator_interaction_list)){
# l1 matrix
# TO check:
# y var is also included in l1_values, interaction_list has considered this
mediator_interaction_effect_matrix[[i]] <- effect.matrix.mediator(interaction_factors = l1_values[mediator_interaction_list[[i]]], mediator=mediator, xvar=xvar, contrast = sol_1$contrast)
est_samples <- array(0, dim = c(nrow(mediator_interaction_effect_matrix[[i]]), n_sample, num_id))
for (n_id in 1:num_id)
est_samples[,,n_id] <- mediator_interaction_effect_matrix[[i]] %*% est_matrix[colnames(mediator_interaction_effect_matrix[[i]]),, n_id]
table_m <- construct.table.individual(est_samples, attr(mediator_interaction_effect_matrix[[i]], 'levels'))
table_list[[table_list_index]] <- table_m
table_list_index = table_list_index + 1
}
}else{
l1_values <- attr(sol_1$dMatrice$X, 'varValues')
# no interaction with the mediator in level 1, only select the mediator
# TO check:
# y var is also included in l1_values, interaction_list has considered this
l1_matrix <- effect.matrix.mediator(l1_values[mediator_assign], mediator=mediator, contrast = sol_1$contrast)
est_samples <- array(0, dim = c(nrow(l1_matrix), n_sample, num_id))
for (n_id in 1:num_id)
est_samples[,,n_id] <- l1_matrix %*% est_matrix[colnames(l1_matrix),, n_id]
table_m <- construct.table.individual(est_samples, attr(l1_matrix, 'levels'))
table_list[[table_list_index]] <- table_m
table_list_index = table_list_index + 1
}
}
if (mediator_in_l2){ # xvar in level 2
if (is_mediator){
stop("The mediator is between subjects, please set individual = FALSE.")
}
}
return(table_list)
}
construct.table.individual <-
function (est_samples, row_name){
num_id = dim(est_samples)[3]
means <- apply(est_samples, c(1,3), mean)
quantile_025 <- apply(est_samples, c(1,3), quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_samples, c(1,3), quantile, probs = 0.975, type = 3, na.rm = FALSE)
table_m <- array(NA, dim = c(nrow(row_name), ncol(row_name) + 3, num_id),
dimnames = list(rep("", nrow(row_name)), c(colnames(row_name), 'mean', '2.5%', '97.5%'), NULL))
table_m_index <- array(NA, dim = c(nrow(row_name), 1),
dimnames = list(NULL, c('est_samples_row_index')))
for (n_id in 1:num_id){
for (k1 in 1:nrow(row_name)){
temp <- k1
table_m[temp, 1:ncol(row_name), n_id] <- row_name[k1, ]
#table_m[temp, (ncol(row_name) + 1) : (ncol(row_name) + ncol(col_name))] <- col_name
table_m_index[temp,1] <- k1
#table_m_index[temp,2] <- 1:nrow(col_name)
table_m[temp, ncol(row_name) + 1, n_id] <- round(means[k1,n_id], digits = 4)
table_m[temp, ncol(row_name) + 2, n_id] <- pmin(round(quantile_025[k1,n_id], digits = 4), round(quantile_975[k1,n_id], digits = 4))
table_m[temp, ncol(row_name) + 3, n_id] <- pmax(round(quantile_025[k1,n_id], digits = 4), round(quantile_975[k1,n_id], digits = 4))
}
}
# reorder table_m column names, sort values column by column, keep the order of table_m_index
table_mediator <- list(table_m = table_m, index_name = row_name, index = table_m_index, samples = est_samples)
return(table_mediator )
} | /scratch/gouwar.j/cran-all/cranData/BANOVA/R/cal.mediation.effects.individual.R |
conv.diag <-
function(x){
if (class(x) %in% c('BANOVA', 'BANOVA.Binomial','BANOVA.Bernoulli',
'BANOVA.Normal', 'BANOVA.T', 'BANOVA.Multinomial','BANOVA.ordMutinomial')){
if (!x$single_level){
if (x$model_name == 'BANOVA.Multinomial')
sol <- conv.geweke.heidel(x$samples_l2_param, colnames(x$dMatrice$X_full[[1]]), colnames(x$dMatrice$Z))
else
sol <- conv.geweke.heidel(x$samples_l2_param, colnames(x$dMatrice$X), colnames(x$dMatrice$Z))
}else{
if (x$model_name == 'BANOVA.Multinomial')
sol <- conv.geweke.heidel(x$samples_l1_param, colnames(x$dMatrice$Z), colnames(x$dMatrice$X_full[[1]]))
else
sol <- conv.geweke.heidel(x$samples_l1_param, colnames(x$dMatrice$Z), colnames(x$dMatrice$X))
}
}
class(sol) <- 'conv.diag'
sol
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/conv.diag.R |
conv.geweke.heidel <-
function (samples_l2_param, X_names, Z_names){
row_names <- array(NA, dim = c(ncol(samples_l2_param),1))
for (i in 1:length(X_names))
for (j in 1:length(Z_names)){
temp <- (i - 1)*length(Z_names) + j
if (X_names[i] == " ")
row_names[temp] <- Z_names[j]
else
row_names[temp] <- paste(X_names[i]," : ", Z_names[j])
}
pass_ind <- T
sol_converge <- coda::geweke.diag(coda::as.mcmc(samples_l2_param),0.2,0.5)
p_values_converge <- 2*pnorm(-abs(sol_converge$z))
decision_conerge <- array(NA,length(p_values_converge))
decision_conerge[p_values_converge>=0.001] <- 'passed'
decision_conerge[p_values_converge<0.001] <- 'failed'
if (sum(p_values_converge<0.001) > 0) pass_ind <- F
sol_geweke <- data.frame('Geweke stationarity test' = decision_conerge, 'Geweke convergence p value' = round(p_values_converge, digits = 4))
#sol_geweke <- data.frame(cbind(decision_conerge, as.numeric(round(p_values_converge, digits = 4))))
#print(str(sol_geweke))
rownames(sol_geweke) <- row_names
colnames(sol_geweke) <- c('Geweke stationarity test','Geweke convergence p value')
hddata <- samples_l2_param
colnames(hddata) <- row_names
sol_heidel_temp <- coda::heidel.diag(coda::as.mcmc(hddata))
sol_heidel <- data.frame(H_W_stat = sol_heidel_temp[, 1], H_W_p = round(sol_heidel_temp[, 3], 4))
colnames(sol_heidel) <- c('H. & W. stationarity test', 'H. & W. convergence p value')
#print(sol_heidel)
#sol_heidel[,3] <- round(sol_heidel[,3],4)
#sol_heidel[,3] <- round(sol_heidel[,3],4)
#sol_heidel[,5] <- round(sol_heidel[,5],4)
#sol_heidel[,6] <- round(sol_heidel[,6],4)
if (sum(sol_heidel[,1]<1) > 0) pass_ind <- F
sol_heidel[which(sol_heidel[,1]==1),1]<-'passed'
sol_heidel[which(sol_heidel[,1]<1),1]<-'failed'
sol <- list(sol_geweke = sol_geweke, sol_heidel = sol_heidel, pass_ind = pass_ind)
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/conv.geweke.heidel.R |
design.matrix <-
function(l1_formula = 'NA', l2_formula = 'NA', data, id, contrast = NULL){
tmp_contrasts <- getOption("contrasts")
# error checking
if (l1_formula == 'NA')
stop("Formula in level 1 is missing! In the case of no level 1 factor, please use 'y~1'")
#### 1.1.2
data <- assign_contrast(data, contrast)
####
if (l2_formula == 'NA'){
# stop("Formula in level 2 is missing! In the case of no level 1 factor, please use '~1'")
# one level model
options(contrasts = rep("contr.sum",2)) # use effect coding for both unordered and ordered factors
options(na.action='na.pass') # pass NAs, then check features but not the response(since it's Bayesian)
mf1 <- model.frame(formula = l1_formula, data = data)
y <- model.response(mf1)
if (length(y) == 0) stop('The response variable is not found!')
X <- model.matrix(attr(mf1,'terms'), data = mf1)
if (sum(is.na(X)) > 0) stop('Missing/NA values in level 1 features!')
if (dim(X)[2] == 0) stop('No variables in level 1 model! Please add an intercept at least.')
if (attr(attr(mf1,'terms'),'intercept') != 0) # for tables in outputs
attr(X,'varNames') <- c('(Intercept)',attr(attr(mf1,'terms'),'term.labels'))
else
stop('Intercept in level 1 must be included!')
attr(X,'dataClasses') <- attr(attr(mf1,'terms'),'dataClasses')[-1] # exclude y
attr(X,'varValues') <- get.values(data, mf1)
temp <- get.interactions(mf1)
attr(X,'interactions') <- temp$results
attr(X,'interactions_index') <- temp$index
attr(X,'interactions_num') <- temp$results_num
attr(X,'interactions_numeric_index') <- temp$numeric_index
# find index of numeric variables (covariates) in X
numeric_index <- which(attr(X,'dataClasses') == 'numeric' | attr(X,'dataClasses') == 'integer')
numeric_index <- c(numeric_index, temp$numeric_index) # add interactions including at least one numeric variable
numeric_index_in_X <- array(NA, dim = c(1,length(numeric_index)))
if (length(numeric_index) > 0){
for (i in 1:length(numeric_index)){
numeric_index_in_X[i] <- which(attr(X,'assign') == numeric_index[i])
}
X[,numeric_index_in_X] <- mean.center(X[,numeric_index_in_X])
warning("level 1 numeric variables have been mean centered.\n", call. = F, immediate. = T)
}
attr(X,'numeric_index') <- numeric_index_in_X
Z = NULL
Z_full = NULL
}else{
options(contrasts = rep("contr.sum",2)) # use effect coding for both unordered and ordered factors
options(na.action='na.pass') # pass NAs, then check features but not the response(since it's Bayesian)
mf1 <- model.frame(formula = l1_formula, data = data)
y <- model.response(mf1)
if (length(y) == 0) stop('The response variable is not found!')
X <- model.matrix(attr(mf1,'terms'), data = mf1)
if (sum(is.na(X)) > 0) stop('Missing/NA values in level 1 features!')
if (dim(X)[2] == 0) stop('No variables in level 1 model! Please add an intercept at least.')
if (attr(attr(mf1,'terms'),'intercept') != 0) # for tables in outputs
attr(X,'varNames') <- c('(Intercept)',attr(attr(mf1,'terms'),'term.labels'))
else
stop('Intercept in level 1 must be included!')
attr(X,'dataClasses') <- attr(attr(mf1,'terms'),'dataClasses')[-1] # exclude y
attr(X,'varValues') <- get.values(data, mf1)
temp <- get.interactions(mf1)
attr(X,'interactions') <- temp$results
attr(X,'interactions_index') <- temp$index
attr(X,'interactions_num') <- temp$results_num
attr(X,'interactions_numeric_index') <- temp$numeric_index
# find index of numeric variables (covariates) in X
numeric_index <- which(attr(X,'dataClasses') == 'numeric' | attr(X,'dataClasses') == 'integer')
numeric_index <- c(numeric_index, temp$numeric_index) # add interactions including at least one numeric variable
numeric_index_in_X <- array(NA, dim = c(1,length(numeric_index)))
if (length(numeric_index) > 0){
for (i in 1:length(numeric_index)){
numeric_index_in_X[i] <- which(attr(X,'assign') == numeric_index[i])
}
X[,numeric_index_in_X] <- mean.center(X[,numeric_index_in_X])
warning("level 1 numeric variables have been mean centered.\n", call. = F, immediate. = T)
}
attr(X,'numeric_index') <- numeric_index_in_X
mf2 <- model.frame(formula = l2_formula, data = data)
Z_full <- model.matrix(attr(mf2,'terms'), data = mf2)
if (sum(is.na(Z_full)) > 0) stop('Missing/NA values in level 2 features!')
if (dim(Z_full)[2] == 0) stop('No variables in level 2 model! Please add an intercept at least.')
if (attr(attr(mf2,'terms'),'response') == 1) stop("level 2 model shouldn't include the response! Start with the '~'.")
#convert Z from long format to short format, using the first row of each id
num_id <- length(unique(id))
id_index <- array(NA,dim = c(num_id,1))
for (i in 1:num_id){
index_row <- which(id == i)
# check if it is a good between-subject factor
if (max(index_row) > nrow(Z_full)) stop('ID indicator error!')
for (j in 1:ncol(Z_full))
if (max(Z_full[index_row, j]) != min(Z_full[index_row, j])) stop('Bad between-subject factor!')
id_index[i] <- index_row[1]
}
Z <- as.matrix(Z_full[id_index,])
colnames(Z) <- colnames(Z_full)
if (attr(attr(mf2,'terms'),'intercept') != 0) # for tables in outputs
attr(Z,'varNames') <- c('(Intercept)',attr(attr(mf2,'terms'),'term.labels'))
else
stop('Intercept in level 2 must be included!')
attr(Z,'dataClasses') <- attr(attr(mf2,'terms'),'dataClasses')
attr(Z,'varValues') <- get.values(data, mf2, id_index)
temp <- get.interactions(mf2)
attr(Z,'interactions') <- temp$results
attr(Z,'interactions_index') <- temp$index
attr(Z,'interactions_num') <- temp$results_num
attr(Z,'interactions_numeric_index') <- temp$numeric_index
attr(Z,"assign") <- attr(Z_full,"assign")
attr(Z,"contrasts") <- attr(Z_full,"contrasts")
# find index of numeric variables (covariates) in Z
numeric_index <- which(attr(Z,'dataClasses') == 'numeric' | attr(Z,'dataClasses') == 'integer')
numeric_index <- c(numeric_index, temp$numeric_index) # add interactions including at least one numeric variable
numeric_index_in_Z <- array(NA, dim = c(1,length(numeric_index)))
if (length(numeric_index) > 0){
numeric_index_in_Z <- array(NA, dim = c(1,length(numeric_index)))
for (i in 1:length(numeric_index)){
numeric_index_in_Z[i] <- which(attr(Z,'assign') == numeric_index[i])
}
Z[,numeric_index_in_Z] <- mean.center(Z[,numeric_index_in_Z])
warning("level 2 numeric variables have been mean centered.\n", call. = F, immediate. = T)
}
attr(Z,'numeric_index') <- numeric_index_in_Z
attr(Z_full,'numeric_index') <- numeric_index_in_Z
}
options(contrasts = tmp_contrasts)
result <- list(X = X, Z = Z, Z_full = Z_full, y = y)
return(result)
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/design.matrix.R |
effect.matrix.factor <-
function (factors, assign = array(dim = 0), index_factor = NA, numeric_index = array(dim = 0), contrast = NULL){
# generate the effect matrix for each factor, numerical covariates excluded, TODO: may have various levels for numeric variables
# Args:
# factors : values of factors to generate factor matrix
# assign : index corresponding to each factor in the full design matrix, see X <- model.matrix(attr(mf1,'terms'), data = mf1)
# index_factor : one number, the index of current factor in the full design matrix
# numeric_index : the index of numeric variables in the full design matrix
# Returns:
# a matrix
#
####
# if (length(assign) != 0){
# index <- which(assign == index_factor)
# level <- length(index) + 1
# effect_matrix <- matrix(0, nrow = level, ncol = length(assign))
# effect_matrix[,index] <- contr.sum(level)
# effect_matrix[,1] <- 1 # grand mean included
#if (length(numeric_index) > 0) effect_matrix[, numeric_index] <- 1 # consider the covariates effect
# attr(effect_matrix, 'levels') <- factors
# }
# new version
tmp_contrasts <- getOption("contrasts")
options(contrasts = rep("contr.sum",2))
# TODO combine effect matrix factor with effect matrix interaction
if (length(assign) != 0){
defaultWarn <- getOption("warn")
#ignore of warning messages in the code below
options(warn = -1)
fac_levels <- levels(factors) #extract factor levels
if(is.na(as.numeric(fac_levels[1]))){
#if the factor levels are not labeled with numeric values keep the same labeling
level <- factor(fac_levels, levels = fac_levels, labels = fac_levels)
} else {
fac_levels_numeric <- as.numeric(fac_levels)
dummy_condition <- (length(fac_levels_numeric) == 2) && (0 %in% fac_levels_numeric) && (1 %in% fac_levels_numeric)
effect_condition <- sum(fac_levels_numeric) == 0
if (effect_condition || dummy_condition){
#if factors are effect or dummy coded, levels count from postive to negative values
level_values_sorted <- sort(fac_levels_numeric, decreasing = T)
level <- factor(level_values_sorted, levels = level_values_sorted, labels = level_values_sorted)
} else {
#if not labeled keep the same labeling with numbers
level <- factor(fac_levels, levels = fac_levels, labels = fac_levels)
}
}
level_label <- levels(level)
var_name <- attr(factors,'var_names')
options(warn = defaultWarn)
### 1.1.2
level <- assign_contrast_factor(level, var_name, contrast)
###
#eval(parse(text = paste(var_name,'<- factor(c(1:',level,'))', sep = '')))
eval(parse(text = paste(var_name,'<- level', sep = '')))
# with column names, and include an intercept
eval(parse(text = paste('effect_matrix <- model.matrix(~',var_name,', data = ', var_name,')', sep='')))
attr(effect_matrix, 'levels') <- levels(factors)
}else{
effect_matrix = NA
}
options(contrasts = tmp_contrasts)
return(effect_matrix)
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/effect.matrix.factor.R |
effect.matrix.interaction <-
function (interaction_factors = list(),
assign = array(dim = 0),
main_eff_index = array(dim = 0),
index_inter_factor = NA,
numeric_index = array(dim = 0),
contrast = NULL){
# generate the effect matrix for each interaction, numerical covariates excluded, TODO: may have various levels for numeric variables
# Args:
# interaction_factors : a list of values of factors in the interaction to generate the effect matrix
# assign : Not used for the new method, to remove
# index_factor : Not used, to remove
# numeric_index : Not used, to remove
# Returns:
# an effect matrix
#
# old method, hard coded
if(0){
# two way interactions
if (length(interaction_factors) == 2){
factor1 <- interaction_factors[[1]]
factor2 <- interaction_factors[[2]]
n1 <- length(factor1)
n2 <- length(factor2)
temp1 <- array(NA,dim = c(n1*n2,1))
temp2 <- array(NA,dim = c(n1*n2,1))
for (i in 1:n1)
for (j in 1: n2){
temp1[(i-1)*n2 + j] <- factor1[i]
temp2[(i-1)*n2 + j] <- factor2[j]
}
tempdata <- data.frame(cbind(temp1,temp2)) # everything converted to 1,2,3...
tempdata[,1] <- as.factor(tempdata[,1])
tempdata[,2] <- as.factor(tempdata[,2])
tempmatrix <- model.matrix(~ temp1 * temp2, data = tempdata)
tempIntermatrix <- tempmatrix[,-(1:(n1-1+n2-1+1))] # intercept:first column is excluded
tempMainmatrix <- tempmatrix[,2:(n1-1+n2-1+1)]
index <- which(assign == index_inter_factor)
effect_matrix <- matrix(0, nrow = n1*n2, ncol = length(assign))
effect_matrix[,index] <- tempIntermatrix
effect_matrix[,1] <- 1 # grand mean included
#if (length(numeric_index) > 0) effect_matrix[, numeric_index] <- 1 # consider the covariates effect
#include main effects
effect_matrix[, c(which(assign == main_eff_index[1]), which(assign == main_eff_index[2]))] <- tempMainmatrix
attr(effect_matrix, 'levels') <- cbind(temp1,temp2)
}else{
# multi way interactions
effect_matrix <- NA
}
return(effect_matrix)
}
# new method including higher number (>= 2) of interactions
tmp_contrasts <- getOption("contrasts")
options(contrasts = rep("contr.sum",2))
if (length(interaction_factors) >= 2){
num_inter = length(interaction_factors)
levels_inter = list()
names_inter = list()
for (i in 1:num_inter){
names_inter[[i]] = attr(interaction_factors[[i]], 'var_names')
levels_inter[[attr(interaction_factors[[i]], 'var_names')]] = levels(interaction_factors[[i]])
}
factors_inter = expand.grid(levels_inter)
factors_inter_factor = as.data.frame(lapply(factors_inter, as.factor))
#### 1.1.2
factors_inter_factor <- assign_contrast(factors_inter_factor, contrast)
####
formula_inter = paste(names_inter, collapse = '*')
eval(parse(text = paste('effect_matrix <- model.matrix(~',formula_inter,', data = factors_inter_factor)', sep='')))
attr(effect_matrix, 'levels') = as.matrix(factors_inter)
}else{
effect_matrix = NA
}
options(contrasts = tmp_contrasts)
return(effect_matrix)
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/effect.matrix.interaction.R |
# find design matrix of coefficients of a mediator (including interactions which contains the mediator, using summation)
# the mediator must be included in each interaction
effect.matrix.mediator <- function (interaction_factors=list(),
mediator=NA,
matrix_formula=NULL,
xvar=NA,
xvar_include = FALSE,
intercept_include = FALSE,
flood_values = list(),
contrast = NULL){
# generate the effect matrix for each interaction, numerical covariates excluded, TODO: may have various levels for numeric variables
# Args:
# interaction_factors : a list of values of factors in the interaction to generate the effect matrix
# assign : Not used for the new method, to remove
# index_factor : Not used, to remove
# numeric_index : Not used, to remove
# Returns:
# an effect matrix
#
tmp_contrasts <- getOption("contrasts")
options(contrasts = rep("contr.sum",2))
if (length(interaction_factors) > 0){
num_inter = length(interaction_factors)
levels_inter = list()
names_inter = list()
for (i in 1:num_inter){
names_inter[[i]] = attr(interaction_factors[[i]], 'var_names')
if (is.factor(interaction_factors[[i]])){
levels_inter[[names_inter[[i]]]] = levels(interaction_factors[[i]])
}else{
# for numeric or integer var, use 1 instead, e.g. the mediator
if(names_inter[[i]] %in% c(mediator, xvar)){
levels_inter[[names_inter[[i]]]] = 1
}else{
if (names_inter[[i]] %in% names(flood_values)){
if (length(names(flood_values)) != length(unique(names(flood_values)))) stop('Please provide unique flood light values!', call. = FALSE)
if (length(flood_values[[names_inter[[i]]]]) > 1) stop('Please provide one value at a time for the other numeric variables!', call. = FALSE)
levels_inter[[names_inter[[i]]]] = flood_values[[names_inter[[i]]]]
}else{
levels_inter[[names_inter[[i]]]] = 0 #mean(interaction_factors[[i]])
}
}
}
}
factors_inter = expand.grid(levels_inter)
level_factor <- factors_inter
# remove the response variable
if (!is.null(matrix_formula)){
the_term <- terms(matrix_formula)
if (attr(the_term, 'response') > 0){
all_names <- as.character(attr(the_term, "variables"))[-1]
response_name <- all_names[attr(the_term, 'response')]
level_factor[response_name] <- NULL
}
}
temp_fun <- function(x){
if (length(unique(x)) > 1)
as.factor(x)
else
as.numeric(as.character(x))
}
factors_inter_factor = as.data.frame(lapply(factors_inter, temp_fun))
#### 1.1.2
factors_inter_factor <- assign_contrast(factors_inter_factor, contrast)
####
formula_inter = paste(names_inter, collapse = '*')
if (is.null(matrix_formula))
eval(parse(text = paste('model_frame <- model.frame(~',formula_inter,', data = factors_inter_factor)', sep='')))
else
model_frame <- model.frame(matrix_formula, data = factors_inter_factor)
#eval(parse(text = paste('model_frame <- model.frame(',matrix_formula,', data = factors_inter_factor)', sep='')))
effect_matrix <- model.matrix(formula(attr(model_frame, 'terms')), data = factors_inter_factor)
#attr(effect_matrix, 'levels') = as.matrix(factors_inter)
attr(effect_matrix, 'levels') = as.matrix(level_factor)
if (!is.na(mediator)){
# only calculate the summation of coefficients that related to the mediator exclude xvar
if (!is.na(xvar) & (xvar %in% rownames(attr(attr(model_frame, 'terms'), 'factors')))){
tmp_mtx <- attr(attr(model_frame, 'terms'), 'factors')
tmp_ind_m <- which(rownames(tmp_mtx) == mediator)
tmp_ind_x <- which(rownames(tmp_mtx) == xvar)
if (!xvar_include)
assign_selected <- which(tmp_mtx[tmp_ind_m, ] == 1 & tmp_mtx[tmp_ind_x, ] == 0)
else
assign_selected <- which(tmp_mtx[tmp_ind_m, ] == 1 & tmp_mtx[tmp_ind_x, ] == 1)
#assign_selected <- which(attr(attr(model_frame, 'terms'), 'factors')[mediator, ] == 1 & attr(attr(model_frame, 'terms'), 'factors')[xvar, ] == 0)
}else{
tmp_mtx <- attr(attr(model_frame, 'terms'), 'factors')
tmp_ind <- which(rownames(tmp_mtx) == mediator)
assign_selected <- which(tmp_mtx[tmp_ind, ] == 1)
#assign_selected <- which(attr(attr(model_frame, 'terms'), 'factors')[mediator, ] == 1)
}
column_selected <- which(attr(effect_matrix, 'assign') %in% assign_selected)
if (intercept_include) column_selected <- c(1,column_selected)
effect_matrix_selected <- effect_matrix[ , column_selected, drop=FALSE]
attr(effect_matrix_selected, 'levels') = as.matrix(level_factor)
}else{
if (!is.na(xvar) & (xvar %in% rownames(attr(attr(model_frame, 'terms'), 'factors')))){
# exclude xvar
tmp_mtx <- attr(attr(model_frame, 'terms'), 'factors')
tmp_ind_x <- which(rownames(tmp_mtx) == xvar)
assign_selected <- which(tmp_mtx[tmp_ind_x, ] == 0)
column_selected <- which(attr(effect_matrix, 'assign') %in% assign_selected)
if (length(column_selected) == 0){
# intercept only
effect_matrix_selected <- array(1, dim = c(1, 1), dimnames = list(NULL, '(Intercept)'))
attr(effect_matrix_selected, 'levels') = as.matrix(array(1, dim = c(1, 1), dimnames = list(NULL, '(Intercept)')))
}else{
if (intercept_include) column_selected <- c(1,column_selected)
effect_matrix_selected <- effect_matrix[ , column_selected, drop=FALSE]
attr(effect_matrix_selected, 'levels') = as.matrix(level_factor)
}
}else{
effect_matrix_selected <- effect_matrix
attr(effect_matrix_selected, 'levels') = as.matrix(level_factor)
}
}
}else{
effect_matrix_selected = NA
}
options(contrasts = tmp_contrasts)
return(effect_matrix_selected)
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/effect.matrix.mediator.R |
est <-
function (f, est_matrix, n_sample, l1_matrix, l2_matrix, cutp0, cutp1){
if (nrow(l1_matrix) == 1 & nrow(l2_matrix) == 1){
est_samples_cutp0 <- array(0, dim = c(nrow(l2_matrix), n_sample))
est_samples_cutp1 <- array(0, dim = c(nrow(l2_matrix), n_sample))
est_samples <- array(0, dim = c(nrow(l2_matrix), n_sample))
if (sum(cutp0 != cutp1) == 0){
for (n_s in 1:n_sample){
temp <- l1_matrix %*% est_matrix[, , n_s] %*% t(l2_matrix)
est_samples[, n_s] <- 1 - f(temp)
}
}else if(sum(cutp1 != 0) == 0){
for (n_s in 1:n_sample){
temp <- l1_matrix %*% est_matrix[, , n_s] %*% t(l2_matrix) - cutp0[n_s]
est_samples[, n_s] <- f(temp)
}
}else{
for (n_s in 1:n_sample){
temp <- l1_matrix %*% est_matrix[, , n_s] %*% t(l2_matrix)
est_samples_cutp0[, n_s] <- temp - cutp0[n_s]
est_samples_cutp1[, n_s] <- temp - cutp1[n_s]
est_samples[, n_s] <- f(est_samples_cutp0[, n_s]) - f(est_samples_cutp1[, n_s])
}
}
}else if (nrow(l1_matrix) == 1 & nrow(l2_matrix) > 1){
est_samples_cutp0 <- array(0, dim = c(nrow(l2_matrix), n_sample))
est_samples_cutp1 <- array(0, dim = c(nrow(l2_matrix), n_sample))
est_samples <- array(0, dim = c(nrow(l2_matrix), n_sample))
if (sum(cutp0 != cutp1) == 0){
for (n_s in 1:n_sample){
temp <- l1_matrix %*% est_matrix[, colnames(l2_matrix), n_s] %*% t(l2_matrix)
est_samples[, n_s] <- 1 - f(temp)
}
}else if(sum(cutp1 != 0) == 0){
for (n_s in 1:n_sample){
temp <- l1_matrix %*% est_matrix[, colnames(l2_matrix), n_s] %*% t(l2_matrix) - cutp0[n_s]
est_samples[, n_s] <- f(temp)
}
}else{
for (n_s in 1:n_sample){
temp <- l1_matrix %*% est_matrix[, colnames(l2_matrix), n_s] %*% t(l2_matrix)
est_samples_cutp0[, n_s] <- temp - cutp0[n_s]
est_samples_cutp1[, n_s] <- temp - cutp1[n_s]
est_samples[, n_s] <- f(est_samples_cutp0[, n_s]) - f(est_samples_cutp1[, n_s])
}
}
}else if (nrow(l2_matrix) == 1 & nrow(l1_matrix) > 1){
est_samples_cutp0 <- array(0, dim = c(nrow(l1_matrix), n_sample))
est_samples_cutp1 <- array(0, dim = c(nrow(l1_matrix), n_sample))
est_samples <- array(0, dim = c(nrow(l1_matrix), n_sample))
if (sum(cutp0 != cutp1) == 0){
for (n_s in 1:n_sample){
temp <- l1_matrix %*% est_matrix[colnames(l1_matrix), , n_s] %*% t(l2_matrix)
est_samples[, n_s] <- 1 - f(temp)
}
}else if(sum(cutp1 != 0) == 0){
for (n_s in 1:n_sample){
temp <- l1_matrix %*% est_matrix[colnames(l1_matrix), , n_s] %*% t(l2_matrix) - cutp0[n_s]
est_samples[, n_s] <- f(temp)
}
}else{
for (n_s in 1:n_sample){
temp <- l1_matrix %*% est_matrix[colnames(l1_matrix), , n_s] %*% t(l2_matrix)
est_samples_cutp0[, n_s] <- temp - cutp0[n_s]
est_samples_cutp1[, n_s] <- temp - cutp1[n_s]
est_samples[, n_s] <- f(est_samples_cutp0[, n_s]) - f(est_samples_cutp1[, n_s])
}
}
}else{
est_samples_cutp0 <- array(0, dim = c(nrow(l1_matrix), nrow(l2_matrix), n_sample))
est_samples_cutp1 <- array(0, dim = c(nrow(l1_matrix), nrow(l2_matrix), n_sample))
est_samples <- array(0, dim = c(nrow(l1_matrix), nrow(l2_matrix), n_sample))
if (sum(cutp0 != cutp1) == 0){
for (n_s in 1:n_sample){
temp <- l1_matrix %*% est_matrix[colnames(l1_matrix), colnames(l2_matrix), n_s] %*% t(l2_matrix)
est_samples[,, n_s] <- 1 - f(temp)
}
}else if(sum(cutp1 != 0) == 0){
for (n_s in 1:n_sample){
temp <- l1_matrix %*% est_matrix[colnames(l1_matrix), colnames(l2_matrix), n_s] %*% t(l2_matrix) - cutp0[n_s]
est_samples[,, n_s] <- f(temp)
}
}else{
for (n_s in 1:n_sample){
temp <- l1_matrix %*% est_matrix[colnames(l1_matrix), colnames(l2_matrix),n_s] %*% t(l2_matrix)
est_samples_cutp0[,, n_s] <- temp - cutp0[n_s]
est_samples_cutp1[,, n_s] <- temp - cutp1[n_s]
est_samples[,, n_s] <- f(est_samples_cutp0[,, n_s]) - f(est_samples_cutp1[,, n_s])
}
}
}
return(est_samples)
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/est.R |
est.multi <-
function (est_matrix, n_sample, l1_matrix, l2_matrix){
n_choice <- length(l1_matrix)
exp_choice_linear <- list()
choice_prob <- list()
row_names <- dimnames(est_matrix)[[1]]
for (n_c in 1: n_choice){
if (nrow(l1_matrix[[n_c]]) == 1 & nrow(l2_matrix) == 1){
est_samples <- array(0, dim = c(nrow(l2_matrix), n_sample))
for (n_s in 1:n_sample){
temp <- l1_matrix[[n_c]] %*% est_matrix[,,n_s] %*% t(l2_matrix)
est_samples[, n_s] <- temp
}
exp_choice_linear[[n_c]] <- exp(est_samples)
}else if (nrow(l1_matrix[[n_c]]) > 1 & nrow(l2_matrix) == 1){
est_samples <- array(0, dim = c(nrow(l1_matrix[[n_c]]), n_sample))
common_name <- intersect(colnames(l1_matrix[[n_c]]), row_names)
l1_temp <- as.matrix(as.data.frame(l1_matrix[[n_c]])[common_name])
for (n_s in 1:n_sample){
# choice 1 intercept not in est_matrix
temp <- l1_temp %*% est_matrix[common_name, , n_s] %*% t(l2_matrix)
est_samples[, n_s] <- temp
}
exp_choice_linear[[n_c]] <- exp(est_samples)
}else if (nrow(l1_matrix[[n_c]]) == 1 & nrow(l2_matrix) > 1){
est_samples <- array(0, dim = c(nrow(l2_matrix), n_sample))
for (n_s in 1:n_sample){
temp <- l1_matrix[[n_c]] %*% est_matrix[, colnames(l2_matrix), n_s] %*% t(l2_matrix)
est_samples[, n_s] <- temp
}
exp_choice_linear[[n_c]] <- exp(est_samples)
}else{
est_samples <- array(0, dim = c(nrow(l1_matrix[[n_c]]), nrow(l2_matrix), n_sample))
for (n_s in 1:n_sample){
common_name <- intersect(colnames(l1_matrix[[n_c]]), row_names)
l1_temp <- as.matrix(as.data.frame(l1_matrix[[n_c]])[common_name])
temp <- l1_temp %*% est_matrix[common_name, colnames(l2_matrix), n_s] %*% t(l2_matrix)
est_samples[,, n_s] <- temp
}
exp_choice_linear[[n_c]] <- exp(est_samples)
}
}
choice_prob_sum <- array(0 , dim = dim(exp_choice_linear[[1]]))
for (n_c in 1:n_choice){
choice_prob_sum <- choice_prob_sum + exp_choice_linear[[n_c]]
}
for (n_c in 1:n_choice){
# print(exp_choice_linear[[n_c]])
# print('sum:')
# print(choice_prob_sum)
# print('divid:')
# print(exp_choice_linear[[n_c]]/choice_prob_sum)
choice_prob[[n_c]] <- exp_choice_linear[[n_c]]/choice_prob_sum
}
return(choice_prob)
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/est.multi.R |
est_pred <-
function(f, est_matrix, l1_matrix, l2_matrix, cutp0, cutp1){
temp <- l1_matrix %*% est_matrix %*% t(l2_matrix)
if (sum(cutp0 != cutp1) == 0){
est <- 1 - f(temp)
}else if(sum(cutp1 != 0) == 0){
temp <- temp - cutp0
est <- f(temp)
}else{
est_cutp0 <- temp - cutp0
est_cutp1 <- temp - cutp1
est <- f(est_cutp0) - f(est_cutp1)
}
return(est)
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/est_pred.R |
###
# This version, the floodlight analysis hasn't been tested for two cases: (level1_num && level1_fac) (level2_num && level1_fac)
###
# find the effects of the factor only (not including the numeric variable), using cal.mediation.effects
# find the effects of the interaction between the numeric variable and the factor, using cal.effects (specific to the numeric var), and possible modifications of effect.matrix.mediator
#
floodlight.analysis <-
function (sol,
numeric_name,
factor_name,
samples_l2_param, X, Z, data = NULL, dataX = NULL, dataZ = NULL, flood_values = list()){
numeric_name <- trimws(numeric_name)
factor_name <- trimws(factor_name)
X_names = colnames(X) # names after effect coding
X_varNames = attr(X, "varNames") # names before coding
Z_names = colnames(Z) # names after effect coding
Z_varNames = attr(Z, 'varNames') # names before coding
X_assign = attr(X, "assign")
X_classes = attr(X, "dataClasses")
Z_assign = attr(Z, "assign")
Z_classes = attr(Z, "dataClasses")
# convert samples_l2_param to est_matrix (row: X_names, column: Z_names)
n_sample <- nrow(samples_l2_param)
num_l1 <- length(X_assign)
num_l2 <- length(Z_assign)
est_matrix <- array(0 , dim = c(num_l1, num_l2, n_sample), dimnames = list(trimws(X_names), trimws(Z_names), NULL))
for (i in 1:num_l1){
for (j in 1:n_sample)
est_matrix[i,,j] <- samples_l2_param[j,((i-1)*num_l2+1):((i-1)*num_l2+num_l2)]
}
# find the levels (level 1 or 2) for the numeric and categorical variables
level1_num = numeric_name %in% X_varNames
level2_num = numeric_name %in% Z_varNames
level1_fac = factor_name %in% X_varNames
level2_fac = factor_name %in% Z_varNames
if (level1_num && level2_num) stop("The numerical variable can't appear in both levels." )
if (level1_fac && level2_fac) stop("The categorical variable can't appear in both levels." )
if (!level1_num && !level2_num) stop("The numerical variable isn't included in the model." )
if (!level1_fac && !level2_fac) stop("The categorical variable isn't included in the model." )
## find the range of numeric values
if (!is.null(data)){
num_value <- data[,which(colnames(data) == numeric_name)]
}else{
if(level1_num){
index_num_X <- which(colnames(dataX[[1]]) == numeric_name)
num_value <- c()
for (i in 1:length(dataX)){
num_value <- c(num_value, dataX[[i]][, index_num_X])
}
}else{
index_num_Z <- which(colnames(dataZ) == numeric_name)
num_value <- dataZ[, index_num_Z]
}
}
num_range <- range(num_value)
if (level1_num && level1_fac){
if (!((X_classes[numeric_name] == "numeric" || X_classes[numeric_name] == "integer") && X_classes[factor_name] == "factor"))
stop('Variable types are not correct.')
# generate var names from the factor variable (e.g. name1, name2, ..)
## look for the name (index) in the X_varNames
## look for the index in X_assign
## find the corresponding names in X_names
X_names_factor <- X_names[X_assign == (which(X_varNames == factor_name) - 1)] # since assign starts from 0
# generate var names from the interaction between the numeric varibale and the factor (e.g. num_name : factor1, num_name : factor2,..)
## use the attr(,"interactions") to find the corresponding (match the name of the two variables) index
X_interactions <- attr(X, "interactions_num")
X_interactions_index <- attr(X, "interactions_numeric_index")
inter_found_flag = F
factor_name_map_inter_name <- list()
if (length(X_interactions) > 0){
for (i in 1:length(X_interactions)){
tmp_names <- attr(X_interactions[[i]], 'names')
if (length(tmp_names) == 2 && (numeric_name %in% tmp_names) && (factor_name %in% tmp_names)){
inter_index <- X_interactions_index[i]
assign_index <- which(attr(X, "assign") == inter_index)
inter_names <- X_names[assign_index]
split_inter_names <- strsplit(inter_names, ':')
for (j in 1:length(split_inter_names)){
split_inter_names[[j]] <- trimws(split_inter_names[[j]])
# create a map, factor name : interaction name
for (name_fac_inter in split_inter_names[[j]]){
if (name_fac_inter %in% X_names_factor)
factor_name_map_inter_name[[name_fac_inter]] <- inter_names[j]
}
}
inter_found_flag <- T
}
}
}
if (!inter_found_flag){
stop('No specified interaction found in the model!')
}
flood_eff <- cal.flood.effects(sol, est_matrix, n_sample, factor_name, numeric_name, flood_values = flood_values)
# for each level of the factor (names found before)
## find these factors which is corresponding to the column of est_matrix
## for the first row (the intercept) of est_matrix, calculate the floodlight
floodlight_samples <- data.frame(array(0, dim = c(n_sample, length(X_names_factor)), dimnames = list(NULL, X_names_factor)))
for (name_fac in X_names_factor)
for (n_s in 1:n_sample){
floodlight_samples[[name_fac]][n_s] = - est_matrix[name_fac, 1, n_s]/est_matrix[factor_name_map_inter_name[[name_fac]], 1, n_s]
}
res <- array(0, dim = c(length(X_names_factor), 3), dimnames = list(X_names_factor, c('mean', '2.5%', '97.5%')))
for (name_fac in X_names_factor){
res[name_fac, 1] <- mean(floodlight_samples[[name_fac]])
res[name_fac, 2:3] <- quantile(floodlight_samples[[name_fac]], c(0.025, 0.975))
}
rownames(res) <- paste(numeric_name, rownames(res), sep = ":")
}
if (level2_num && level1_fac){
if (!((Z_classes[numeric_name] == "numeric" || Z_classes[numeric_name] == "integer") && X_classes[factor_name] == "factor"))
stop('Variable types are not correct.')
# generate var names from the factor variable (e.g. name1, name2, ..)
## look for the name (index) in X_varNames, Z_varNames
## look for the index in X_assign, Z_assign
## find the corresponding names in X_names, Z_names
Z_names_num <- Z_names[Z_assign == (which(Z_varNames == numeric_name) - 1)] # since assign starts from 0
X_names_factor <- X_names[X_assign == (which(X_varNames == factor_name) - 1)] # since assign starts from 0
# for each level of the factor (names found before)
## find these factors which is corresponding to the column of est_matrix
## for the first row (the intercept) of est_matrix, calculate the floodlight
floodlight_samples <- data.frame(array(0, dim = c(n_sample, length(X_names_factor)), dimnames = list(NULL, X_names_factor)))
#factor_eff_samples <- data.frame(array(0, dim = c(n_sample, length(X_names_factor)), dimnames = list(NULL, X_names_factor)))
#numeric_eff_sample <- data.frame(array(0, dim = c(n_sample, length(Z_names_num)), dimnames = list(NULL, Z_names_num)))
for (name_fac in X_names_factor){
for (n_s in 1:n_sample){
floodlight_samples[[name_fac]][n_s] = - est_matrix[name_fac, 1, n_s]/est_matrix[name_fac, Z_names_num, n_s]
}
}
flood_eff <- cal.flood.effects(sol, est_matrix, n_sample, factor_name, numeric_name, flood_values = flood_values)
res <- array(0, dim = c(length(X_names_factor), 3), dimnames = list(X_names_factor, c('mean', '2.5%', '97.5%')))
for (name_fac in X_names_factor){
res[name_fac, 1] <- mean(floodlight_samples[[name_fac]])
res[name_fac, 2:3] <- quantile(floodlight_samples[[name_fac]], c(0.025, 0.975))
}
rownames(res) <- paste(numeric_name, rownames(res), sep = ":")
}
if (level1_num && level2_fac){
warning('This type of analysis is under development for a more general case. It might not be stable now.', call. = FALSE)
if (!((X_classes[numeric_name] == "numeric" || X_classes[numeric_name] == "integer") && Z_classes[factor_name] == "factor"))
stop('Variable types are not correct.')
# generate var names from the factor variable (e.g. name1, name2, ..)
## look for the name (index) in X_varNames, Z_varNames
## look for the index in X_assign, Z_assign
## find the corresponding names in X_names, Z_names
X_names_num <- X_names[X_assign == (which(X_varNames == numeric_name) - 1)] # since assign starts from 0
Z_names_factor <- Z_names[Z_assign == (which(Z_varNames == factor_name) - 1)] # since assign starts from 0
# for each level of the factor (names found before)
## find these factors which is corresponding to the column of est_matrix
## for the first row (the intercept) of est_matrix, calculate the floodlight
floodlight_samples <- data.frame(array(0, dim = c(n_sample, length(Z_names_factor)), dimnames = list(NULL, Z_names_factor)))
for (name_fac in Z_names_factor)
for (n_s in 1:n_sample){
floodlight_samples[[name_fac]][n_s] = - est_matrix[1, name_fac, n_s]/est_matrix[X_names_num, name_fac, n_s]
}
flood_eff <- cal.flood.effects(sol, est_matrix, n_sample, factor_name, numeric_name, flood_values = flood_values)
res <- array(0, dim = c(length(Z_names_factor), 3), dimnames = list(Z_names_factor, c('mean', '2.5%', '97.5%')))
for (name_fac in Z_names_factor){
res[name_fac, 1] <- mean(floodlight_samples[[name_fac]])
res[name_fac, 2:3] <- quantile(floodlight_samples[[name_fac]], c(0.025, 0.975))
}
rownames(res) <- paste(numeric_name, rownames(res), sep = ":")
}
if (level2_num && level2_fac){
warning('This type of analysis is under development for a more general case. It might not be stable now.', call. = FALSE)
if (!((Z_classes[numeric_name] == "numeric" || Z_classes[numeric_name] == "integer") && Z_classes[factor_name] == "factor"))
stop('Variable types are not correct.')
# generate var names from the factor variable (e.g. name1, name2, ..)
## look for the name (index) in the Z_varNames
## look for the index in Z_assign
## find the corresponding names in Z_names
Z_names_factor <- Z_names[Z_assign == (which(Z_varNames == factor_name) - 1)] # since assign starts from 0
# generate var names from the interaction between the numeric varibale and the factor (e.g. num_name : factor1, num_name : factor2,..)
## use the attr(,"interactions") to find the corresponding (match the name of the two variables) index
Z_interactions <- attr(Z, "interactions_num")
Z_interactions_index <- attr(Z, "interactions_numeric_index")
inter_found_flag = F
factor_name_map_inter_name <- list()
if (length(Z_interactions) > 0){
for (i in 1:length(Z_interactions)){
tmp_names <- attr(Z_interactions[[i]], 'names')
if (length(tmp_names) == 2 && (numeric_name %in% tmp_names) && (factor_name %in% tmp_names)){
inter_index <- Z_interactions_index[i]
assign_index <- which(attr(Z, "assign") == inter_index)
inter_names <- Z_names[assign_index]
split_inter_names <- strsplit(inter_names, ':')
for (j in 1:length(split_inter_names)){
split_inter_names[[j]] <- trimws(split_inter_names[[j]])
# create a map, factor name : interaction name
for (name_fac_inter in split_inter_names[[j]]){
if (name_fac_inter %in% Z_names_factor)
factor_name_map_inter_name[[name_fac_inter]] <- inter_names[j]
}
}
inter_found_flag <- T
}
}
}
if (!inter_found_flag){
stop('No specified interaction found in the model!')
}
flood_eff <- cal.flood.effects(sol, est_matrix, n_sample, factor_name, numeric_name, flood_values = flood_values)
# for each level of the factor (names found before)
## find these factors which is corresponding to the column of est_matrix
## for the first row (the intercept) of est_matrix, calculate the floodlight
floodlight_samples <- data.frame(array(0, dim = c(n_sample, length(Z_names_factor)), dimnames = list(NULL, Z_names_factor)))
for (name_fac in Z_names_factor)
for (n_s in 1:n_sample){
floodlight_samples[[name_fac]][n_s] = - est_matrix[1, name_fac, n_s]/est_matrix[1, factor_name_map_inter_name[[name_fac]], n_s]
}
res <- array(0, dim = c(length(Z_names_factor), 3), dimnames = list(Z_names_factor, c('mean', '2.5%', '97.5%')))
for (name_fac in Z_names_factor){
res[name_fac, 1] <- mean(floodlight_samples[[name_fac]])
res[name_fac, 2:3] <- quantile(floodlight_samples[[name_fac]], c(0.025, 0.975))
}
rownames(res) <- paste(numeric_name, rownames(res), sep = ":")
}
return(list(sol = flood_eff, num_range = num_range))
} | /scratch/gouwar.j/cran-all/cranData/BANOVA/R/floodlight.analysis.R |
get.interactions <-
function(mf, ncol_intercepts = 0){
factor_matrix <- attr(attr(mf,'terms'),'factors')
factor_order <- attr(attr(mf,'terms'),'order')
col_index_inter <- which(factor_order >= 2)
col_chosen_inter <- array(dim = 0) # store interactions without numeric variables
col_chosen_inter_numeric <- array(dim = 0) # store interactions with numeric variables, used for mean centering
results <- list()
results_num <- list()
if (length(col_index_inter) > 0){
for (i in 1:length(col_index_inter)){
index_inter <- which(factor_matrix[,col_index_inter[i]] == 1) # order matters
# exclude/include the case that the interaction include a numeric variable
if (sum(attr(attr(mf,'terms'),'dataClasses')[index_inter] != 'factor') == 0){
results[[length(results) + 1]] <- index_inter + ncol_intercepts
col_chosen_inter <- c(col_chosen_inter, col_index_inter[i] + ncol_intercepts)
}else{
results_num[[length(results_num) + 1]] <- index_inter + ncol_intercepts
col_chosen_inter_numeric <- c(col_chosen_inter_numeric, col_index_inter[i] + ncol_intercepts)
}
}
}
sol <- list()
sol$results <- results
sol$results_num <- results_num
sol$index <- col_chosen_inter
sol$numeric_index <- col_chosen_inter_numeric
return(sol)
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/get.interactions.R |
get.values <-
function(data, mf, id_index = array(dim = 0), intercept_names = character(0)){
#
# Args:
# data : original data frame
# mf : model frame
# id_index : corresponding row index for Z matrix values
# Return:
# a list of values included in mf (y values, continuous variable before mean centering-shouldn't be used)
# the order of var_names in results matters
var_names <- c(intercept_names, attr(mf,'names'))
results <- list()
if (length(var_names) > 0){
for (i in 1: length(var_names)){
if (length(id_index) == 0){
eval(parse(text = paste('results[[',i,']] <- data$',var_names[i],sep='')))
}else{
eval(parse(text = paste('results[[',i,']] <- data$',var_names[i], '[id_index]', sep='')))
}
eval(parse(text = paste("attr(results[[",i,"]], 'var_names') <- '", var_names[i],"'",sep="")))
}
}
return(results)
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/get.values.R |
mean.center <-
function(m){
if (!('matrix' %in% class(m)))
m <- as.matrix(m)
for (i in 1:ncol(m))
m[,i] <- m[,i] - mean(m[,i])
return(m)
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/mean.center.R |
multi.design.matrix <-
function(l1_formula = 'NA', l2_formula = 'NA', dataX, dataZ = NULL, id, contrast = NULL){
tmp_contrasts <- getOption("contrasts")
#check formats
if (l1_formula == 'NA')
stop("Formula in level 1 is missing! In the case of no level 1 factor, please use 'y~1'")
if (l2_formula == 'NA'){
if (!inherits(dataX, 'list')) stop('Xsamples must be a list of features data.')
temp1 <- nrow(dataX[[1]])
temp2 <- ncol(dataX[[1]])
for (i in 1:length(dataX))
if (nrow(dataX[[i]]) != temp1 || ncol(dataX[[i]]) != temp2)
stop('dataX dimensions mismatch! Each element of the list should have the same dimension.')
n_ob <- length(dataX)
first_choice_set <- dataX[[1]] # used to make all attributes
# check if intercepts are included
mf1_temp <- model.frame(formula = l1_formula, data = first_choice_set)
intercept_bool <- attr(attr(mf1_temp,'terms'),'intercept')
if (!intercept_bool) stop('Intercept in level 1 must be included!')
n_choice <- nrow(first_choice_set)
if (n_choice < 2) stop('Data error, number of choices less than 2. Please change models.')
n_features <- ncol(first_choice_set)
col_names <- colnames(first_choice_set)
intercept_names <- ''
for (i in 2:n_choice)
intercept_names[i-1] <- paste('choice',i,'_Intercept', sep = "")
#col_names <- c(intercept_names,col_names)
dataClasses <- ''
for (i in 1:ncol(first_choice_set)){
dataClasses[i] <- class(first_choice_set[,i])
}
X_full <- list()
X_original_choice <- list()
# build a big matrix for each choice corresponds to all observations
for (i in 1:n_choice){
matrix_temp <- matrix(0, nrow = n_ob, ncol = n_features)
for (j in 1:n_ob){
temp <- as.matrix(dataX[[j]])
matrix_temp[j,] <- temp[i,]
}
colnames(matrix_temp) <- col_names
matrixtemp <- data.frame(matrix_temp)
for (j in 1:n_features){
if (dataClasses[j] == 'numeric'){
matrixtemp[,j] <- as.numeric(as.character(matrixtemp[,j])) # R somehow automatically convert everything to factors
}else if(dataClasses[j] == 'integer'){
matrixtemp[,j] <- as.integer(as.character(matrixtemp[,j]))
}else if(dataClasses[j] == 'factor'){
matrixtemp[,j] <- as.factor(as.character(matrixtemp[,j]))
}else
stop('Bad class object in dataX')
}
X_original_choice[[i]] <- matrixtemp
intercept_matrix_values <- matrix(0, nrow = nrow(matrixtemp), ncol = n_choice - 1)
if (i > 1)
intercept_matrix_values[, i-1] <- 1
colnames(intercept_matrix_values) <- intercept_names
X_new_values <- cbind(intercept_matrix_values, matrixtemp) # for extracting values of variables
# build full design matrix of X
options(contrasts = rep("contr.sum",2)) # use effect coding for both unordered and ordered factors
options(na.action='na.fail') # An error will occur if features data contains NA's.
#### 1.1.2
matrixtemp <- assign_contrast(matrixtemp, contrast)
####
mf1 <- model.frame(formula = l1_formula, data = matrixtemp)
#y <- model.response(mf1)
X <- model.matrix(attr(mf1,'terms'), data = mf1)
if (dim(X)[2] == 0) stop('No variables in level 1 model! Please add an intercept at least.')
original_assign <- attr(X,'assign')
if (attr(attr(mf1,'terms'),'intercept') != 0){
if (ncol(X) == 2){
tempname <- colnames(X)[2]
X <- matrix(X[, -1],ncol = 1) # exclude the intercept because of the identification problem, this removes the attribute assign, if 2 columns before, then it becomes 1 row!
colnames(X) <- tempname
}else
X <- X[, -1]
attr(X,'assign') <- original_assign[-1]
}
attr(X,'dataClasses') <- attr(attr(mf1,'terms'),'dataClasses')
numeric_index <- which(attr(X,'dataClasses') == 'numeric' | attr(X,'dataClasses') == 'integer')
tmp <- get.interactions(mf1)
numeric_index <- c(numeric_index, tmp$numeric_index) # add interactions including at least one numeric variable
numeric_index_in_X <- array(NA, dim = c(1,length(numeric_index)))
if (length(numeric_index) > 0){
for (j in 1:length(numeric_index)){
numeric_index_in_X[j] <- which(attr(X,'assign') == numeric_index[j])
}
X[,numeric_index_in_X] <- mean.center(X[,numeric_index_in_X]) # mean center numeric variables (covariates) in X
warning("level 1 numeric variables have been mean centered.\n", call. = F, immediate. = T)
}
# then col bind the intercept matrix
intercept_matrix <- matrix(0, nrow = n_ob, ncol = n_choice - 1)
if (i > 1)
intercept_matrix[, i-1] <- 1
colnames(intercept_matrix) <- intercept_names
X_new <- cbind(intercept_matrix, X)
attr(X_new,'numeric_index') <- c(1:(n_choice - 1), numeric_index_in_X + n_choice - 1)
attr(X_new,'assign') <- c(1:(n_choice - 1), attr(X,'assign') + n_choice - 1)
attr(X_new,'varNames') <- c(intercept_names, attr(attr(mf1,'terms'),'term.labels'))
#else
# stop('Intercept in level 1 must be included!')
temp <- matrix(c(rep('numeric', n_choice - 1), attr(attr(mf1,'terms'),'dataClasses')), nrow = 1)
colnames(temp) <- c(intercept_names, attr(attr(attr(mf1,'terms'),'dataClasses'),'names'))
attr(X_new,'dataClasses') <- matrix(c(rep('numeric', n_choice - 1), attr(attr(mf1,'terms'),'dataClasses')), nrow = 1)
attr(attr(X_new,'dataClasses'), 'names') <- c(intercept_names,attr(attr(attr(mf1,'terms'),'dataClasses'),'names'))
attr(X_new,'varValues') <- get.values(data.frame(X_new_values), mf1, intercept_names = intercept_names)
temp <- get.interactions(mf1, n_choice - 1)
attr(X_new,'interactions') <- temp$results
attr(X_new,'interactions_index') <- temp$index
attr(X_new,'interactions_num') <- temp$results_num
attr(X_new,'interactions_numeric_index') <- temp$numeric_index
X_full[[i]] <- X_new
}
# check dimensions of each matrix for each choice
n_full_feature <- ncol(X_full[[1]])
for (i in 2:n_choice)
if(ncol(X_full[[i]]) != n_full_feature) stop('Data is not balanced! for each choice alternative, the categorical features should have the same number of levels.')
Z = NULL
Z_full = NULL
}else{
if (!inherits(dataX, 'list')) stop('Xsamples must be a list of features data.')
if (length(dataX) != nrow(dataZ)) stop('X, Z samples dimension mismatch.')
temp1 <- nrow(dataX[[1]])
temp2 <- ncol(dataX[[1]])
for (i in 1:length(dataX))
if (nrow(dataX[[i]]) != temp1 || ncol(dataX[[i]]) != temp2)
stop('dataX dimensions mismatch! Each element of the list should have the same dimension.')
n_ob <- length(dataX)
first_choice_set <- dataX[[1]] # used to make all attributes
# check if intercepts are included
mf1_temp <- model.frame(formula = l1_formula, data = first_choice_set)
intercept_bool <- attr(attr(mf1_temp,'terms'),'intercept')
if (!intercept_bool) stop('Intercept in level 1 must be included!')
n_choice <- nrow(first_choice_set)
if (n_choice < 2) stop('Data error, number of choices less than 2. Please change models.')
n_features <- ncol(first_choice_set)
col_names <- colnames(first_choice_set)
intercept_names <- ''
for (i in 2:n_choice)
intercept_names[i-1] <- paste('choice',i,'_Intercept', sep = "")
#col_names <- c(intercept_names,col_names)
dataClasses <- ''
for (i in 1:ncol(first_choice_set)){
dataClasses[i] <- class(first_choice_set[,i])
}
X_full <- list()
X_original_choice <- list()
# build a big matrix for each choice corresponds to all observations
for (i in 1:n_choice){
matrix_temp <- matrix(0, nrow = n_ob, ncol = n_features)
for (j in 1:n_ob){
temp <- as.matrix(dataX[[j]])
matrix_temp[j,] <- temp[i,]
}
colnames(matrix_temp) <- col_names
matrixtemp <- data.frame(matrix_temp)
for (j in 1:n_features){
if (dataClasses[j] == 'numeric'){
matrixtemp[,j] <- as.numeric(as.character(matrixtemp[,j])) # R somehow automatically convert everything to factors
}else if(dataClasses[j] == 'integer'){
matrixtemp[,j] <- as.integer(as.character(matrixtemp[,j]))
}else if(dataClasses[j] == 'factor'){
matrixtemp[,j] <- as.factor(as.character(matrixtemp[,j]))
}else
stop('Bad class object in dataX')
}
X_original_choice[[i]] <- matrixtemp
intercept_matrix_values <- matrix(0, nrow = nrow(matrixtemp), ncol = n_choice - 1)
if (i > 1)
intercept_matrix_values[, i-1] <- 1
colnames(intercept_matrix_values) <- intercept_names
X_new_values <- cbind(intercept_matrix_values, matrixtemp) # for extracting values of variables
# build full design matrix of X and Z
options(contrasts = rep("contr.sum",2)) # use effect coding for both unordered and ordered factors
options(na.action='na.fail') # An error will occur if features data contains NA's.
#### 1.1.2
matrixtemp <- assign_contrast(matrixtemp, contrast)
####
mf1 <- model.frame(formula = l1_formula, data = matrixtemp)
#y <- model.response(mf1)
X <- model.matrix(attr(mf1,'terms'), data = mf1)
if (dim(X)[2] == 0) stop('No variables in level 1 model! Please add an intercept at least.')
original_assign <- attr(X,'assign')
if (attr(attr(mf1,'terms'),'intercept') != 0){
if (ncol(X) == 2){
tempname <- colnames(X)[2]
X <- matrix(X[, -1],ncol = 1) # exclude the intercept because of the identification problem, this removes the attribute assign, if 2 columns before, then it becomes 1 row!
colnames(X) <- tempname
}else
X <- X[, -1]
attr(X,'assign') <- original_assign[-1]
}
attr(X,'dataClasses') <- attr(attr(mf1,'terms'),'dataClasses')
numeric_index <- which(attr(X,'dataClasses') == 'numeric' | attr(X,'dataClasses') == 'integer')
tmp <- get.interactions(mf1)
numeric_index <- c(numeric_index, tmp$numeric_index) # add interactions including at least one numeric variable
numeric_index_in_X <- array(NA, dim = c(1,length(numeric_index)))
if (length(numeric_index) > 0){
for (j in 1:length(numeric_index)){
numeric_index_in_X[j] <- which(attr(X,'assign') == numeric_index[j])
}
X[,numeric_index_in_X] <- mean.center(X[,numeric_index_in_X]) # mean center numeric variables (covariates) in X
warning("level 1 numeric variables have been mean centered.\n", call. = F, immediate. = T)
}
# then col bind the intercept matrix
intercept_matrix <- matrix(0, nrow = n_ob, ncol = n_choice - 1)
if (i > 1)
intercept_matrix[, i-1] <- 1
colnames(intercept_matrix) <- intercept_names
X_new <- cbind(intercept_matrix, X)
attr(X_new,'numeric_index') <- c(1:(n_choice - 1), numeric_index_in_X + n_choice - 1)
attr(X_new,'assign') <- c(1:(n_choice - 1), attr(X,'assign') + n_choice - 1)
attr(X_new,'varNames') <- c(intercept_names, attr(attr(mf1,'terms'),'term.labels'))
#else
# stop('Intercept in level 1 must be included!')
temp <- matrix(c(rep('numeric', n_choice - 1), attr(attr(mf1,'terms'),'dataClasses')), nrow = 1)
colnames(temp) <- c(intercept_names, attr(attr(attr(mf1,'terms'),'dataClasses'),'names'))
attr(X_new,'dataClasses') <- matrix(c(rep('numeric', n_choice - 1), attr(attr(mf1,'terms'),'dataClasses')), nrow = 1)
attr(attr(X_new,'dataClasses'), 'names') <- c(intercept_names,attr(attr(attr(mf1,'terms'),'dataClasses'),'names'))
attr(X_new,'varValues') <- get.values(data.frame(X_new_values), mf1, intercept_names = intercept_names)
temp <- get.interactions(mf1, n_choice - 1)
attr(X_new,'interactions') <- temp$results
attr(X_new,'interactions_index') <- temp$index
attr(X_new,'interactions_num') <- temp$results_num
attr(X_new,'interactions_numeric_index') <- temp$numeric_index
X_full[[i]] <- X_new
}
# check dimensions of each matrix for each choice
n_full_feature <- ncol(X_full[[1]])
for (i in 2:n_choice)
if(ncol(X_full[[i]]) != n_full_feature) stop('Data is not balanced! for each choice alternative, the categorical features should have the same number of levels.')
#### 1.1.2
dataZ <- assign_contrast(dataZ, contrast)
####
mf2 <- model.frame(formula = l2_formula, data = dataZ)
Z_full <- model.matrix(attr(mf2,'terms'), data = mf2)
if (dim(Z_full)[2] == 0) stop('No variables in level 2 model! Please add an intercept at least.')
if (attr(attr(mf2,'terms'),'response') == 1) stop("level 2 model shouldn't include the response! Start with the '~'.")
#convert Z from long format to short format, using the first row of each id
num_id <- length(unique(id))
id_index <- array(NA,dim = c(num_id,1))
for (i in 1:num_id){
index_row <- which(id == i)
# check if it is a good between-subject factor
if (max(index_row) > nrow(Z_full)) stop('ID indicator error!')
for (j in 1:ncol(Z_full))
if (max(Z_full[index_row, j]) != min(Z_full[index_row, j])) stop('Bad between-subject factor!')
id_index[i] <- index_row[1]
}
Z <- as.matrix(Z_full[id_index,])
colnames(Z) <- colnames(Z_full)
if (attr(attr(mf2,'terms'),'intercept') != 0) # for tables in outputs
attr(Z,'varNames') <- c('(Intercept)',attr(attr(mf2,'terms'),'term.labels'))
else
stop('Intercept in level 2 must be included!')
attr(Z,'dataClasses') <- attr(attr(mf2,'terms'),'dataClasses')
attr(Z,'varValues') <- get.values(dataZ, mf2, id_index)
temp <- get.interactions(mf2)
attr(Z,'interactions') <- temp$results
attr(Z,'interactions_index') <- temp$index
attr(Z,'interactions_num') <- temp$results_num
attr(Z,'interactions_numeric_index') <- temp$numeric_index
attr(Z,"assign") <- attr(Z_full,"assign")
attr(Z,"contrasts") <- attr(Z_full,"contrasts")
# find index of numeric variables (covariates) in Z
numeric_index <- which(attr(Z,'dataClasses') == 'numeric' | attr(Z,'dataClasses') == 'integer')
numeric_index <- c(numeric_index, temp$numeric_index) # add interactions including at least one numeric variable
numeric_index_in_Z <- array(NA, dim = c(1,length(numeric_index)))
if (length(numeric_index) > 0){
numeric_index_in_Z <- array(NA, dim = c(1,length(numeric_index)))
for (i in 1:length(numeric_index)){
numeric_index_in_Z[i] <- which(attr(Z,'assign') == numeric_index[i])
}
Z[,numeric_index_in_Z] <- mean.center(Z[,numeric_index_in_Z])
warning("level 2 numeric variables have been mean centered.\n", call. = F, immediate. = T)
}
attr(Z,'numeric_index') <- numeric_index_in_Z
attr(Z_full,'numeric_index') <- numeric_index_in_Z
}
options(contrasts = tmp_contrasts)
return(list(X_full = X_full, X_original_choice = X_original_choice, Z = Z, Z_full = Z_full))
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/multi.design.matrix.R |
multi.effect.matrix.factor <-
function (n_choice, factors, assign = array(dim = 0), index_factor = NA, numeric_index = array(dim = 0), contrast = NULL){
# old version
# result <- list()
# for (n_c in 1:n_choice){
# if (length(assign) != 0){
# index <- which(assign == index_factor)
# level <- length(index) + 1
# effect_matrix <- matrix(0, nrow = level, ncol = length(assign))
# effect_matrix[,index] <- contr.sum(level)
# if (n_c != 1)
# effect_matrix[,n_c-1] <- 1 # grand mean included
# #if (length(numeric_index) > 0) effect_matrix[, numeric_index] <- 1 # consider the covariates effect
# attr(effect_matrix, 'levels') <- factors
# }
# result[[n_c]] <- effect_matrix
# }
# new version
tmp_contrasts <- getOption("contrasts")
options(contrasts = rep("contr.sum",2))
result <- list()
for (n_c in 1:n_choice){
if (length(assign) != 0){
level <- as.factor(levels(factors))
var_name <- attr(factors,'var_names')
### 1.1.2
level <- assign_contrast_factor(level, var_name, contrast)
###
eval(parse(text = paste(var_name,'<- level', sep = '')))
# with column names, and include an intercept
eval(parse(text = paste('effect_matrix <- model.matrix(~',var_name,', data = ', var_name,')', sep='')))
# Note hard coded here, be consistent with 'multi.design.matrix.R'
if (n_c > 1){
intercept_name = paste('choice', n_c,'_Intercept', sep = "")
temp <- colnames(effect_matrix)
temp[grep('Intercept', temp)] <- intercept_name
colnames(effect_matrix) <- temp
}else{
# remove choice 1 intercept, identification problem
#effect_matrix <- effect_matrix[-grep('Intercept', temp)]
}
attr(effect_matrix, 'levels') <- levels(factors)
}else{
effect_matrix <- NA
}
result[[n_c]] <- effect_matrix
}
options(contrasts = tmp_contrasts)
return(result)
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/multi.effect.matrix.factor.R |
multi.effect.matrix.interaction <-
function (n_choice, interaction_factors = list(), assign = array(dim = 0),
main_eff_index = array(dim = 0), index_inter_factor = NA,
numeric_index = array(dim = 0), contrast = NULL){
result <- list()
# old method, hard coded
if(0){
# two way interactions
if (length(interaction_factors) == 2){
factor1 <- interaction_factors[[1]]
factor2 <- interaction_factors[[2]]
n1 <- length(factor1)
n2 <- length(factor2)
temp1 <- array(NA,dim = c(n1*n2,1))
temp2 <- array(NA,dim = c(n1*n2,1))
for (i in 1:n1)
for (j in 1: n2){
temp1[(i-1)*n2 + j] <- factor1[i]
temp2[(i-1)*n2 + j] <- factor2[j]
}
tempdata <- data.frame(cbind(temp1,temp2)) # everything converted to 1,2,3...
tempdata[,1] <- as.factor(tempdata[,1])
tempdata[,2] <- as.factor(tempdata[,2])
tempmatrix <- model.matrix(~ temp1 * temp2, data = tempdata)
tempIntermatrix <- tempmatrix[,-(1:(n1-1+n2-1+1))] # intercept:first column is excluded
tempMainmatrix <- tempmatrix[,2:(n1-1+n2-1+1)]
index <- which(assign == index_inter_factor)
for (n_c in 1: n_choice){
effect_matrix <- matrix(0, nrow = n1*n2, ncol = length(assign))
effect_matrix[,index] <- tempIntermatrix
if (n_c != 1)
effect_matrix[,n_c - 1] <- 1 # grand mean included
#if (length(numeric_index) > 0) effect_matrix[, numeric_index] <- 1 # consider the covariates effect
#include main effects
effect_matrix[, c(which(assign == main_eff_index[1]), which(assign == main_eff_index[2]))] <- tempMainmatrix
attr(effect_matrix, 'levels') <- cbind(temp1,temp2)
result[[n_c]] <- effect_matrix
}
}else{
result <- NA
}
return(result)
}
# new method including higher number (>= 2) of interactions
tmp_contrasts <- getOption("contrasts")
options(contrasts = rep("contr.sum",2))
if (length(interaction_factors) >= 2){
num_inter = length(interaction_factors)
levels_inter = list()
names_inter = list()
for (i in 1:num_inter){
names_inter[[i]] = attr(interaction_factors[[i]], 'var_names')
levels_inter[[attr(interaction_factors[[i]], 'var_names')]] = levels(interaction_factors[[i]])
}
factors_inter = expand.grid(levels_inter)
factors_inter_factor = as.data.frame(lapply(factors_inter, as.factor))
#### 1.1.2
factors_inter_factor <- assign_contrast(factors_inter_factor, contrast)
####
formula_inter = paste(names_inter, collapse = '*')
eval(parse(text = paste('effect_matrix <- model.matrix(~',formula_inter,', data = factors_inter_factor)', sep='')))
for (n_c in 1: n_choice){
if (n_c > 1){
intercept_name = paste('choice', n_c,'_Intercept', sep = "")
temp <- colnames(effect_matrix)
temp[grep('Intercept', temp)] <- intercept_name
temp_m <- effect_matrix
colnames(temp_m) <- temp
}else{
# remove choice 1 intercept, identification problem
#temp_m <- effect_matrix[-grep('Intercept', effect_matrix)]
}
attr(temp_m, 'levels') = as.matrix(factors_inter)
result[[n_c]] <- temp_m
}
}else{
result = NA
}
options(contrasts = tmp_contrasts)
return(result)
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/multi.effect.matrix.interaction.R |
multi.predict.means <-
function(samples_l2_param, dataX, dataZ, X, X_original_choice, Z_full, mf1, mf2, Xsamples = NULL, Zsamples = NULL){
if(is.null(Xsamples)){
Xsamples <- dataX
}
if(is.null(Zsamples)){
Zsamples <- dataZ
}
if(!is.null(mf2))
if (length(Xsamples) != nrow(Zsamples)) stop('X, Z samples dimension mismatch.')
if (!inherits(Xsamples, 'list')) stop('Xsamples must be a list of features data.')
for (i in 1:length(Xsamples))
if (ncol(Xsamples[[i]]) != ncol(dataX[[1]]) || nrow(Xsamples[[i]]) != nrow(dataX[[1]]))
stop('level 1 samples dimension mismatch!')
#if (is.vector(samples)) samples <- matrix(samples, nrow = 1)
#if (is.vector(X)) X <- matrix(X, ncol = 1)
if (is.vector(Z_full)) Z_full <- matrix(Z_full, ncol = 1)
if(!is.null(mf2))
if (ncol(Zsamples) != ncol(dataZ)) stop('level 2 samples dimension mismatch!')
n_iter <- nrow(samples_l2_param)
num_l1 <- ncol(X[[1]])
if(is.null(mf2)){
num_l2 <- 1
}else{
num_l2 <- ncol(Z_full)
}
est_matrix <- array(0 , dim = c(num_l1, num_l2, n_iter))
for (i in 1:num_l1){
for (j in 1:n_iter)
est_matrix[i,,j] <- samples_l2_param[j,((i-1)*num_l2+1):((i-1)*num_l2+num_l2)]
}
l1_names <- attr(mf1, 'names')
if(is.null(mf2)){
l2_names <- c(" ")
}else{
l2_names <- attr(mf2, 'names')
}
l1_index_in_data <- which(colnames(dataX[[1]]) %in% l1_names)
l2_index_in_data <- which(colnames(dataZ) %in% l2_names)
# find index of level 1 factors and numeric variables
l1_factor_index_in_data <- array(dim = 0)
l1_numeric_index_in_data <- array(dim = 0)
if (length(l1_index_in_data) > 0){
for (i in 1: length(l1_index_in_data)){
if (inherits(dataX[[1]][1,l1_index_in_data[i]], 'factor'))
l1_factor_index_in_data <- c(l1_factor_index_in_data, l1_index_in_data[i])
if (inherits(dataX[[1]][1,l1_index_in_data[i]], 'integer') || inherits(dataX[[1]][1,l1_index_in_data[i]], 'numeric'))
l1_numeric_index_in_data <- c(l1_numeric_index_in_data, l1_index_in_data[i])
}
}
# find index of level 2 factors and numeric variables
l2_factor_index_in_data <- array(dim = 0)
l2_numeric_index_in_data <- array(dim = 0)
if (length(l2_index_in_data) > 0){
for (i in 1: length(l2_index_in_data)){
if (inherits(dataZ[1,l2_index_in_data[i]], 'factor'))
l2_factor_index_in_data <- c(l2_factor_index_in_data, l2_index_in_data[i])
if (inherits(dataZ[1,l2_index_in_data[i]], 'integer') || inherits(dataZ[1,l2_index_in_data[i]], 'numeric'))
l2_numeric_index_in_data <- c(l2_numeric_index_in_data, l2_index_in_data[i])
}
}
n_choice <- length(X)
prediction <- matrix(0, nrow = n_choice*length(Xsamples), ncol = 5)
colnames(prediction) <- c('Sample number', 'Choice','Median', '2.5%', '97.5%')
est_samples <- matrix(0, nrow = n_choice, ncol = n_iter)
temp_index <- 1
for (n_sample in 1 : length(Xsamples)){
l1_vector <- list()
for (n_c in 1: n_choice){
l1_vector[[n_c]] <- matrix(rep(0, num_l1), nrow = 1)
if (n_c != 1) l1_vector[[n_c]][1,n_c-1] <- 1
if (length(l1_factor_index_in_data) > 0){
index_row <- rowMatch(Xsamples[[n_sample]][n_c, l1_factor_index_in_data], X_original_choice[[n_c]][, l1_factor_index_in_data])
if (is.na(index_row)) stop('Bad samples provided! Could not find matching factors!')
l1_vector[[n_c]] <- X[[n_c]][index_row, ]
}
if (length(l1_numeric_index_in_data) > 0)
for (i in 1:length(l1_numeric_index_in_data)){
l1_vector[[n_c]][attr(X[[1]], 'numeric_index')[-c(1:(n_choice - 1))][i]] <- Xsamples[[n_sample]][n_c, l1_numeric_index_in_data[i]]
}
}
l2_vector <- matrix(c(1, rep(0, num_l2-1)), nrow = 1)
if (length(l2_factor_index_in_data) > 0){
index_row_Z <- rowMatch(Zsamples[n_sample, l2_factor_index_in_data], dataZ[, l2_factor_index_in_data])
if (is.na(index_row_Z)) stop('Bad samples provided! Could not find matching factors!')
l2_vector <- Z_full[index_row_Z, ]
}
if (length(l2_numeric_index_in_data) > 0)
for (i in 1:length(l2_numeric_index_in_data))
l2_vector[attr(Z_full, 'numeric_index')[i]] <- Zsamples[n_sample,l2_numeric_index_in_data[i]]
for(n_c in 1: n_choice){
for (n_i in 1:n_iter){
if (length(l1_vector[[n_c]]) == 1 | length(l2_vector) == 1){ # not a matrix, R somehow automatically convert dim(1,n) matrix to a vector
if (length(l1_vector[[n_c]]) == 1) temp <- matrix(est_matrix[,,n_i], nrow = 1)
if (length(l2_vector) == 1) temp <- matrix(est_matrix[,,n_i], ncol = 1)
#print(l1_vector[[n_c]])
est_samples[n_c, n_i] <- exp(matrix(l1_vector[[n_c]], nrow = 1) %*% temp %*% t(matrix(l2_vector, nrow = 1)))
}else{
est_samples[n_c, n_i] <- exp(matrix(l1_vector[[n_c]], nrow = 1) %*% est_matrix[,,n_i] %*% t(matrix(l2_vector, nrow = 1)))
}
}
}
est_prob_sum <- matrix(0, nrow = 1, ncol = n_iter)
for (n_c in 1:n_choice)
est_prob_sum <- est_prob_sum + est_samples[n_c,]
est_prob <- matrix(0, nrow = n_choice, ncol = n_iter)
for (n_c in 1:n_choice){
est_prob[n_c, ] <- est_samples[n_c, ] / est_prob_sum
means <- median(est_prob[n_c, ])
quantile_025975 <- quantile(est_prob[n_c, ], probs = c(0.025, 0.975))
prediction[temp_index, ] <- c(n_sample, n_c, round(c(means, quantile_025975), digits = 5))
temp_index <- temp_index + 1
}
}
return(prediction)
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/multi.predict.means.R |
multi.print.table.means <-
function (coeff_table, n_choice, samples_l2_param, X_names, X_assign = array(dim = 0), X_classes = character(0), Z_names, Z_assign = array(dim = 0), Z_classes = character(0),
l1_values = list(), l1_interactions = list(), l1_interactions_index = array(dim = 0),
l2_values = list(), l2_interactions = list(), l2_interactions_index = array(dim = 0),
numeric_index_in_X, numeric_index_in_Z, single_level = F, contrast = NULL){
sol_tables <- list()
if (length(X_assign) == 1 && length(Z_assign) == 1) coeff_table <- matrix(coeff_table, nrow = 1) # the case that there is only one intercept
n_sample <- nrow(samples_l2_param)
num_l1 <- length(X_assign)
num_l2 <- length(Z_assign)
est_matrix <- array(0 , dim = c(num_l1, num_l2, n_sample), dimnames = list(X_names, Z_names, NULL))
for (i in 1:num_l1){
for (j in 1:n_sample)
est_matrix[i,,j] <- samples_l2_param[j,((i-1)*num_l2+1):((i-1)*num_l2+num_l2)]
}
if(single_level){
cat('\n')
cat('Table of probabilities for each category of the response\n')
cat('--------------------------------------------------------\n')
# Grand mean
# cat('\n')
# cat('Grand mean: \n')
sol_tables[['Grand mean(each response): \n']] <- list()
l1_v <- list()
for (n_c in 1:n_choice){
temp <- matrix(rep(0, num_l1), nrow = 1)
if (n_c != 0)
temp[n_c - 1] <- 1
l1_v[[n_c]] <- temp
}
l2_v <- matrix(c(1, rep(0, num_l2 - 1)), nrow = 1)
# gmean <- est.multi(est_matrix, n_sample, l1_v, l2_v)
# for (n_c in 1:n_choice){
# cat('\n')
# cat('Choice:',n_c,'\n')
# cat(round(mean(gmean[[n_c]]), digits = 4), '\n')
# temp_title <- paste('Choice: ',n_c, sep ="")
# sol_tables[['Grand mean(each response): \n']][[temp_title]] <- as.table(matrix(round(quantile(gmean[[n_c]], probs = c(0.025, 0.975)), digits = 4), nrow = 1, ncol = 2, dimnames = list('',c('2.5%','97.5%'))))
# print(sol_tables[['Grand mean(each response): \n']][[temp_title]])
# }
# means of main effect in level 1 and 2
if (length(X_classes) != 0){
l1_factors <- which(X_classes == 'factor')
if (length(l1_factors) != 0){
cat('\n')
#cat('Means for factors at level 1: \n')
sol_tables[['Means for factors at level 1: \n']] <- list()
l1_matrix <- list()
#l2_v <- matrix(c(1, rep(0, num_l2 - 1)), nrow = 1) # only look at the intercept in level 2
for (i in 1:length(l1_factors)){
l1_matrix[[i]] <- multi.effect.matrix.factor(n_choice, l1_values[[l1_factors[i]]], X_assign, l1_factors[i], numeric_index_in_X, contrast = contrast)
# Compute median and quantile
# print(dim(est_matrix))
# print(est_matrix[,,1])
# print(n_sample)
# print(l2_v)
est_samples <- est.multi(est_matrix, n_sample, l1_matrix[[i]], l2_v)
cat('\nFactor:',attr(X_classes, 'names')[l1_factors[i]],'\n')
for (n_c in 1: n_choice){
cat('\n')
cat('Choice:',n_c,'\n')
means <- apply(est_samples[[n_c]], 1, mean)
quantile_025 <- apply(est_samples[[n_c]], 1, quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_samples[[n_c]], 1, quantile, probs = 0.975, type = 3, na.rm = FALSE)
table <- matrix(NA, nrow = length(means), ncol = 4)
table[, 2] <- means
table[, 3] <- pmin(quantile_025, quantile_975)
table[, 4] <- pmax(quantile_025, quantile_975)
table <- round(table, digits = 4)
table[, 1] <- attr(l1_matrix[[i]][[1]],'levels')
colnames(table) <- c(attr(X_classes, 'names')[l1_factors[i]], 'mean', '2.5%', '97.5%')
rownames(table) <- rep('', nrow(table))
cat('\n')
print(as.table(table))
temp_title <- paste('Choice: ',n_c, sep ="")
sol_tables[['Means for factors at level 1: \n']][[temp_title]] <- as.table(table)
}
}
}
}
if (length(Z_classes) != 0){
l2_factors <- which(Z_classes == 'factor')
if (length(l2_factors) != 0){
cat('\n')
#cat('Means for factors at level 2: \n')
sol_tables[['Means for factors at level 2: \n']] <- list()
l2_matrix <- list()
for (i in 1:length(l2_factors)){
l2_matrix[[i]] <- multi.effect.matrix.factor(n_choice, l2_values[[l2_factors[i]]], Z_assign, l2_factors[i], numeric_index_in_Z, contrast = contrast)
est_samples <- est.multi(est_matrix, n_sample, l1_v, l2_matrix[[i]])
cat('\nFactor:',attr(Z_classes, 'names')[l2_factors[i]],'\n')
for (n_c in 1: n_choice){
cat('\n')
cat('Choice:',n_c,'\n')
means <- apply(est_samples[[n_c]], 1, mean)
quantile_025 <- apply(est_samples[[n_c]], 1, quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_samples[[n_c]], 1, quantile, probs = 0.975, type = 3, na.rm = FALSE)
table <- matrix(NA, nrow = length(means), ncol = 4)
table[, 2] <- means
table[, 3] <- pmin(quantile_025, quantile_975)
table[, 4] <- pmax(quantile_025, quantile_975)
table <- round(table, digits = 4)
table[, 1] <- attr(l2_matrix[[i]],'levels')
colnames(table) <- c(attr(Z_classes, 'names')[l2_factors[i]], 'mean', '2.5%', '97.5%')
rownames(table) <- rep('', nrow(table))
cat('\n')
print(as.table(table))
temp_title <- paste('Choice: ',n_c, sep ="")
sol_tables[['Means for factors at level 2: \n']][[temp_title]] <- as.table(table)
}
}
}
}
# means of interactions between level 1 and 2
if (length(X_classes) != 0 && length(Z_classes) != 0){
if (length(l1_factors) != 0 && length(l2_factors) != 0){
cat('\n')
#cat('Means for interactions between level 1 and level 2 factors: \n')
sol_tables[['Means for interactions between level 1 and level 2 factors: \n']] <- list()
for (i in 1:length(l1_factors)){
for (j in 1:length(l2_factors)){
#means <- l1_matrix[[i]] %*% est_matrix_mean %*% t(l2_matrix[[j]])
#quantile_025 <- l1_matrix[[i]] %*% est_matrix_025 %*% t(l2_matrix[[j]])
#quantile_975 <- l1_matrix[[i]] %*% est_matrix_975 %*% t(l2_matrix[[j]])
est_samples <- est.multi(est_matrix, n_sample, l1_matrix[[i]], l2_matrix[[j]])
cat('\nFactor:',attr(X_classes, 'names')[l1_factors[i]],' ',attr(Z_classes, 'names')[l2_factors[j]],'\n')
for (n_c in 1: n_choice){
cat('\n')
cat('Choice:',n_c,'\n')
means <- apply(est_samples[[n_c]], c(1,2), mean)
quantile_025 <- apply(est_samples[[n_c]], c(1,2), quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_samples[[n_c]], c(1,2), quantile, probs = 0.975, type = 3, na.rm = FALSE)
table <- matrix(NA, nrow = nrow(l1_matrix[[i]][[1]]) * nrow(l2_matrix[[j]]), ncol = 5)
for (k1 in 1:nrow(l1_matrix[[i]][[1]])){
temp <- ((k1-1) * nrow(l2_matrix[[j]]) + 1):((k1-1) * nrow(l2_matrix[[j]]) + nrow(l2_matrix[[j]]))
table[temp, 3] <- round(means[k1,], digits = 4)
table[temp, 4] <- pmin(round(quantile_025[k1,], digits = 4), round(quantile_975[k1,], digits = 4))
table[temp, 5] <- pmax(round(quantile_025[k1,], digits = 4), round(quantile_975[k1,], digits = 4))
table[temp, 1] <- rep(attr(l1_matrix[[i]][[1]],'levels')[k1], nrow(l2_matrix[[j]]))
table[temp, 2] <- attr(l2_matrix[[j]],'levels')
}
colnames(table) <- c(attr(X_classes, 'names')[l1_factors[i]], attr(Z_classes, 'names')[l2_factors[j]], 'mean', '2.5%', '97.5%')
rownames(table) <- rep('', nrow(table))
cat('\n')
print(as.table(table))
temp_title <- paste('Choice: ',n_c, sep ="")
sol_tables[['Means for interactions between level 1 and level 2 factors: \n']][[temp_title]] <- as.table(table)
}
}
}
}
}
# means of interactions in level 1 or 2
if (length(l1_interactions) > 0){
cat('\n')
#cat('Means for interactions at level 1: \n')
sol_tables[['Means for interactions at level 1: \n']] <- list()
l1_inter_matrix <- list()
index <- 1
for (i in 1:length(l1_interactions)){
temp1 <- l1_values[l1_interactions[[i]]]
if (length(temp1) >= 2){
#temp2 <- list()
#for (j in 1:length(temp1))
#temp2[[j]] <- levels(temp1[[j]])
l1_inter_matrix[[index]] <- multi.effect.matrix.interaction(n_choice, interaction_factors = temp1, assign = X_assign,
l1_interactions[[i]], index_inter_factor = l1_interactions_index[i],
numeric_index_in_X, contrast = contrast)
est_samples <- est.multi(est_matrix, n_sample, l1_inter_matrix[[index]], l2_v)
cat('\nFactor:',attr(X_classes, 'names')[l1_interactions[[i]] - 1],'\n')
for (n_c in 1: n_choice){
cat('\n')
cat('Choice:',n_c,'\n')
means <- apply(est_samples[[n_c]], 1, mean)
quantile_025 <- apply(est_samples[[n_c]], 1, quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_samples[[n_c]], 1, quantile, probs = 0.975, type = 3, na.rm = FALSE)
table <- cbind(attr(l1_inter_matrix[[index]][[1]], 'levels'),
round(means, digits = 4),
pmin(round(quantile_025, digits = 4), round(quantile_975, digits = 4)),
pmax(round(quantile_025, digits = 4), round(quantile_975, digits = 4)))
colnames(table) <- c(attr(X_classes, 'names')[l1_interactions[[i]]], 'mean', '2.5%', '97.5%')
rownames(table) <- rep('', nrow(table))
cat('\n')
print(as.table(table))
temp_title <- paste('Choice: ', n_c, sep ="")
sol_tables[['Means for interactions at level 1: \n']][[temp_title]] <- as.table(table)
}
# print the interaction between this interaction and level 2 factors if there exists
if (length(Z_classes) != 0){
l2_factors <- which(Z_classes == 'factor')
if (length(l2_factors) != 0){
cat('\n')
#cat('Means for interactions between level 1 interactions and level 2 factors: \n')
sol_tables[['Means for interactions between level 1 interactions and level 2 factors: \n']] <- list()
for (j in 1:length(l2_factors)){
#means <- l1_inter_matrix[[index]] %*% est_matrix_mean %*% t(l2_matrix[[j]])
#quantile_025 <- l1_inter_matrix[[index]] %*% est_matrix_025 %*% t(l2_matrix[[j]])
#quantile_975 <- l1_inter_matrix[[index]] %*% est_matrix_975 %*% t(l2_matrix[[j]])
est_samples <- est.multi(est_matrix, n_sample, l1_inter_matrix[[index]], l2_matrix[[j]])
cat('\nFactor:',attr(X_classes, 'names')[l1_interactions[[i]]],attr(Z_classes, 'names')[l2_factors[j]],'\n')
for (n_c in 1: n_choice){
cat('\n')
cat('Choice:',n_c,'\n')
means <- apply(est_samples[[n_c]], c(1,2), mean)
quantile_025 <- apply(est_samples[[n_c]], c(1,2), quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_samples[[n_c]], c(1,2), quantile, probs = 0.975, type = 3, na.rm = FALSE)
table <- matrix(NA, nrow = nrow(l1_inter_matrix[[i]][[1]]) * nrow(l2_matrix[[j]]), ncol = 6)
for (k1 in 1:nrow(l1_inter_matrix[[i]][[1]])){
temp <- ((k1-1) * nrow(l2_matrix[[j]]) + 1):((k1-1) * nrow(l2_matrix[[j]]) + nrow(l2_matrix[[j]]))
table[temp, 4] <- round(means[k1,], digits = 4)
table[temp, 5] <- pmin(round(quantile_025[k1,], digits = 4), round(quantile_975[k1,], digits = 4))
table[temp, 6] <- pmax(round(quantile_025[k1,], digits = 4), round(quantile_975[k1,], digits = 4))
table[temp, 1] <- attr(l1_inter_matrix[[i]][[1]],'levels')[k1,][1]
table[temp, 2] <- attr(l1_inter_matrix[[i]][[1]],'levels')[k1,][2]
table[temp, 3] <- attr(l2_matrix[[j]],'levels')
}
colnames(table) <- c(attr(X_classes, 'names')[l1_interactions[[i]] - 1], attr(Z_classes, 'names')[l2_factors[j]], 'mean', '2.5%', '97.5%')
rownames(table) <- rep('', nrow(table))
cat('\n')
print(as.table(table))
temp_title <- paste('Choice: ', n_c, sep ="")
sol_tables[['Means for interactions between level 1 interactions and level 2 factors: \n']][[temp_title]] <- as.table(table)
}
}
}
}
index <- index + 1
}
}
}
if (length(l2_interactions) > 0){
cat('\n')
#cat('Means for interactions at level 2: \n')
sol_tables[['Means for interactions at level 2: \n']] <- list()
l2_inter_matrix <- list()
index <- 1
for (i in 1:length(l2_interactions)){
temp1 <- l2_values[l2_interactions[[i]]]
if (length(temp1) >= 2){
#temp2 <- list()
#for (j in 1:length(temp1))
#temp2[[j]] <- levels(temp1[[j]])
l2_inter_matrix[[index]] <- multi.effect.matrix.interaction(n_choice, interaction_factors = temp1, assign = Z_assign,
l2_interactions[[i]], index_inter_factor = l2_interactions_index[i],
numeric_index_in_Z, contrast = contrast)
est_samples <- est.multi(est_matrix, n_sample, l1_v, l2_inter_matrix[[index]])
cat('\nFactor:',attr(Z_classes, 'names')[l2_interactions[[i]]],'\n')
for (n_c in 1: n_choice){
cat('\n')
cat('Choice:',n_c,'\n')
means <- apply(est_samples[[n_c]], 1, mean)
quantile_025 <- apply(est_samples[[n_c]], 1, quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_samples[[n_c]], 1, quantile, probs = 0.975, type = 3, na.rm = FALSE)
table <- cbind(attr(l2_inter_matrix[[index]], 'levels'),
matrix(round(means, digits = 4), ncol = 1),
matrix(pmin(round(quantile_025, digits = 4), round(quantile_975, digits = 4)), ncol = 1),
matrix(pmax(round(quantile_025, digits = 4), round(quantile_975, digits = 4)), ncol = 1))
colnames(table) <- c(attr(Z_classes, 'names')[l2_interactions[[i]]], 'mean', '2.5%', '97.5%')
rownames(table) <- rep('', nrow(table))
cat('\n')
print(as.table(table))
temp_title <- paste('Choice: ', n_c, sep ="")
sol_tables[['Means for interactions at level 2: \n']][[temp_title]] <- as.table(table)
}
# print the interaction between this interaction and level 1 factors if there exists
if (length(X_classes) != 0){
l1_factors <- which(X_classes == 'factor')
if (length(l1_factors) != 0){
cat('\n')
cat('Means for interactions between level 2 interactions and level 1 factors: \n')
sol_tables[['Means for interactions between level 2 interactions and level 1 factors: \n']] <- list()
for (j in 1:length(l1_factors)){
#means <- l1_matrix[[j]] %*% est_matrix_mean %*% t(l2_inter_matrix[[index]])
#quantile_025 <- l1_matrix[[j]] %*% est_matrix_025 %*% t(l2_inter_matrix[[index]])
#quantile_975 <- l1_matrix[[j]] %*% est_matrix_975 %*% t(l2_inter_matrix[[index]])
est_samples <- est.multi(est_matrix, n_sample, l1_matrix[[j]], l2_inter_matrix[[index]])
cat('\nFactor:',attr(X_classes, 'names')[l1_factors[[j]]],attr(Z_classes, 'names')[l2_interactions[[i]]], '\n')
for (n_c in 1: n_choice){
cat('\n')
cat('Choice:',n_c,'\n')
means <- apply(est_samples[[n_c]], c(1,2), mean)
quantile_025 <- apply(est_samples[[n_c]], c(1,2), quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_samples[[n_c]], c(1,2), quantile, probs = 0.975, type = 3, na.rm = FALSE)
table <- matrix(NA, nrow = nrow(l1_matrix[[j]][[1]]) * nrow(l2_inter_matrix[[index]]), ncol = 6)
for (k1 in 1:nrow(l1_matrix[[j]][[1]])){
temp <- ((k1-1) * nrow(l2_inter_matrix[[index]]) + 1):((k1-1) * nrow(l2_inter_matrix[[index]]) + nrow(l2_inter_matrix[[index]]))
table[temp, 4] <- round(means[k1,], digits = 4)
table[temp, 5] <- pmin(round(quantile_025[k1,], digits = 4), round(quantile_975[k1,], digits = 4))
table[temp, 6] <- pmax(round(quantile_025[k1,], digits = 4), round(quantile_975[k1,], digits = 4))
table[temp, 1] <- attr(l1_matrix[[j]][[1]],'levels')[k1]
table[temp, 2:3] <- attr(l2_inter_matrix[[i]],'levels')
}
colnames(table) <- c(attr(X_classes, 'names')[l1_factors[[j]]], attr(Z_classes, 'names')[l2_interactions[[i]]], 'mean', '2.5%', '97.5%')
rownames(table) <- rep('', nrow(table))
cat('\n')
print(as.table(table))
temp_title <- paste('Choice: ', n_c, sep ="")
sol_tables[['Means for interactions between level 2 interactions and level 1 factors: \n']][[temp_title]] <- as.table(table)
}
}
}
}
index <- index + 1
}
}
}
}else{
# compute the overall table of means(prediction of y)
cat('\n')
cat('Table of means of the response\n')
cat('------------------------------\n')
# Grand mean
cat('\n')
cat('Grand mean: \n')
l1_v <- list()
for (n_c in 1:n_choice){
temp <- matrix(rep(0, num_l1), nrow = 1)
if (n_c != 0)
temp[n_c - 1] <- 1
l1_v[[n_c]] <- temp
}
l2_v <- matrix(c(1, rep(0, num_l2 - 1)), nrow = 1) # only look at the intercept in level 2
gmean <- est.multi(est_matrix, n_sample, l1_v, l2_v)
ggmean <- 0
for (n_c in 1:n_choice){
ggmean <- ggmean + n_c*gmean[[n_c]]
}
cat(round(mean(ggmean), digits = 4), '\n')
sol_tables[['Grand mean: \n']] <- as.table(matrix(round(quantile(ggmean, probs = c(0.025, 0.975)), digits = 4), nrow = 1, ncol = 2, dimnames = list('',c('2.5%','97.5%'))))
print(sol_tables[['Grand mean: \n']])
# means by main effect in level 1 and 2
if (length(X_classes) != 0){
l1_factors <- which(X_classes == 'factor')
if (length(l1_factors) != 0){
cat('\n')
cat('Table of means for factors at level 1: \n')
l1_matrix <- list()
#l2_v <- matrix(c(1, rep(0, num_l2 - 1)), nrow = 1) # only look at the intercept in level 2
for (i in 1:length(l1_factors)){
l1_matrix[[i]] <- multi.effect.matrix.factor(n_choice, l1_values[[l1_factors[i]]], X_assign, l1_factors[i], numeric_index_in_X, contrast = contrast)
# Compute median and quantile
est_samples <- est.multi(est_matrix, n_sample, l1_matrix[[i]], l2_v)
est_l1mean <- 0
cat('\nFactor:',attr(X_classes, 'names')[l1_factors[i]],'\n')
for (n_c in 1: n_choice){
est_l1mean <- est_l1mean + n_c*est_samples[[n_c]]
}
means <- apply(est_l1mean, 1, mean)
quantile_025 <- apply(est_l1mean, 1, quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_l1mean, 1, quantile, probs = 0.975, type = 3, na.rm = FALSE)
table <- matrix(NA, nrow = length(means), ncol = 4)
table[, 2] <- means
table[, 3] <- pmin(quantile_025, quantile_975)
table[, 4] <- pmax(quantile_025, quantile_975)
table <- round(table, digits = 4)
table[, 1] <- attr(l1_matrix[[i]][[1]],'levels')
colnames(table) <- c(attr(X_classes, 'names')[l1_factors[i]], 'mean', '2.5%', '97.5%')
rownames(table) <- rep('', nrow(table))
cat('\n')
print(as.table(table))
sol_tables[['Table of means for factors at level 1: \n']] <- as.table(table)
}
}
}
if (length(Z_classes) != 0){
l2_factors <- which(Z_classes == 'factor')
if (length(l2_factors) != 0){
cat('\n')
cat('Table of means of for factors at level 2: \n')
l2_matrix <- list()
for (i in 1:length(l2_factors)){
l2_matrix[[i]] <- effect.matrix.factor(l2_values[[l2_factors[i]]], Z_assign, l2_factors[i], numeric_index_in_Z, contrast = contrast)
est_samples <- est.multi(est_matrix, n_sample, l1_v, l2_matrix[[i]])
est_l2mean <- 0
cat('\nFactor:',attr(Z_classes, 'names')[l2_factors[i]],'\n')
for (n_c in 1: n_choice){
est_l2mean <- est_l2mean + n_c*est_samples[[n_c]]
}
means <- apply(est_l2mean, 1, mean)
quantile_025 <- apply(est_l2mean, 1, quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_l2mean, 1, quantile, probs = 0.975, type = 3, na.rm = FALSE)
table <- matrix(NA, nrow = length(means), ncol = 4)
table[, 2] <- means
table[, 3] <- pmin(quantile_025, quantile_975)
table[, 4] <- pmax(quantile_025, quantile_975)
table <- round(table, digits = 4)
table[, 1] <- attr(l2_matrix[[i]],'levels')
colnames(table) <- c(attr(Z_classes, 'names')[l2_factors[i]], 'mean', '2.5%', '97.5%')
rownames(table) <- rep('', nrow(table))
cat('\n')
print(as.table(table))
sol_tables[['Table of means of for factors at level 2: \n']] <- as.table(table)
}
}
}
# means by interactions between level 1 and 2
if (length(X_classes) != 0 && length(Z_classes) != 0){
if (length(l1_factors) != 0 && length(l2_factors) != 0){
cat('\n')
cat('Table of means for interactions between level 1 and level 2 factors: \n')
for (i in 1:length(l1_factors)){
for (j in 1:length(l2_factors)){
est_l1l2mean <- 0
est_samples <- est.multi(est_matrix, n_sample, l1_matrix[[i]], l2_matrix[[j]])
cat('\nFactor:',attr(X_classes, 'names')[l1_factors[i]],' ',attr(Z_classes, 'names')[l2_factors[j]],'\n')
for (n_c in 1: n_choice){
est_l1l2mean <- est_l1l2mean + n_c*est_samples[[n_c]]
}
means <- apply(est_l1l2mean, c(1,2), mean)
quantile_025 <- apply(est_l1l2mean, c(1,2), quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_l1l2mean, c(1,2), quantile, probs = 0.975, type = 3, na.rm = FALSE)
table <- matrix(NA, nrow = nrow(l1_matrix[[i]][[1]]) * nrow(l2_matrix[[j]]), ncol = 5)
for (k1 in 1:nrow(l1_matrix[[i]][[1]])){
temp <- ((k1-1) * nrow(l2_matrix[[j]]) + 1):((k1-1) * nrow(l2_matrix[[j]]) + nrow(l2_matrix[[j]]))
table[temp, 3] <- round(means[k1,], digits = 4)
table[temp, 4] <- pmin(round(quantile_025[k1,], digits = 4), round(quantile_975[k1,], digits = 4))
table[temp, 5] <- pmax(round(quantile_025[k1,], digits = 4), round(quantile_975[k1,], digits = 4))
table[temp, 1] <- rep(attr(l1_matrix[[i]][[1]],'levels')[k1], nrow(l2_matrix[[j]]))
table[temp, 2] <- attr(l2_matrix[[j]],'levels')
}
colnames(table) <- c(attr(X_classes, 'names')[l1_factors[i]], attr(Z_classes, 'names')[l2_factors[j]], 'mean', '2.5%', '97.5%')
rownames(table) <- rep('', nrow(table))
cat('\n')
print(as.table(table))
sol_tables[['Table of means for interactions between level 1 and level 2 factors: \n']] <- as.table(table)
}
}
}
}
# means of interactions in level 1 or 2
if (length(l1_interactions) > 0){
cat('\n')
cat('Table of means for interactions at level 1: \n')
l1_inter_matrix <- list()
index <- 1
for (i in 1:length(l1_interactions)){
temp1 <- l1_values[l1_interactions[[i]]]
if (length(temp1) >= 2){
#temp2 <- list()
#for (j in 1:length(temp1))
#temp2[[j]] <- levels(temp1[[j]])
l1_inter_matrix[[index]] <- multi.effect.matrix.interaction(n_choice, interaction_factors = temp1, assign = X_assign,
l1_interactions[[i]], index_inter_factor = l1_interactions_index[i],
numeric_index_in_X, contrast = contrast)
est_l1inmean <- 0
est_samples <- est.multi(est_matrix, n_sample, l1_inter_matrix[[index]], l2_v)
cat('\nFactor:',attr(X_classes, 'names')[l1_interactions[[i]] - 1],'\n')
for (n_c in 1: n_choice){
est_l1inmean <- est_l1inmean + n_c*est_samples[[n_c]]
}
means <- apply(est_l1inmean, 1, mean)
quantile_025 <- apply(est_l1inmean, 1, quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_l1inmean, 1, quantile, probs = 0.975, type = 3, na.rm = FALSE)
table <- cbind(attr(l1_inter_matrix[[index]][[1]], 'levels'),
round(means, digits = 4),
pmin(round(quantile_025, digits = 4), round(quantile_975, digits = 4)),
pmax(round(quantile_025, digits = 4), round(quantile_975, digits = 4)))
colnames(table) <- c(attr(X_classes, 'names')[l1_interactions[[i]]], 'mean', '2.5%', '97.5%')
rownames(table) <- rep('', nrow(table))
cat('\n')
print(as.table(table))
sol_tables[['Table of means for interactions at level 1: \n']] <- as.table(table)
# print the interaction between this interaction and level 2 factors if there exists
if (length(Z_classes) != 0){
l2_factors <- which(Z_classes == 'factor')
if (length(l2_factors) != 0){
cat('\n')
cat('Table of means for interactions between level 1 interactions and level 2 factors: \n')
for (j in 1:length(l2_factors)){
est_l1inl2mean <- 0
est_samples <- est.multi(est_matrix, n_sample, l1_inter_matrix[[index]], l2_matrix[[j]])
cat('\nFactor:',attr(X_classes, 'names')[l1_interactions[[i]]],attr(Z_classes, 'names')[l2_factors[j]],'\n')
for (n_c in 1: n_choice){
est_l1inl2mean <- est_l1inl2mean + n_c*est_samples[[n_c]]
}
means <- apply(est_l1inl2mean, c(1,2), mean)
quantile_025 <- apply(est_l1inl2mean, c(1,2), quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_l1inl2mean, c(1,2), quantile, probs = 0.975, type = 3, na.rm = FALSE)
table <- matrix(NA, nrow = nrow(l1_inter_matrix[[i]][[1]]) * nrow(l2_matrix[[j]]), ncol = 6)
for (k1 in 1:nrow(l1_inter_matrix[[i]][[1]])){
temp <- ((k1-1) * nrow(l2_matrix[[j]]) + 1):((k1-1) * nrow(l2_matrix[[j]]) + nrow(l2_matrix[[j]]))
table[temp, 4] <- round(means[k1,], digits = 4)
table[temp, 5] <- pmin(round(quantile_025[k1,], digits = 4), round(quantile_975[k1,], digits = 4))
table[temp, 6] <- pmax(round(quantile_025[k1,], digits = 4), round(quantile_975[k1,], digits = 4))
table[temp, 1] <- attr(l1_inter_matrix[[i]][[1]],'levels')[k1,][1]
table[temp, 2] <- attr(l1_inter_matrix[[i]][[1]],'levels')[k1,][2]
table[temp, 3] <- attr(l2_matrix[[j]],'levels')
}
colnames(table) <- c(attr(X_classes, 'names')[l1_interactions[[i]] - 1], attr(Z_classes, 'names')[l2_factors[j]], 'mean', '2.5%', '97.5%')
rownames(table) <- rep('', nrow(table))
cat('\n')
print(as.table(table))
sol_tables[['Table of means for interactions between level 1 interactions and level 2 factors: \n']] <- as.table(table)
}
}
}
index <- index + 1
}
}
}
if (length(l2_interactions) > 0){
cat('\n')
cat('Table of means for interactions at level 2: \n')
l2_inter_matrix <- list()
index <- 1
for (i in 1:length(l2_interactions)){
temp1 <- l2_values[l2_interactions[[i]]]
if (length(temp1) >= 2){
#temp2 <- list()
#for (j in 1:length(temp1))
#temp2[[j]] <- levels(temp1[[j]])
l2_inter_matrix[[index]] <- effect.matrix.interaction(interaction_factors = temp1, assign = Z_assign,
l2_interactions[[i]], index_inter_factor = l2_interactions_index[i],
numeric_index_in_Z, contrast = contrast)
est_l2inmean <- 0
est_samples <- est.multi(est_matrix, n_sample, l1_v, l2_inter_matrix[[index]])
cat('\nFactor:',attr(Z_classes, 'names')[l2_interactions[[i]]],'\n')
for (n_c in 1: n_choice){
est_l2inmean <- est_l2inmean + n_c*est_samples[[n_c]]
}
means <- apply(est_l2inmean, 1, mean)
quantile_025 <- apply(est_l2inmean, 1, quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_l2inmean, 1, quantile, probs = 0.975, type = 3, na.rm = FALSE)
table <- cbind(attr(l2_inter_matrix[[index]], 'levels'),
matrix(round(means, digits = 4), ncol = 1),
matrix(pmin(round(quantile_025, digits = 4), round(quantile_975, digits = 4)), ncol = 1),
matrix(pmax(round(quantile_025, digits = 4), round(quantile_975, digits = 4)), ncol = 1))
colnames(table) <- c(attr(Z_classes, 'names')[l2_interactions[[i]]], 'mean', '2.5%', '97.5%')
rownames(table) <- rep('', nrow(table))
cat('\n')
print(as.table(table))
sol_tables[['Table of means for interactions at level 2: \n']] <- as.table(table)
# print the interaction between this interaction and level 1 factors if there exists
if (length(X_classes) != 0){
l1_factors <- which(X_classes == 'factor')
if (length(l1_factors) != 0){
cat('\n')
cat('Table of means for interactions between level 2 interactions and level 1 factors: \n')
for (j in 1:length(l1_factors)){
est_l2inl1mean <- 0
est_samples <- est.multi(est_matrix, n_sample, l1_matrix[[j]], l2_inter_matrix[[index]])
cat('\nFactor:',attr(X_classes, 'names')[l1_factors[[j]]],attr(Z_classes, 'names')[l2_interactions[[i]]], '\n')
for (n_c in 1: n_choice){
est_l2inl1mean<- est_l2inl1mean + n_c*est_samples[[n_c]]
}
means <- apply(est_l2inl1mean, c(1,2), mean)
quantile_025 <- apply(est_l2inl1mean, c(1,2), quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_l2inl1mean, c(1,2), quantile, probs = 0.975, type = 3, na.rm = FALSE)
table <- matrix(NA, nrow = nrow(l1_matrix[[j]][[1]]) * nrow(l2_inter_matrix[[index]]), ncol = 6)
for (k1 in 1:nrow(l1_matrix[[j]][[1]])){
temp <- ((k1-1) * nrow(l2_inter_matrix[[index]]) + 1):((k1-1) * nrow(l2_inter_matrix[[index]]) + nrow(l2_inter_matrix[[index]]))
table[temp, 4] <- round(means[k1,], digits = 4)
table[temp, 5] <- pmin(round(quantile_025[k1,], digits = 4), round(quantile_975[k1,], digits = 4))
table[temp, 6] <- pmax(round(quantile_025[k1,], digits = 4), round(quantile_975[k1,], digits = 4))
table[temp, 1] <- attr(l1_matrix[[j]][[1]],'levels')[k1]
table[temp, 2:3] <- attr(l2_inter_matrix[[i]],'levels')
}
colnames(table) <- c(attr(X_classes, 'names')[l1_factors[[j]]], attr(Z_classes, 'names')[l2_interactions[[i]]], 'mean', '2.5%', '97.5%')
rownames(table) <- rep('', nrow(table))
cat('\n')
print(as.table(table))
sol_tables[['Table of means for interactions between level 2 interactions and level 1 factors: \n']] <- as.table(table)
}
}
}
index <- index + 1
}
}
}
cat('\n')
cat('Table of probabilities for each category of the response\n')
cat('-------------------------------------------------------\n')
# Grand mean
cat('\n')
cat('Grand mean: \n')
sol_tables[['Grand mean(each response): \n']] <- list()
l1_v <- list()
for (n_c in 1:n_choice){
temp <- matrix(rep(0, num_l1), nrow = 1)
if (n_c != 0)
temp[n_c - 1] <- 1
l1_v[[n_c]] <- temp
}
l2_v <- matrix(c(1, rep(0, num_l2 - 1)), nrow = 1)
gmean <- est.multi(est_matrix, n_sample, l1_v, l2_v)
for (n_c in 1:n_choice){
cat('\n')
cat('Choice:',n_c,'\n')
cat(round(mean(gmean[[n_c]]), digits = 4), '\n')
temp_title <- paste('Choice: ',n_c, sep ="")
sol_tables[['Grand mean(each response): \n']][[temp_title]] <- as.table(matrix(round(quantile(gmean[[n_c]], probs = c(0.025, 0.975)), digits = 4), nrow = 1, ncol = 2, dimnames = list('',c('2.5%','97.5%'))))
print(sol_tables[['Grand mean(each response): \n']][[temp_title]])
}
# means of main effect in level 1 and 2
if (length(X_classes) != 0){
l1_factors <- which(X_classes == 'factor')
if (length(l1_factors) != 0){
cat('\n')
cat('Means for factors at level 1: \n')
sol_tables[['Means for factors at level 1: \n']] <- list()
l1_matrix <- list()
#l2_v <- matrix(c(1, rep(0, num_l2 - 1)), nrow = 1) # only look at the intercept in level 2
for (i in 1:length(l1_factors)){
l1_matrix[[i]] <- multi.effect.matrix.factor(n_choice, l1_values[[l1_factors[i]]], X_assign, l1_factors[i], numeric_index_in_X, contrast = contrast)
# Compute median and quantile
est_samples <- est.multi(est_matrix, n_sample, l1_matrix[[i]], l2_v)
cat('\nFactor:',attr(X_classes, 'names')[l1_factors[i]],'\n')
for (n_c in 1: n_choice){
cat('\n')
cat('Choice:',n_c,'\n')
means <- apply(est_samples[[n_c]], 1, mean)
quantile_025 <- apply(est_samples[[n_c]], 1, quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_samples[[n_c]], 1, quantile, probs = 0.975, type = 3, na.rm = FALSE)
table <- matrix(NA, nrow = length(means), ncol = 4)
table[, 2] <- means
table[, 3] <- pmin(quantile_025, quantile_975)
table[, 4] <- pmax(quantile_025, quantile_975)
table <- round(table, digits = 4)
table[, 1] <- attr(l1_matrix[[i]][[1]],'levels')
colnames(table) <- c(attr(X_classes, 'names')[l1_factors[i]], 'mean', '2.5%', '97.5%')
rownames(table) <- rep('', nrow(table))
cat('\n')
print(as.table(table))
temp_title <- paste('Choice: ',n_c, sep ="")
sol_tables[['Means for factors at level 1: \n']][[temp_title]] <- as.table(table)
}
}
}
}
if (length(Z_classes) != 0){
l2_factors <- which(Z_classes == 'factor')
if (length(l2_factors) != 0){
cat('\n')
cat('Means for factors at level 2: \n')
sol_tables[['Means for factors at level 2: \n']] <- list()
l2_matrix <- list()
for (i in 1:length(l2_factors)){
l2_matrix[[i]] <- effect.matrix.factor(l2_values[[l2_factors[i]]], Z_assign, l2_factors[i], numeric_index_in_Z, contrast = contrast)
est_samples <- est.multi(est_matrix, n_sample, l1_v, l2_matrix[[i]])
cat('\nFactor:',attr(Z_classes, 'names')[l2_factors[i]],'\n')
for (n_c in 1: n_choice){
cat('\n')
cat('Choice:',n_c,'\n')
means <- apply(est_samples[[n_c]], 1, mean)
quantile_025 <- apply(est_samples[[n_c]], 1, quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_samples[[n_c]], 1, quantile, probs = 0.975, type = 3, na.rm = FALSE)
table <- matrix(NA, nrow = length(means), ncol = 4)
table[, 2] <- means
table[, 3] <- pmin(quantile_025, quantile_975)
table[, 4] <- pmax(quantile_025, quantile_975)
table <- round(table, digits = 4)
table[, 1] <- attr(l2_matrix[[i]],'levels')
colnames(table) <- c(attr(Z_classes, 'names')[l2_factors[i]], 'mean', '2.5%', '97.5%')
rownames(table) <- rep('', nrow(table))
cat('\n')
print(as.table(table))
temp_title <- paste('Choice: ',n_c, sep ="")
sol_tables[['Means for factors at level 2: \n']][[temp_title]] <- as.table(table)
}
}
}
}
# means of interactions between level 1 and 2
if (length(X_classes) != 0 && length(Z_classes) != 0){
if (length(l1_factors) != 0 && length(l2_factors) != 0){
cat('\n')
cat('Means for interactions between level 1 and level 2 factors: \n')
sol_tables[['Means for interactions between level 1 and level 2 factors: \n']] <- list()
for (i in 1:length(l1_factors)){
for (j in 1:length(l2_factors)){
#means <- l1_matrix[[i]] %*% est_matrix_mean %*% t(l2_matrix[[j]])
#quantile_025 <- l1_matrix[[i]] %*% est_matrix_025 %*% t(l2_matrix[[j]])
#quantile_975 <- l1_matrix[[i]] %*% est_matrix_975 %*% t(l2_matrix[[j]])
est_samples <- est.multi(est_matrix, n_sample, l1_matrix[[i]], l2_matrix[[j]])
cat('\nFactor:',attr(X_classes, 'names')[l1_factors[i]],' ',attr(Z_classes, 'names')[l2_factors[j]],'\n')
for (n_c in 1: n_choice){
cat('\n')
cat('Choice:',n_c,'\n')
means <- apply(est_samples[[n_c]], c(1,2), mean)
quantile_025 <- apply(est_samples[[n_c]], c(1,2), quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_samples[[n_c]], c(1,2), quantile, probs = 0.975, type = 3, na.rm = FALSE)
table <- matrix(NA, nrow = nrow(l1_matrix[[i]][[1]]) * nrow(l2_matrix[[j]]), ncol = 5)
for (k1 in 1:nrow(l1_matrix[[i]][[1]])){
temp <- ((k1-1) * nrow(l2_matrix[[j]]) + 1):((k1-1) * nrow(l2_matrix[[j]]) + nrow(l2_matrix[[j]]))
table[temp, 3] <- round(means[k1,], digits = 4)
table[temp, 4] <- pmin(round(quantile_025[k1,], digits = 4), round(quantile_975[k1,], digits = 4))
table[temp, 5] <- pmax(round(quantile_025[k1,], digits = 4), round(quantile_975[k1,], digits = 4))
table[temp, 1] <- rep(attr(l1_matrix[[i]][[1]],'levels')[k1], nrow(l2_matrix[[j]]))
table[temp, 2] <- attr(l2_matrix[[j]],'levels')
}
colnames(table) <- c(attr(X_classes, 'names')[l1_factors[i]], attr(Z_classes, 'names')[l2_factors[j]], 'mean', '2.5%', '97.5%')
rownames(table) <- rep('', nrow(table))
cat('\n')
print(as.table(table))
temp_title <- paste('Choice: ',n_c, sep ="")
sol_tables[['Means for interactions between level 1 and level 2 factors: \n']][[temp_title]] <- as.table(table)
}
}
}
}
}
# means of interactions in level 1 or 2
if (length(l1_interactions) > 0){
cat('\n')
cat('Means for interactions at level 1: \n')
sol_tables[['Means for interactions at level 1: \n']] <- list()
l1_inter_matrix <- list()
index <- 1
for (i in 1:length(l1_interactions)){
temp1 <- l1_values[l1_interactions[[i]]]
if (length(temp1) >= 2){
#temp2 <- list()
#for (j in 1:length(temp1))
#temp2[[j]] <- levels(temp1[[j]])
l1_inter_matrix[[index]] <- multi.effect.matrix.interaction(n_choice, interaction_factors = temp1, assign = X_assign,
l1_interactions[[i]], index_inter_factor = l1_interactions_index[i],
numeric_index_in_X, contrast = contrast)
est_samples <- est.multi(est_matrix, n_sample, l1_inter_matrix[[index]], l2_v)
cat('\nFactor:',attr(X_classes, 'names')[l1_interactions[[i]] - 1],'\n')
for (n_c in 1: n_choice){
cat('\n')
cat('Choice:',n_c,'\n')
means <- apply(est_samples[[n_c]], 1, mean)
quantile_025 <- apply(est_samples[[n_c]], 1, quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_samples[[n_c]], 1, quantile, probs = 0.975, type = 3, na.rm = FALSE)
table <- cbind(attr(l1_inter_matrix[[index]][[1]], 'levels'),
round(means, digits = 4),
pmin(round(quantile_025, digits = 4), round(quantile_975, digits = 4)),
pmax(round(quantile_025, digits = 4), round(quantile_975, digits = 4)))
colnames(table) <- c(attr(X_classes, 'names')[l1_interactions[[i]]], 'mean', '2.5%', '97.5%')
rownames(table) <- rep('', nrow(table))
cat('\n')
print(as.table(table))
temp_title <- paste('Choice: ', n_c, sep ="")
sol_tables[['Means for interactions at level 1: \n']][[temp_title]] <- as.table(table)
}
# print the interaction between this interaction and level 2 factors if there exists
if (length(Z_classes) != 0){
l2_factors <- which(Z_classes == 'factor')
if (length(l2_factors) != 0){
cat('\n')
cat('Means for interactions between level 1 interactions and level 2 factors: \n')
sol_tables[['Means for interactions between level 1 interactions and level 2 factors: \n']] <- list()
for (j in 1:length(l2_factors)){
#means <- l1_inter_matrix[[index]] %*% est_matrix_mean %*% t(l2_matrix[[j]])
#quantile_025 <- l1_inter_matrix[[index]] %*% est_matrix_025 %*% t(l2_matrix[[j]])
#quantile_975 <- l1_inter_matrix[[index]] %*% est_matrix_975 %*% t(l2_matrix[[j]])
est_samples <- est.multi(est_matrix, n_sample, l1_inter_matrix[[index]], l2_matrix[[j]])
cat('\nFactor:',attr(X_classes, 'names')[l1_interactions[[i]]],attr(Z_classes, 'names')[l2_factors[j]],'\n')
for (n_c in 1: n_choice){
cat('\n')
cat('Choice:',n_c,'\n')
means <- apply(est_samples[[n_c]], c(1,2), mean)
quantile_025 <- apply(est_samples[[n_c]], c(1,2), quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_samples[[n_c]], c(1,2), quantile, probs = 0.975, type = 3, na.rm = FALSE)
table <- matrix(NA, nrow = nrow(l1_inter_matrix[[i]][[1]]) * nrow(l2_matrix[[j]]), ncol = 6)
for (k1 in 1:nrow(l1_inter_matrix[[i]][[1]])){
temp <- ((k1-1) * nrow(l2_matrix[[j]]) + 1):((k1-1) * nrow(l2_matrix[[j]]) + nrow(l2_matrix[[j]]))
table[temp, 4] <- round(means[k1,], digits = 4)
table[temp, 5] <- pmin(round(quantile_025[k1,], digits = 4), round(quantile_975[k1,], digits = 4))
table[temp, 6] <- pmax(round(quantile_025[k1,], digits = 4), round(quantile_975[k1,], digits = 4))
table[temp, 1] <- attr(l1_inter_matrix[[i]][[1]],'levels')[k1,][1]
table[temp, 2] <- attr(l1_inter_matrix[[i]][[1]],'levels')[k1,][2]
table[temp, 3] <- attr(l2_matrix[[j]],'levels')
}
colnames(table) <- c(attr(X_classes, 'names')[l1_interactions[[i]] - 1], attr(Z_classes, 'names')[l2_factors[j]], 'mean', '2.5%', '97.5%')
rownames(table) <- rep('', nrow(table))
cat('\n')
print(as.table(table))
temp_title <- paste('Choice: ', n_c, sep ="")
sol_tables[['Means for interactions between level 1 interactions and level 2 factors: \n']][[temp_title]] <- as.table(table)
}
}
}
}
index <- index + 1
}
}
}
if (length(l2_interactions) > 0){
cat('\n')
cat('Means for interactions at level 2: \n')
sol_tables[['Means for interactions at level 2: \n']] <- list()
l2_inter_matrix <- list()
index <- 1
for (i in 1:length(l2_interactions)){
temp1 <- l2_values[l2_interactions[[i]]]
if (length(temp1) >= 2){
#temp2 <- list()
#for (j in 1:length(temp1))
#temp2[[j]] <- levels(temp1[[j]])
l2_inter_matrix[[index]] <- effect.matrix.interaction(interaction_factors = temp1, assign = Z_assign,
l2_interactions[[i]], index_inter_factor = l2_interactions_index[i],
numeric_index_in_Z, contrast = contrast)
est_samples <- est.multi(est_matrix, n_sample, l1_v, l2_inter_matrix[[index]])
cat('\nFactor:',attr(Z_classes, 'names')[l2_interactions[[i]]],'\n')
for (n_c in 1: n_choice){
cat('\n')
cat('Choice:',n_c,'\n')
means <- apply(est_samples[[n_c]], 1, mean)
quantile_025 <- apply(est_samples[[n_c]], 1, quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_samples[[n_c]], 1, quantile, probs = 0.975, type = 3, na.rm = FALSE)
table <- cbind(attr(l2_inter_matrix[[index]], 'levels'),
matrix(round(means, digits = 4), ncol = 1),
matrix(pmin(round(quantile_025, digits = 4), round(quantile_975, digits = 4)), ncol = 1),
matrix(pmax(round(quantile_025, digits = 4), round(quantile_975, digits = 4)), ncol = 1))
colnames(table) <- c(attr(Z_classes, 'names')[l2_interactions[[i]]], 'mean', '2.5%', '97.5%')
rownames(table) <- rep('', nrow(table))
cat('\n')
print(as.table(table))
temp_title <- paste('Choice: ', n_c, sep ="")
sol_tables[['Means for interactions at level 2: \n']][[temp_title]] <- as.table(table)
}
# print the interaction between this interaction and level 1 factors if there exists
if (length(X_classes) != 0){
l1_factors <- which(X_classes == 'factor')
if (length(l1_factors) != 0){
cat('\n')
cat('Means for interactions between level 2 interactions and level 1 factors: \n')
sol_tables[['Means for interactions between level 2 interactions and level 1 factors: \n']] <- list()
for (j in 1:length(l1_factors)){
#means <- l1_matrix[[j]] %*% est_matrix_mean %*% t(l2_inter_matrix[[index]])
#quantile_025 <- l1_matrix[[j]] %*% est_matrix_025 %*% t(l2_inter_matrix[[index]])
#quantile_975 <- l1_matrix[[j]] %*% est_matrix_975 %*% t(l2_inter_matrix[[index]])
est_samples <- est.multi(est_matrix, n_sample, l1_matrix[[j]], l2_inter_matrix[[index]])
cat('\nFactor:',attr(X_classes, 'names')[l1_factors[[j]]],attr(Z_classes, 'names')[l2_interactions[[i]]], '\n')
for (n_c in 1: n_choice){
cat('\n')
cat('Choice:',n_c,'\n')
means <- apply(est_samples[[n_c]], c(1,2), mean)
quantile_025 <- apply(est_samples[[n_c]], c(1,2), quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_samples[[n_c]], c(1,2), quantile, probs = 0.975, type = 3, na.rm = FALSE)
table <- matrix(NA, nrow = nrow(l1_matrix[[j]][[1]]) * nrow(l2_inter_matrix[[index]]), ncol = 6)
for (k1 in 1:nrow(l1_matrix[[j]][[1]])){
temp <- ((k1-1) * nrow(l2_inter_matrix[[index]]) + 1):((k1-1) * nrow(l2_inter_matrix[[index]]) + nrow(l2_inter_matrix[[index]]))
table[temp, 4] <- round(means[k1,], digits = 4)
table[temp, 5] <- pmin(round(quantile_025[k1,], digits = 4), round(quantile_975[k1,], digits = 4))
table[temp, 6] <- pmax(round(quantile_025[k1,], digits = 4), round(quantile_975[k1,], digits = 4))
table[temp, 1] <- attr(l1_matrix[[j]][[1]],'levels')[k1]
table[temp, 2:3] <- attr(l2_inter_matrix[[i]],'levels')
}
colnames(table) <- c(attr(X_classes, 'names')[l1_factors[[j]]], attr(Z_classes, 'names')[l2_interactions[[i]]], 'mean', '2.5%', '97.5%')
rownames(table) <- rep('', nrow(table))
cat('\n')
print(as.table(table))
temp_title <- paste('Choice: ', n_c, sep ="")
sol_tables[['Means for interactions between level 2 interactions and level 1 factors: \n']][[temp_title]] <- as.table(table)
}
}
}
}
index <- index + 1
}
}
}
}
return(sol_tables)
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/multi.print.table.means.R |
pValues <-
function (sample){
n_row <- nrow(sample)
n_col <- ncol(sample)
p_value <- array(NA,n_col)
for (i in 1:n_col){
n_tailp <- length(which(sample[,i] > 0))
n_tailn <- length(which(sample[,i] < 0))
p_value[i] <- round(min(n_tailp,n_tailn) / n_row, digits = 5)
}
return (2 * p_value) # two tailed test
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/pValues.R |
# pairs functions
#' @param x a 'BANOVA' object
#'
#' @return plot pairs graph
#'
#' @examples
#' \dontrun{
#'
#' }
pairs.BANOVA<- function(x, ...){
if(x$model_name %in% c('BANOVA.Normal','BANOVA.T','BANOVA.Bernoulli','BANOVA.Binomial',
'BANOVA.Poisson','BANOVA.ordMultinomial','BANOVA.Multinomial')){
pairs(x$stan_fit, ...)
}else{
stop(x$model_name, " is not supported by BANOVA.pairs!")
}
} | /scratch/gouwar.j/cran-all/cranData/BANOVA/R/pairs.R |
predict.BANOVA.Bernoulli <-
function(object, newdata = NULL, ...){
sol <- predict.means(object$samples_l2_param, object$data, object$dMatrice$X, object$dMatrice$Z_full,
mf1 = object$mf1, mf2 = object$mf2, newdata, model = 'BernNormal', n_trials = object$num_trials)
return(sol)
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/predict.BANOVA.Bern.R |
predict.BANOVA.Binomial <-
function(object, newdata = NULL,...){
sol <- predict.means(object$samples_l2_param, object$data, object$dMatrice$X, object$dMatrice$Z_full,
mf1 = object$mf1, mf2 = object$mf2, newdata, model = 'BernNormal', n_trials = object$num_trials)
return(sol)
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/predict.BANOVA.Bin.R |
predict.BANOVA.Multinomial <-
function(object, Xsamples = NULL, Zsamples = NULL,...){
sol <- multi.predict.means(object$samples_l2_param, object$dataX, object$dataZ, object$dMatrice$X_full, object$dMatrice$X_original_choice, object$dMatrice$Z_full,
mf1 = object$mf1, mf2 = object$mf2, Xsamples, Zsamples)
return(sol)
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/predict.BANOVA.Multinomial.R |
predict.BANOVA.Normal <-
function(object, newdata = NULL,...){
if(object$single_level){
sol <- predict.means(object$samples_l1_param, object$data, object$dMatrice$X, object$dMatrice$Z_full,
mf1 = object$mf1, mf2 = object$mf2, newdata, model = 'NormalNormal')
}else{
sol <- predict.means(object$samples_l2_param, object$data, object$dMatrice$X, object$dMatrice$Z_full,
mf1 = object$mf1, mf2 = object$mf2, newdata, model = 'NormalNormal')
}
return(sol)
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/predict.BANOVA.Normal.R |
predict.BANOVA.Poisson <-
function(object, newdata = NULL,...){
if(object$single_level){
sol <- predict.means(object$samples_l1_param, object$data, object$dMatrice$X, object$dMatrice$Z_full,
mf1 = object$mf1, mf2 = object$mf2, newdata, model = 'PoissonNormal')
}else{
sol <- predict.means(object$samples_l2_param, object$data, object$dMatrice$X, object$dMatrice$Z_full,
mf1 = object$mf1, mf2 = object$mf2, newdata, model = 'PoissonNormal', l2_sd = object$samples_l2_sigma_param)
}
return(sol)
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/predict.BANOVA.Poisson.R |
predict.BANOVA <- function(object, newdata = NULL, Xsamples = NULL, Zsamples = NULL,...){
if(object$single_level){
if (object$model_name %in% c("BANOVA.Normal", "BANOVA.T")){
sol <- predict.means(object$samples_l1_param, object$data, object$dMatrice$X, object$dMatrice$Z_full,
mf1 = object$mf1, mf2 = object$mf2, newdata, model = 'NormalNormal')
}else if(object$model_name == "BANOVA.Poisson"){
sol <- predict.means(object$samples_l1_param, object$data, object$dMatrice$X, object$dMatrice$Z_full,
mf1 = object$mf1, mf2 = object$mf2, newdata, model = 'PoissonNormal')
}else if(object$model_name %in% c("BANOVA.Binomial", "BANOVA.Bernoulli")){
sol <- predict.means(object$samples_l1_param, object$data, object$dMatrice$X, object$dMatrice$Z_full,
mf1 = object$mf1, mf2 = object$mf2, newdata, model = 'BernNormal', n_trials = object$num_trials)
}else if(object$model_name == "BANOVA.ordMultinomial"){
sol <- predict.means(object$samples_l1_param, object$data, object$dMatrice$X, object$dMatrice$Z_full,
mf1 = object$mf1, mf2 = object$mf2, newdata, samples_cutp_param = object$samples_cutp_param, model = 'MultinomialordNormal')
}else if(object$model_name == "BANOVA.Multinomial"){
sol <- multi.predict.means(object$samples_l1_param, object$dataX, object$dataZ, object$dMatrice$X_full, object$dMatrice$X_original_choice, object$dMatrice$Z_full,
mf1 = object$mf1, mf2 = object$mf2, Xsamples, Zsamples)
}
}else{
if (object$model_name %in% c("BANOVA.Normal", "BANOVA.T")){
sol <- predict.means(object$samples_l2_param, object$data, object$dMatrice$X, object$dMatrice$Z_full,
mf1 = object$mf1, mf2 = object$mf2, newdata, model = 'NormalNormal')
}else if(object$model_name == "BANOVA.Poisson"){
sol <- predict.means(object$samples_l2_param, object$data, object$dMatrice$X, object$dMatrice$Z_full,
mf1 = object$mf1, mf2 = object$mf2, newdata, model = 'PoissonNormal', l2_sd = object$samples_l2_sigma_param)
}else if(object$model_name %in% c("BANOVA.Binomial", "BANOVA.Bernoulli")){
sol <- predict.means(object$samples_l2_param, object$data, object$dMatrice$X, object$dMatrice$Z_full,
mf1 = object$mf1, mf2 = object$mf2, newdata, model = 'BernNormal', n_trials = object$num_trials)
}else if(object$model_name == "BANOVA.ordMultinomial"){
sol <- predict.means(object$samples_l2_param, object$data, object$dMatrice$X, object$dMatrice$Z_full,
mf1 = object$mf1, mf2 = object$mf2, newdata, samples_cutp_param = object$samples_cutp_param, model = 'MultinomialordNormal')
}else if(object$model_name == "BANOVA.Multinomial"){
sol <- multi.predict.means(object$samples_l2_param, object$dataX, object$dataZ, object$dMatrice$X_full, object$dMatrice$X_original_choice, object$dMatrice$Z_full,
mf1 = object$mf1, mf2 = object$mf2, Xsamples, Zsamples)
}
}
return(sol)
} | /scratch/gouwar.j/cran-all/cranData/BANOVA/R/predict.BANOVA.R |
predict.BANOVA.T <-
function(object, newdata = NULL,...){
if(object$single_level){
sol <- predict.means(object$samples_l1_param, object$data, object$dMatrice$X, object$dMatrice$Z_full,
mf1 = object$mf1, mf2 = object$mf2, newdata, model = 'NormalNormal')
}else{
sol <- predict.means(object$samples_l2_param, object$data, object$dMatrice$X, object$dMatrice$Z_full,
mf1 = object$mf1, mf2 = object$mf2, newdata, model = 'NormalNormal')
}
return(sol)
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/predict.BANOVA.T.R |
predict.BANOVA.ordMultinomial <-
function(object, newdata = NULL,...){
if(object$single_level){
sol <- predict.means(object$samples_l1_param, object$data, object$dMatrice$X, object$dMatrice$Z_full,
mf1 = object$mf1, mf2 = object$mf2, newdata, samples_cutp_param = object$samples_cutp_param, model = 'MultinomialordNormal')
}else{
sol <- predict.means(object$samples_l2_param, object$data, object$dMatrice$X, object$dMatrice$Z_full,
mf1 = object$mf1, mf2 = object$mf2, newdata, samples_cutp_param = object$samples_cutp_param, model = 'MultinomialordNormal')
}
return(sol)
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/predict.BANOVA.ordMultinomial.R |
predict.means <-
function (samples_l2_param, data, X, Z_full, mf1, mf2 = NULL, samples = NULL, samples_cutp_param = NA, model = NA, l2_sd = NA, n_trials = NULL){
if(is.null(samples)) samples <- data
if (is.vector(samples)) samples <- matrix(samples, nrow = 1)
if (is.vector(X)) X <- matrix(X, ncol = 1)
if (is.vector(Z_full)) X <- matrix(Z_full, ncol = 1)
if (ncol(samples) != ncol(data)) stop("Samples' dimension mismatch!")
n_iter <- nrow(samples_l2_param)
num_l1 <- ncol(X)
if(is.null(mf2) || is.null(Z_full)){
num_l2 <- 1
}else{
num_l2 <- ncol(Z_full)
}
est_matrix <- array(0 , dim = c(num_l1, num_l2, n_iter))
for (i in 1:num_l1){
for (j in 1:n_iter)
est_matrix[i,,j] <- samples_l2_param[j,((i-1)*num_l2+1):((i-1)*num_l2+num_l2)]
}
if (model == 'NormalNormal'){
link_inv <- identity
}else if (model == 'PoissonNormal'){
link_inv <- exp
l2_var <- l2_sd^2
}else if (model == 'BernNormal' || model == 'MultinomialordNormal'){
link_inv <- function(x) return(exp(x)/(exp(x) + 1))
}
l1_names <- attr(mf1, 'names')[-1] # exclude y
if (is.null(mf2)){
l2_names <- c(" ")
}else{
l2_names <- attr(mf2, 'names')
}
l1_index_in_data <- which(colnames(data) %in% l1_names)
l2_index_in_data <- which(colnames(data) %in% l2_names)
# find index of level 1 factors and numeric variables
l1_factor_index_in_data <- array(dim = 0)
l1_numeric_index_in_data <- array(dim = 0)
if (length(l1_index_in_data) > 0){
for (i in 1: length(l1_index_in_data)){
if (inherits(data[1, l1_index_in_data[i]], 'factor'))
l1_factor_index_in_data <- c(l1_factor_index_in_data, l1_index_in_data[i])
if (inherits(data[1, l1_index_in_data[i]], 'integer') || inherits(data[1, l1_index_in_data[i]], 'numeric'))
l1_numeric_index_in_data <- c(l1_numeric_index_in_data, l1_index_in_data[i])
}
}
# find index of level 2 factors and numeric variables
l2_factor_index_in_data <- array(dim = 0)
l2_numeric_index_in_data <- array(dim = 0)
if (length(l2_index_in_data) > 0){
for (i in 1: length(l2_index_in_data)){
if (inherits(data[1, l2_index_in_data[i]], 'factor'))
l2_factor_index_in_data <- c(l2_factor_index_in_data, l2_index_in_data[i])
if (inherits(data[1, l2_index_in_data[i]], 'integer') || inherits(data[1, l2_index_in_data[i]], 'numeric'))
l2_numeric_index_in_data <- c(l2_numeric_index_in_data, l2_index_in_data[i])
}
}
l12_factor_index <- c(l1_factor_index_in_data, l2_factor_index_in_data)
if (model == 'BernNormal'){
y_pred <- matrix(0, nrow = nrow(samples), ncol = 3)
colnames(y_pred) <- c('Median', '2.5%', '97.5%')
est_samples <- matrix(0, nrow = 1, ncol = n_iter)
sample_size = mean(n_trials)
for (n_sample in 1 : nrow(samples)){
l1_vector <- matrix(c(1, rep(0, num_l1-1)), nrow = 1)
l2_vector <- matrix(c(1, rep(0, num_l2-1)), nrow = 1)
if (length(l12_factor_index) > 0){
index_row <- rowMatch(samples[n_sample, l12_factor_index], data[, l12_factor_index])
if (is.na(index_row)) stop('Bad samples provided! Could not find matching factors!')
l1_vector <- X[index_row, ]
if (!is.null(Z_full))
l2_vector <- Z_full[index_row, ]
}
# TODO numeric variables included in prediction +-SD
#if (length(l1_numeric_index_in_data) > 0)
# for (i in 1:length(l1_numeric_index_in_data))
# l1_vector[attr(X, 'numeric_index')[i]] <- samples[n_sample,l1_numeric_index_in_data[i]]
#if (length(l2_numeric_index_in_data) > 0)
# for (i in 1:length(l2_numeric_index_in_data))
# l2_vector[attr(Z_full, 'numeric_index')[i]] <- samples[n_sample,l2_numeric_index_in_data[i]]
if (sum(is.na(l2_sd)) > 0){
for (n_i in 1:n_iter){
if (length(l1_vector) == 1 | length(l2_vector) == 1){
if (length(l1_vector) == 1) temp <- matrix(est_matrix[,,n_i], nrow = 1)
if (length(l2_vector) == 1) temp <- matrix(est_matrix[,,n_i], ncol = 1)
est_samples[n_i] <- matrix(l1_vector, nrow = 1) %*% temp %*% t(matrix(l2_vector, nrow = 1))
}else{
est_samples[n_i] <- matrix(l1_vector, nrow = 1) %*% est_matrix[,,n_i] %*% t(matrix(l2_vector, nrow = 1))
}
}
}else{
for (n_i in 1:n_iter){
if (length(l1_vector) == 1 | length(l2_vector) == 1){
if (length(l1_vector) == 1) temp <- matrix(est_matrix[,,n_i], nrow = 1)
if (length(l2_vector) == 1) temp <- matrix(est_matrix[,,n_i], ncol = 1)
est_samples[n_i] <- matrix(l1_vector, nrow = 1) %*% temp %*% t(matrix(l2_vector, nrow = 1)) + sum(l2_var[n_i,])/2
}else{
est_samples[n_i] <- matrix(l1_vector, nrow = 1) %*% est_matrix[,,n_i] %*% t(matrix(l2_vector, nrow = 1)) + sum(l2_var[n_i,])/2
}
}
}
means <- apply(est_samples, 1, median)
quantile_025 <- apply(est_samples, 1, quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_samples, 1, quantile, probs = 0.975, type = 3, na.rm = FALSE)
y_pred[n_sample, 1:3] <- c(link_inv(means) * sample_size, link_inv(quantile_025) * sample_size, link_inv(quantile_975) * sample_size)
}
y_pred <- round(y_pred, digits = 4)
return(y_pred)
}
if (model != 'MultinomialordNormal' && model != 'BernNormal'){
y_pred <- matrix(0, nrow = nrow(samples), ncol = 3)
colnames(y_pred) <- c('Median', '2.5%', '97.5%')
est_samples <- matrix(0, nrow = 1, ncol = n_iter)
for (n_sample in 1 : nrow(samples)){
l1_vector <- matrix(c(1, rep(0, num_l1-1)), nrow = 1)
l2_vector <- matrix(c(1, rep(0, num_l2-1)), nrow = 1)
if (length(l12_factor_index) > 0){
index_row <- rowMatch(samples[n_sample, l12_factor_index], data[, l12_factor_index])
if (is.na(index_row)) stop('Bad samples provided! Could not find matching factors!')
l1_vector <- X[index_row, ]
if (!is.null(Z_full))
l2_vector <- Z_full[index_row, ]
}
# TODO numeric variables included in prediction
#if (length(l1_numeric_index_in_data) > 0)
# for (i in 1:length(l1_numeric_index_in_data))
# l1_vector[attr(X, 'numeric_index')[i]] <- samples[n_sample,l1_numeric_index_in_data[i]]
#if (length(l2_numeric_index_in_data) > 0)
# for (i in 1:length(l2_numeric_index_in_data))
# l2_vector[attr(Z_full, 'numeric_index')[i]] <- samples[n_sample,l2_numeric_index_in_data[i]]
if (sum(is.na(l2_sd)) > 0){
for (n_i in 1:n_iter){
if (length(l1_vector) == 1 | length(l2_vector) == 1){
if (length(l1_vector) == 1) temp <- matrix(est_matrix[,,n_i], nrow = 1)
if (length(l2_vector) == 1) temp <- matrix(est_matrix[,,n_i], ncol = 1)
est_samples[n_i] <- matrix(l1_vector, nrow = 1) %*% temp %*% t(matrix(l2_vector, nrow = 1))
}else{
est_samples[n_i] <- matrix(l1_vector, nrow = 1) %*% est_matrix[,,n_i] %*% t(matrix(l2_vector, nrow = 1))
}
}
}else{
for (n_i in 1:n_iter){
if (length(l1_vector) == 1 | length(l2_vector) == 1){
if (length(l1_vector) == 1) temp <- matrix(est_matrix[,,n_i], nrow = 1)
if (length(l2_vector) == 1) temp <- matrix(est_matrix[,,n_i], ncol = 1)
est_samples[n_i] <- matrix(l1_vector, nrow = 1) %*% temp %*% t(matrix(l2_vector, nrow = 1)) + sum(l2_var[n_i,])/2
}else{
est_samples[n_i] <- matrix(l1_vector, nrow = 1) %*% est_matrix[,,n_i] %*% t(matrix(l2_vector, nrow = 1)) + sum(l2_var[n_i,])/2
}
}
}
means <- apply(est_samples, 1, median)
quantile_025 <- apply(est_samples, 1, quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_samples, 1, quantile, probs = 0.975, type = 3, na.rm = FALSE)
y_pred[n_sample, 1:3] <- c(link_inv(means), link_inv(quantile_025), link_inv(quantile_975))
}
y_pred <- round(y_pred, digits = 4)
return(y_pred)
}
if (model == 'MultinomialordNormal'){
n.cut <- ncol(samples_cutp_param) + 1
cut_samples <- cbind(0, 0, samples_cutp_param, 0) # the first cut point is 0, the previous is set to be 0 to compute the prob. of Y == 1 (1 - logit^-1), the last 0 is for the prob. Y == K
est_samples <- matrix(0, nrow = 1, ncol = n_iter)
prediction <- matrix(0, nrow = (n.cut+1)*nrow(samples), ncol = 5)
colnames(prediction) <- c('Sample number', 'Response','Median', '2.5%', '97.5%')
temp_index <- 1
for (n_sample in 1 : nrow(samples)){
l1_vector <- matrix(c(1, rep(0, num_l1-1)), nrow = 1)
l2_vector <- matrix(c(1, rep(0, num_l2-1)), nrow = 1)
if (length(l12_factor_index) > 0){
index_row <- rowMatch(samples[n_sample, l12_factor_index], data[, l12_factor_index])
if (is.na(index_row)) stop('Bad samples provided! Could not find matching factors!')
l1_vector <- X[index_row, ]
if (!is.null(Z_full))
l2_vector <- Z_full[index_row, ]
}
# TO numeric variables included in prediction
#if (length(l1_numeric_index_in_data) > 0)
# for (i in 1:length(l1_numeric_index_in_data))
# l1_vector[attr(X, 'numeric_index')[i]] <- samples[n_sample,l1_numeric_index_in_data[i]]
#if (length(l2_numeric_index_in_data) > 0)
# for (i in 1:length(l2_numeric_index_in_data))
# l2_vector[attr(Z_full, 'numeric_index')[i]] <- samples[n_sample,l2_numeric_index_in_data[i]]
for (y in 1:(n.cut + 1)){
for (n_i in 1:n_iter){
if (length(l1_vector) == 1 | length(l2_vector) == 1){
if (length(l1_vector) == 1) temp <- matrix(est_matrix[,,n_i], nrow = 1)
if (length(l2_vector) == 1) temp <- matrix(est_matrix[,,n_i], ncol = 1)
est_samples[n_i] <- est_pred(link_inv, temp, matrix(l1_vector, nrow = 1), matrix(l2_vector, nrow = 1),
cut_samples[n_i,y], cut_samples[n_i,y+1])
}else{
est_samples[n_i] <- est_pred(link_inv, est_matrix[,,n_i], matrix(l1_vector, nrow = 1),
matrix(l2_vector, nrow = 1), cut_samples[n_i,y], cut_samples[n_i,y+1])
}
}
means <- apply(est_samples, 1, median)
quantile_025 <- apply(est_samples, 1, quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_samples, 1, quantile, probs = 0.975, type = 3, na.rm = FALSE)
prediction[temp_index,] <- c(n_sample, y, round(c(means, quantile_025, quantile_975), digits = 4))
temp_index <- temp_index + 1
}
}
return(prediction)
}
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/predict.means.R |
print.BANOVA.Bernoulli <-
function(x, ...){
cat('Call:\n')
print(x$call)
cat('\n Coefficients: \n')
print(data.frame(x$coef.tables$full_table))
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/print.BANOVA.Bern.R |
print.BANOVA.Binomial <-
function(x, ...){
cat('Call:\n')
print(x$call)
cat('\n Coefficients: \n')
print(data.frame(x$coef.tables$full_table))
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/print.BANOVA.Bin.R |
print.BANOVA.Multinomial <-
function(x, ...){
cat('Call:\n')
print(x$call)
cat('\n Coefficients: \n')
print(data.frame(x$coef.tables$full_table))
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/print.BANOVA.Multinomial.R |
print.BANOVA.Normal <-
function(x, ...){
cat('Call:\n')
print(x$call)
cat('\n Coefficients: \n')
print(data.frame(x$coef.tables$full_table))
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/print.BANOVA.Normal.R |
print.BANOVA.Poisson <-
function(x, ...){
cat('Call:\n')
print(x$call)
cat('\n Coefficients: \n')
print(data.frame(x$coef.tables$full_table))
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/print.BANOVA.Poisson.R |
print.BANOVA <- function(x, ...){
cat('Call:\n')
print(x$call)
cat('\n Coefficients: \n')
print(data.frame(x$coef.tables$full_table))
} | /scratch/gouwar.j/cran-all/cranData/BANOVA/R/print.BANOVA.R |
print.BANOVA.T <-
function(x, ...){
cat('Call:\n')
print(x$call)
cat('\n Coefficients: \n')
print(data.frame(x$coef.tables$full_table))
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/print.BANOVA.T.R |
print.BANOVA.floodlight <-
function(x, ...){
floodlight.printing <- function(x){
for(i in 1:length(x$sol)){
flood_table <- x$sol[[i]]
within_range <- array(0, dim = c(nrow(flood_table), ncol(flood_table)))
for (i in 1:nrow(flood_table)){
for (j in ncol(flood_table):(ncol(flood_table)-2)){
if (as.numeric(flood_table[i, j]) > x$num_range[1] & as.numeric(flood_table[i, j]) < x$num_range[2])
within_range[i,j] <- 1
}
}
#x$sol <- format(flood_table, trim = T, nsmall = 4)
for (i in 1:nrow(flood_table)){
for (j in ncol(flood_table):(ncol(flood_table)-2)){
if (within_range[i,j])
flood_table[i, j] <- paste(flood_table[i, j], '*', sep="")
}
}
print(noquote(flood_table))
}
}
if (is.null(x$sol)){
#this is the case for multivariate models
dep_var_names <- names(x)
for (name in dep_var_names){
x_temp <- x[[name]]
title <- paste0("\nFloodlight analysis for ", name,"\n")
cat(title)
floodlight.printing(x_temp)
}
} else{
floodlight.printing(x)
}
} | /scratch/gouwar.j/cran-all/cranData/BANOVA/R/print.BANOVA.floodlight.R |
print.BANOVA.mediation <-
function(x, ...){
if (x$individual){
cat('Indirect effect of', x$xvar,':\n')
for (i in 1:length(x$individual_indirect)){
table_name <- names(x$individual_indirect)[i]
if (!is.null(table_name)){
cat(gsub("_", " ", table_name),'\n')
}
print(noquote(x$individual_indirect[[i]]), row.names = F)
}
}else{
cat('Indirect effect of', x$xvar,':\n')
for (i in 1:length(x$indir_effects)){
table_name <- names(x$indir_effects)[i]
if (!is.null(table_name)){
cat(gsub("_", " ", table_name),'\n')
}
print(noquote(x$indir_effects[[i]]), row.names = F)
cat('effect size: ', x$effect_size[[i]], '\n')
}
}
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/print.BANOVA.mediation.R |
print.BANOVA.multi.mediation <-
function(x, ...){
print.effects <- function(list_with_effects, mediators = NULL, additional_title = NULL,
list_with_effect_sizes = NULL){
print.list.elements <- function(list_with_effects, list_with_effect_sizes){
if (!inherits(list_with_effects, "list")){
temp <- list_with_effects
list_with_effects <- list(temp)
}
for (i in 1:length(list_with_effects)){
print(noquote(list_with_effects[[i]]), row.names = F, right=T)
if (!is.null(list_with_effect_sizes)){
cat("effect size:", list_with_effect_sizes[[i]])
cat("\n")
} else {
cat("\n")
}
}
}
if (!is.null(mediators)){
counter <- 1
for (mediator in mediators){
if (!is.null(additional_title)) cat(additional_title[counter])
print.list.elements(list_with_effects[[mediator]], list_with_effect_sizes[[mediator]])
counter <- counter + 1
}
} else {
if (!is.null(additional_title)) cat(additional_title)
print.list.elements(list_with_effects, list_with_effect_sizes)
}
}
num_dashes <- 100
xvar <- x$xvar
mediators <- x$mediators
num_mediators <- length(mediators)
if (x$individual){
save_options <- getOption("max.print")
options(max.print=nrow(x$individual_indirect[[1]])*(num_mediators+10))
#Report individual indirect effects of the causal variable and effect sizes
cat(paste(strrep("-", num_dashes), '\n'))
cat(paste0("Individual indirect effects of the causal variable", xvar, "on the outcome variables\n"))
print.effects(x$individual_indirect, mediators,
paste(rep("\nIndirect effects of", num_mediators), rep(xvar, num_mediators),
rep("via", num_mediators), mediators, rep("\n", num_mediators), sep = " "))
#Report total individual indirect effects of the causal variable
cat(paste(strrep("-", num_dashes), '\n'))
cat(paste("Total individual indirect effects of the causal variable", xvar,
"on the outcome variables\n\n"))
print.effects(x$total_indir_effects)
options(max.print=save_options)
}else{
#Report direct effects of the causal variable on the outcome
cat(paste(strrep("-", num_dashes), '\n'))
cat(paste("Direct effects of the causal variable", xvar, "on the outcome variable\n\n"))
print.effects(x$dir_effects)
#Report direct effects of the mediator variables on the outcome
mediator_names <- paste(mediators, collapse = " and ")
cat(paste(strrep("-", num_dashes), '\n'))
cat(paste("Direct effects of mediators", mediator_names, "on the outcome variable\n"))
print.effects(x$m1_effects, mediators, paste(rep("\nDirect effects of", num_mediators),
mediators, rep("\n", num_mediators), sep = " "))
#Report direct effects of the causal variable on mediator variables
cat(paste(strrep("-", num_dashes), '\n'))
cat(paste("Direct effects of the causal variable", xvar, "on the mediator variables\n"))
print.effects(x$m2_effects, mediators, paste(rep("\nDirect effects of", num_mediators),
rep(xvar, num_mediators), rep("via", num_mediators),
mediators, rep("\n", num_mediators), sep = " "))
#Report indirect effects of the causal variable and effect sizes
cat(paste(strrep("-", num_dashes), '\n'))
cat(paste0("Indirect effects of the causal variable", xvar, "on the outcome variables\n"))
print.effects(x$indir_effects, mediators, list_with_effect_sizes = x$effect_sizes,
paste(rep("\nIndirect effects of", num_mediators), rep(xvar, num_mediators),
rep("via", num_mediators), mediators, rep("\n", num_mediators), sep = " "))
#Report total indirect effects of the causal variable
cat(paste(strrep("-", num_dashes), '\n'))
cat(paste("Total indirect effects of the causal variable", xvar,
"on the outcome variables\n\n"))
print.effects(x$total_indir_effects)
}
} | /scratch/gouwar.j/cran-all/cranData/BANOVA/R/print.BANOVA.multi.mediation.R |
print.BANOVA.ordMultinomial <-
function(x, ...){
cat('Call:\n')
print(x$call)
cat('\n Coefficients: \n')
#print(x$coef.tables$full_table)
#print(x$coef.tables$cutp_table)
print(data.frame(rbind(x$coef.tables$full_table, x$coef.tables$cutp_table)))
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/print.BANOVA.ordMultinomial.R |
print.ancova.effect <-
function(x, ...){
cat("\nTable of sum of squares:\n")
print(x$ancova_table)
cat("\n")
cat("Table of effect sizes (95% credible interval):\n")
print(x$effect_table)
} | /scratch/gouwar.j/cran-all/cranData/BANOVA/R/print.ancova.effect.R |
print.conv.diag <-
function(x, ...){
cat("Geweke Diag. & Heidelberger and Welch's Diag.\n")
#print(x$sol_geweke)
#cat("Heidelberger and Welch's Diag.\n")
#print(x$sol_heidel)
print(format(cbind(x$sol_geweke, x$sol_heidel), nsmall = 4))
if(x$pass_ind){
cat('\n')
cat("The Chain has converged.\n")
}else{
warning("The Chain may not have converged. Consider a longer burn-in/warmup, speeding up the convergence by setting conv_speedup = T, or modification of the model.\n", call. = F, immediate. = T)
}
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/print.conv.diag.R |
print.summary.BANOVA.Bernoulli <-
function(x, ...){
cat('Call:\n')
print(x$call)
cat('\nConvergence diagnostics:\n')
print(x$conv)
print(x$anova.table)
cat('\nTable of p-values (Multidimensional): \n')
print(x$pvalue.table)
cat('\nTable of coefficients: \n')
printCoefmat(x$coef.table)
cat('\nTable of predictions: \n')
table.predictions(x$full_object)
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/print.summary.BANOVA.Bern.R |
print.summary.BANOVA.Binomial <-
function(x, ...){
cat('Call:\n')
print(x$call)
cat('\nConvergence diagnostics:\n')
print(x$conv)
print(x$anova.table)
cat('\nTable of p-values (Multidimensional): \n')
print(x$pvalue.table)
cat('\nTable of coefficients: \n')
printCoefmat(x$coef.table)
cat('\nTable of predictions: \n')
table.predictions(x$full_object)
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/print.summary.BANOVA.Bin.R |
print.summary.BANOVA.Multinomial <-
function(x, ...){
cat('Call:\n')
print(x$call)
cat('\nConvergence diagnostics:\n')
print(x$conv)
print(x$anova.table)
cat('\nTable of p-values (Multidimensional): \n')
print(x$pvalue.table)
cat('\nTable of coefficients: \n')
printCoefmat(x$coef.table)
cat('\nTable of predictions: \n')
table.predictions(x$full_object)
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/print.summary.BANOVA.Multinomial.R |
print.summary.BANOVA.Normal <-
function(x, ...){
cat('Call:\n')
print(x$call)
cat('\nConvergence diagnostics:\n')
print(x$conv)
print(x$anova.table)
cat('\nTable of p-values (Multidimensional): \n')
print(x$pvalue.table)
cat('\nTable of coefficients: \n')
printCoefmat(x$coef.table)
cat('\nTable of predictions: \n')
table.predictions(x$full_object)
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/print.summary.BANOVA.Normal.R |
print.summary.BANOVA.Poisson <-
function(x, ...){
cat('Call:\n')
print(x$call)
cat('\nConvergence diagnostics:\n')
print(x$conv)
print(x$anova.table)
cat('\nTable of p-values (Multidimensional): \n')
print(x$pvalue.table)
cat('\nTable of coefficients: \n')
printCoefmat(x$coef.table)
cat('\nTable of predictions: \n')
table.predictions(x$full_object)
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/print.summary.BANOVA.Poisson.R |
print.summary.BANOVA <- function(x, ...){
cat('Call:\n')
print(x$call)
cat('\nConvergence diagnostics:\n')
print(x$conv)
cat('\nTable of sum of squares & effect sizes:\n')
if (length(x$anova.table) >2){
for (i in 1:length(x$anova.table)){
cat('\nChoice: ', i, '\n')
print(x$anova.table[[i]])
}
}else{
print(x$anova.table)
}
cat('\nTable of p-values (Multidimensional): \n')
print(x$pvalue.table)
cat('\nTable of coefficients: \n')
printCoefmat(x$coef.table)
if (!is.null(x$R2)){
cat('\nMultiple R-squared: ', x$R2, '\n')
}
if (x$model_name == "BANOVA.multiNormal"){
cat('\nCorrelation matrix: \n')
print(x$full_object$correlation.matrix)
print(x$full_object$test.residual.correlation)
cat('\nStandard deviations of dependent variables: \n')
print(x$full_object$test.standard.deviations.of.dep.var)
}
if (!((x$model_name == "BANOVA.Multinomial")&&(x$single_level))){
cat('\nTable of predictions: \n')
table.predictions(x$full_object)
}
} | /scratch/gouwar.j/cran-all/cranData/BANOVA/R/print.summary.BANOVA.R |
print.summary.BANOVA.T <-
function(x, ...){
cat('Call:\n')
print(x$call)
cat('\nConvergence diagnostics:\n')
print(x$conv)
print(x$anova.table)
cat('\nTable of p-values (Multidimensional): \n')
print(x$pvalue.table)
cat('\nTable of coefficients: \n')
printCoefmat(x$coef.table)
cat('\nTable of predictions: \n')
table.predictions(x$full_object)
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/print.summary.BANOVA.T.R |
print.summary.BANOVA.ordMultinomial <-
function(x, ...){
cat('Call:\n')
print(x$call)
cat('\nConvergence diagnostics:\n')
print(x$conv)
print(x$anova.table)
cat('\nTable of p-values (Multidimensional): \n')
print(x$pvalue.table)
cat('\nTable of coefficients: \n')
printCoefmat(x$coef.table)
cat('\nTable of predictions: \n')
table.predictions(x$full_object)
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/print.summary.BANOVA.ordMultinomial.R |
print.table.means <-
function (coeff_table, samples_l2_param, X_names, X_assign = array(dim = 0), X_classes = character(0), Z_names, Z_assign = array(dim = 0), Z_classes = character(0),
l1_values = list(), l1_interactions = list(), l1_interactions_index = array(dim = 0),
l2_values = list(), l2_interactions = list(), l2_interactions_index = array(dim = 0),
numeric_index_in_X,
numeric_index_in_Z,
samples_cutp_param = NA,
model = NA,
l2_sd = NULL,
n_trials = NULL,
contrast = NULL){
sol_tables <- list()
if (length(X_assign) == 1 && length(Z_assign) == 1) coeff_table <- matrix(coeff_table, nrow = 1) # the case that there is only one intercept
n_sample <- nrow(samples_l2_param)
# convert the coeff_table to three matrices, mean, 2.5% and 97.5%, used in the table of means computation
num_l1 <- length(X_assign)
num_l2 <- length(Z_assign)
est_matrix <- array(0 , dim = c(num_l1, num_l2, n_sample), dimnames = list(X_names, Z_names, NULL))
for (i in 1:num_l1){
for (j in 1:n_sample)
est_matrix[i,,j] <- samples_l2_param[j,((i-1)*num_l2+1):((i-1)*num_l2+num_l2)]
}
l2_var <- array(0, dim = c(n_sample, length(X_names)))
colnames(l2_var) <- X_names
if (model == 'BernNormal'){
# sample_size * probability
link_inv <- function(x) return(exp(x)/(exp(x) + 1))
p_indicator <- 0
sample_size = mean(n_trials)
if (sample_size < 0) stop('The average sample size is less than zero!')
# Grand mean
cat('\n')
cat('Grand mean: \n')
# TOFIX: 'beta2_1_1' is hard coded here
if ('beta2_1_1' %in% colnames(samples_l2_param)){
cat(round(link_inv(mean(samples_l2_param[, 'beta2_1_1'] + p_indicator*rowSums(l2_var)/2))*sample_size, digits = 4))
cat('\n')
#sol_tables[['Grand mean: \n']] <- as.table(link_inv(matrix(coeff_table[1,2:3] + mean(rowSums(l2_var))/2, nrow = 1, ncol = 2, dimnames = list('',c('2.5%','97.5%')))))
sol_tables[['Grand mean: \n']] <- as.table(round(link_inv(matrix(quantile(samples_l2_param[, 'beta2_1_1'] + p_indicator * rowSums(l2_var)/2, c(0.025, 0.975)), nrow = 1, ncol = 2, dimnames = list('',c('2.5%','97.5%'))))*sample_size, digits = 4))
}else if('beta1_1' %in% colnames(samples_l2_param)){
cat(round(link_inv(mean(samples_l2_param[, 'beta1_1'] + p_indicator*rowSums(l2_var)/2))*sample_size, digits = 4))
cat('\n')
#sol_tables[['Grand mean: \n']] <- as.table(link_inv(matrix(coeff_table[1,2:3] + mean(rowSums(l2_var))/2, nrow = 1, ncol = 2, dimnames = list('',c('2.5%','97.5%')))))
sol_tables[['Grand mean: \n']] <- as.table(round(link_inv(matrix(quantile(samples_l2_param[, 'beta1_1'] + p_indicator * rowSums(l2_var)/2, c(0.025, 0.975)), nrow = 1, ncol = 2, dimnames = list('',c('2.5%','97.5%'))))*sample_size, digits = 4))
}else{
cat(round(link_inv(mean(samples_l2_param[, 'beta1'] + p_indicator*rowSums(l2_var)/2))*sample_size, digits = 4))
cat('\n')
#sol_tables[['Grand mean: \n']] <- as.table(link_inv(matrix(coeff_table[1,2:3] + mean(rowSums(l2_var))/2, nrow = 1, ncol = 2, dimnames = list('',c('2.5%','97.5%')))))
sol_tables[['Grand mean: \n']] <- as.table(round(link_inv(matrix(quantile(samples_l2_param[, 'beta1'] + p_indicator * rowSums(l2_var)/2, c(0.025, 0.975)), nrow = 1, ncol = 2, dimnames = list('',c('2.5%','97.5%'))))*sample_size, digits = 4))
}
print(sol_tables[['Grand mean: \n']])
# means of main effect in level 1 and 2
if (length(X_classes) != 0){
l1_factors <- which(X_classes == 'factor')
if (length(l1_factors) != 0){
cat('\n')
#cat('Means for factors at level 1: \n')
l1_matrix <- list()
l2_v <- matrix(c(1, rep(0, num_l2 - 1)), nrow = 1) # only look at the intercept in level 2
for (i in 1:length(l1_factors)){
# l1_values also include y values
l1_matrix[[i]] <- effect.matrix.factor(l1_values[[l1_factors[i]+1]], X_assign, l1_factors[i], numeric_index_in_X, contrast = contrast)
#means <- l1_matrix[[i]] %*% est_matrix_mean %*% l2_v
#quantile_025 <- l1_matrix[[i]] %*% est_matrix_025 %*% l2_v
#quantile_975 <- l1_matrix[[i]] %*% est_matrix_975 %*% l2_v
# Compute median and quantile
est_samples <- matrix(0, nrow = nrow(l1_matrix[[i]]), ncol = n_sample)
for (n_s in 1:n_sample)
est_samples[ ,n_s] <- l1_matrix[[i]] %*% est_matrix[colnames(l1_matrix[[i]]), ,n_s] %*% t(l2_v) + p_indicator * sum(l2_var[n_s,])/2 #sum(l2_var[n_s,c(1,i)])/2
means <- apply(est_samples, 1, mean)
quantile_025 <- apply(est_samples, 1, quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_samples, 1, quantile, probs = 0.975, type = 3, na.rm = FALSE)
table <- matrix(NA, nrow = length(means), ncol = 4)
table[, 2] <- means
table[, 3] <- pmin(quantile_025, quantile_975)
table[, 4] <- pmax(quantile_025, quantile_975)
table <- round(link_inv(table)*sample_size, digits = 4)
table[, 1] <- attr(l1_matrix[[i]],'levels')
colnames(table) <- c(attr(X_classes, 'names')[l1_factors[i]], 'mean', '2.5%', '97.5%')
rownames(table) <- rep('', nrow(table))
cat('\n')
print(as.table(table))
sol_tables[['Means for factors at level 1: \n']] <- as.table(table)
}
}
}
if (length(Z_classes) != 0){
l2_factors <- which(Z_classes == 'factor')
if (length(l2_factors) != 0){
cat('\n')
#cat('Means for factors at level 2: \n')
l2_matrix <- list()
l1_v <- matrix(c(1, rep(0, num_l1 - 1)), nrow = 1) # only look at the intercept in level 1
for (i in 1:length(l2_factors)){
l2_matrix[[i]] <- effect.matrix.factor(l2_values[[l2_factors[i]]], Z_assign, l2_factors[i], numeric_index_in_Z, contrast = contrast)
#means <- l1_v %*% est_matrix_mean %*% t(l2_matrix[[i]])
#quantile_025 <- l1_v %*% est_matrix_025 %*% t(l2_matrix[[i]])
#quantile_975 <- l1_v %*% est_matrix_975 %*% t(l2_matrix[[i]])
est_samples <- matrix(0, nrow = nrow(l2_matrix[[i]]), ncol = n_sample)
for (n_s in 1:n_sample)
est_samples[ , n_s] <- l1_v %*% est_matrix[, colnames(l2_matrix[[i]]), n_s] %*% t(l2_matrix[[i]]) + p_indicator * sum(l2_var[n_s,])/2 #l2_var[n_s, 1]/2
means <- apply(est_samples, 1, mean)
quantile_025 <- apply(est_samples, 1, quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_samples, 1, quantile, probs = 0.975, type = 3, na.rm = FALSE)
table <- matrix(NA, nrow = length(means), ncol = 4)
table[, 2] <- means
table[, 3] <- pmin(quantile_025, quantile_975)
table[, 4] <- pmax(quantile_025, quantile_975)
table <- round(link_inv(table)*sample_size, digits = 4)
table[, 1] <- attr(l2_matrix[[i]],'levels')
colnames(table) <- c(attr(Z_classes, 'names')[l2_factors[i]], 'mean', '2.5%', '97.5%')
rownames(table) <- rep('', nrow(table))
cat('\n')
print(as.table(table))
sol_tables[['Means for factors at level 2: \n']] <- as.table(table)
}
}
}
# means of interactions between level 1 and 2
if (length(X_classes) != 0 && length(Z_classes) != 0){
if (length(l1_factors) != 0 && length(l2_factors) != 0){
cat('\n')
#cat('Means for interactions between level 1 and level 2 factors: \n')
for (i in 1:length(l1_factors)){
for (j in 1:length(l2_factors)){
#means <- l1_matrix[[i]] %*% est_matrix_mean %*% t(l2_matrix[[j]])
#quantile_025 <- l1_matrix[[i]] %*% est_matrix_025 %*% t(l2_matrix[[j]])
#quantile_975 <- l1_matrix[[i]] %*% est_matrix_975 %*% t(l2_matrix[[j]])
est_samples <- array(0, dim = c(nrow(l1_matrix[[i]]), nrow(l2_matrix[[j]]), n_sample))
for (n_s in 1:n_sample)
est_samples[ , , n_s] <- l1_matrix[[i]] %*% est_matrix[colnames(l1_matrix[[i]]), colnames(l2_matrix[[j]]), n_s] %*% t(l2_matrix[[j]]) + p_indicator * sum(l2_var[n_s,])/2 #sum(l2_var[n_s, c(1,i)])/2
means <- apply(est_samples, c(1,2), mean)
quantile_025 <- apply(est_samples, c(1,2), quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_samples, c(1,2), quantile, probs = 0.975, type = 3, na.rm = FALSE)
table <- matrix(NA, nrow = nrow(l1_matrix[[i]]) * nrow(l2_matrix[[j]]), ncol = 5)
for (k1 in 1:nrow(l1_matrix[[i]])){
temp <- ((k1-1) * nrow(l2_matrix[[j]]) + 1):((k1-1) * nrow(l2_matrix[[j]]) + nrow(l2_matrix[[j]]))
table[temp, 3] <- round(link_inv(means[k1,])*sample_size, digits = 4)
table[temp, 4] <- pmin(round(link_inv(quantile_025[k1,])*sample_size, digits = 4), round(link_inv(quantile_975[k1,])*sample_size, digits = 4))
table[temp, 5] <- pmax(round(link_inv(quantile_025[k1,])*sample_size, digits = 4), round(link_inv(quantile_975[k1,])*sample_size, digits = 4))
table[temp, 1] <- rep(attr(l1_matrix[[i]],'levels')[k1], nrow(l2_matrix[[j]]))
table[temp, 2] <- attr(l2_matrix[[j]],'levels')
}
colnames(table) <- c(attr(X_classes, 'names')[l1_factors[i]], attr(Z_classes, 'names')[l2_factors[j]], 'mean', '2.5%', '97.5%')
rownames(table) <- rep('', nrow(table))
cat('\n')
print(as.table(table))
sol_tables[['Means for interactions between level 1 and level 2 factors: \n']] <- as.table(table)
}
}
}
}
# means of interactions in level 1 or 2
if (length(l1_interactions) > 0){
cat('\n')
#cat('Means for interactions at level 1: \n')
l1_inter_matrix <- list()
index <- 1
for (i in 1:length(l1_interactions)){
# y var is also included in l1_values, l1_interactions has considered this
temp1 <- l1_values[l1_interactions[[i]]]
if (length(temp1) >= 2){
#temp2 <- list()
#for (j in 1:length(temp1))
#temp2[[j]] <- levels(temp1[[j]])
l1_inter_matrix[[index]] <- effect.matrix.interaction(interaction_factors = temp1, assign = X_assign,
l1_interactions[[i]] - 1, index_inter_factor = l1_interactions_index[i],
numeric_index_in_X, contrast = contrast) #'-1' exclude the 'y'
est_samples <- matrix(0, nrow = nrow(l1_inter_matrix[[index]]), ncol = n_sample)
for (n_s in 1:n_sample)
est_samples[ ,n_s] <- l1_inter_matrix[[index]] %*% est_matrix[colnames(l1_inter_matrix[[index]]),,n_s] %*% t(l2_v) + p_indicator * sum(l2_var[n_s,])/2 #sum(l2_var[n_s,c('(Intercept)',colnames(l1_inter_matrix[[index]]))])/2
means <- apply(est_samples, 1, mean)
quantile_025 <- apply(est_samples, 1, quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_samples, 1, quantile, probs = 0.975, type = 3, na.rm = FALSE)
table <- cbind(attr(l1_inter_matrix[[index]], 'levels'),
round(link_inv(means)*sample_size, digits = 4),
pmin(round(link_inv(quantile_025)*sample_size, digits = 4), round(link_inv(quantile_975)*sample_size, digits = 4)),
pmax(round(link_inv(quantile_025)*sample_size, digits = 4), round(link_inv(quantile_975)*sample_size, digits = 4)))
colnames(table) <- c(attr(X_classes, 'names')[l1_interactions[[i]] - 1], 'mean', '2.5%', '97.5%') #'-1' is used, since 'y' is considered in interaction index
rownames(table) <- rep('', nrow(table))
cat('\n')
print(as.table(table))
sol_tables[['Means for interactions at level 1: \n']] <- as.table(table)
# print the interaction between this interaction and level 2 factors if there exists
if (length(Z_classes) != 0){
l2_factors <- which(Z_classes == 'factor')
if (length(l2_factors) != 0){
cat('\n')
#cat('Means for interactions between level 1 interactions and level 2 factors: \n')
for (j in 1:length(l2_factors)){
#means <- l1_inter_matrix[[index]] %*% est_matrix_mean %*% t(l2_matrix[[j]])
#quantile_025 <- l1_inter_matrix[[index]] %*% est_matrix_025 %*% t(l2_matrix[[j]])
#quantile_975 <- l1_inter_matrix[[index]] %*% est_matrix_975 %*% t(l2_matrix[[j]])
est_samples <- array(0, dim = c(nrow(l1_inter_matrix[[index]]), nrow(l2_matrix[[j]]), n_sample))
for (n_s in 1:n_sample)
est_samples[ , , n_s] <- l1_inter_matrix[[index]] %*% est_matrix[colnames(l1_inter_matrix[[index]]), colnames(l2_matrix[[j]]), n_s] %*% t(l2_matrix[[j]]) + p_indicator * sum(l2_var[n_s,])/2 #sum(l2_var[n_s,c('(Intercept)',colnames(l1_inter_matrix[[index]]))])/2
means <- apply(est_samples, c(1,2), mean)
quantile_025 <- apply(est_samples, c(1,2), quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_samples, c(1,2), quantile, probs = 0.975, type = 3, na.rm = FALSE)
table <- matrix(NA, nrow = nrow(l1_inter_matrix[[i]]) * nrow(l2_matrix[[j]]), ncol = 6)
for (k1 in 1:nrow(l1_inter_matrix[[i]])){
temp <- ((k1-1) * nrow(l2_matrix[[j]]) + 1):((k1-1) * nrow(l2_matrix[[j]]) + nrow(l2_matrix[[j]]))
table[temp, 4] <- round(link_inv(means[k1,])*sample_size, digits = 4)
table[temp, 5] <- pmin(round(link_inv(quantile_025[k1,])*sample_size, digits = 4), round(link_inv(quantile_975[k1,])*sample_size, digits = 4))
table[temp, 6] <- pmax(round(link_inv(quantile_025[k1,])*sample_size, digits = 4), round(link_inv(quantile_975[k1,])*sample_size, digits = 4))
table[temp, 1] <- attr(l1_inter_matrix[[i]],'levels')[k1,][1]
table[temp, 2] <- attr(l1_inter_matrix[[i]],'levels')[k1,][2]
table[temp, 3] <- attr(l2_matrix[[j]],'levels')
}
colnames(table) <- c(attr(X_classes, 'names')[l1_interactions[[i]] - 1], attr(Z_classes, 'names')[l2_factors[j]], 'mean', '2.5%', '97.5%')
rownames(table) <- rep('', nrow(table))
cat('\n')
print(as.table(table))
sol_tables[['Means for interactions between level 1 interactions and level 2 factors: \n']] <- as.table(table)
}
}
}
index <- index + 1
}
}
}
if (length(l2_interactions) > 0){
cat('\n')
#cat('Means for interactions at level 2: \n')
l2_inter_matrix <- list()
index <- 1
for (i in 1:length(l2_interactions)){
temp1 <- l2_values[l2_interactions[[i]]]
if (length(temp1) >= 2){
#temp2 <- list()
#for (j in 1:length(temp1))
#temp2[[j]] <- levels(temp1[[j]])
l2_inter_matrix[[index]] <- effect.matrix.interaction(interaction_factors = temp1, assign = Z_assign,
l2_interactions[[i]], index_inter_factor = l2_interactions_index[i],
numeric_index_in_Z, contrast = contrast)
#means <- l1_v %*% est_matrix_mean %*% t(l2_inter_matrix[[index]])
#quantile_025 <- l1_v %*% est_matrix_025 %*% t(l2_inter_matrix[[index]])
#quantile_975 <- l1_v %*% est_matrix_975 %*% t(l2_inter_matrix[[index]])
est_samples <- matrix(0, nrow = nrow(l2_inter_matrix[[index]]), ncol = n_sample)
#print('debug')
#print(l2_inter_matrix[[index]])
for (n_s in 1:n_sample)
est_samples[ ,n_s] <- l1_v %*% est_matrix[, colnames(l2_inter_matrix[[index]]), n_s] %*% t(l2_inter_matrix[[index]]) + p_indicator * sum(l2_var[n_s,])/2 #l2_var[n_s,c('(Intercept)')]/2
means <- apply(est_samples, 1, mean)
quantile_025 <- apply(est_samples, 1, quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_samples, 1, quantile, probs = 0.975, type = 3, na.rm = FALSE)
table <- cbind(attr(l2_inter_matrix[[index]], 'levels'),
matrix(round(link_inv(means)*sample_size, digits = 4), ncol = 1),
matrix(pmin(round(link_inv(quantile_025)*sample_size, digits = 4), round(link_inv(quantile_975)*sample_size, digits = 4)), ncol = 1),
matrix(pmax(round(link_inv(quantile_025)*sample_size, digits = 4), round(link_inv(quantile_975)*sample_size, digits = 4)), ncol = 1))
colnames(table) <- c(attr(Z_classes, 'names')[l2_interactions[[i]]], 'mean', '2.5%', '97.5%')
rownames(table) <- rep('', nrow(table))
cat('\n')
print(as.table(table))
sol_tables[['Means for interactions at level 2: \n']] <- as.table(table)
# print the interaction between this interaction and level 1 factors if there exists
if (length(X_classes) != 0){
l1_factors <- which(X_classes == 'factor')
if (length(l1_factors) != 0){
cat('\n')
#cat('Means for interactions between level 2 interactions and level 1 factors: \n')
for (j in 1:length(l1_factors)){
#means <- l1_matrix[[j]] %*% est_matrix_mean %*% t(l2_inter_matrix[[index]])
#quantile_025 <- l1_matrix[[j]] %*% est_matrix_025 %*% t(l2_inter_matrix[[index]])
#quantile_975 <- l1_matrix[[j]] %*% est_matrix_975 %*% t(l2_inter_matrix[[index]])
est_samples <- array(0, dim = c(nrow(l1_matrix[[j]]), nrow(l2_inter_matrix[[index]]), n_sample))
for (n_s in 1:n_sample)
est_samples[,, n_s] <- l1_matrix[[j]] %*% est_matrix[colnames(l1_matrix[[j]]), colnames(l2_inter_matrix[[index]]), n_s] %*% t(l2_inter_matrix[[index]]) + p_indicator * sum(l2_var[n_s,])/2 #sum(l2_var[n_s,c('(Intercept)',colnames(colnames(l1_matrix[[j]])))])/2
means <- apply(est_samples, c(1,2), mean)
quantile_025 <- apply(est_samples, c(1,2), quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_samples, c(1,2), quantile, probs = 0.975, type = 3, na.rm = FALSE)
table <- matrix(NA, nrow = nrow(l1_matrix[[j]]) * nrow(l2_inter_matrix[[index]]), ncol = 6)
for (k1 in 1:nrow(l1_matrix[[j]])){
temp <- ((k1-1) * nrow(l2_inter_matrix[[index]]) + 1):((k1-1) * nrow(l2_inter_matrix[[index]]) + nrow(l2_inter_matrix[[index]]))
table[temp, 4] <- round(link_inv(means[k1,])*sample_size, digits = 4)
table[temp, 5] <- pmin(round(link_inv(quantile_025[k1,])*sample_size, digits = 4), round(link_inv(quantile_975[k1,])*sample_size, digits = 4))
table[temp, 6] <- pmax(round(link_inv(quantile_025[k1,])*sample_size, digits = 4), round(link_inv(quantile_975[k1,])*sample_size, digits = 4))
table[temp, 1] <- attr(l1_matrix[[j]],'levels')[k1]
table[temp, 2:3] <- attr(l2_inter_matrix[[i]],'levels')
}
colnames(table) <- c(attr(X_classes, 'names')[l1_factors[[j]]], attr(Z_classes, 'names')[l2_interactions[[i]]], 'mean', '2.5%', '97.5%')
rownames(table) <- rep('', nrow(table))
cat('\n')
print(as.table(table))
sol_tables[['Means for interactions between level 2 interactions and level 1 factors: \n']] <- as.table(table)
}
}
}
index <- index + 1
}
}
}
}
if (model != 'MultinomialordNormal' && model != 'BernNormal'){
if (model == 'NormalNormal'){
link_inv <- identity
p_indicator <- 0 # for Poisson
}else if (model == 'PoissonNormal'){
link_inv <- exp
p_indicator <- 1
if (!is.null(l2_sd)){
l2_var <- l2_sd^2
colnames(l2_var) <- X_names
}
}else if (model == 'BernNormal'){
link_inv <- function(x) return(exp(x)/(exp(x) + 1))
p_indicator <- 0
}
# Grand mean
cat('\n')
cat('Grand mean: \n')
# TOFIX: 'beta2_1_1' is hard coded here
if ('beta2_1_1' %in% colnames(samples_l2_param)){
cat(round(link_inv(mean(samples_l2_param[, 'beta2_1_1'] + p_indicator*rowSums(l2_var)/2)), digits = 4))
cat('\n')
#sol_tables[['Grand mean: \n']] <- as.table(link_inv(matrix(coeff_table[1,2:3] + mean(rowSums(l2_var))/2, nrow = 1, ncol = 2, dimnames = list('',c('2.5%','97.5%')))))
sol_tables[['Grand mean: \n']] <- as.table(round(link_inv(matrix(quantile(samples_l2_param[, 'beta2_1_1'] + p_indicator * rowSums(l2_var)/2, c(0.025, 0.975)), nrow = 1, ncol = 2, dimnames = list('',c('2.5%','97.5%')))), digits = 4))
}else if('beta1_1' %in% colnames(samples_l2_param)){
cat(round(link_inv(mean(samples_l2_param[, 'beta1_1'] + p_indicator*rowSums(l2_var)/2)), digits = 4))
cat('\n')
#sol_tables[['Grand mean: \n']] <- as.table(link_inv(matrix(coeff_table[1,2:3] + mean(rowSums(l2_var))/2, nrow = 1, ncol = 2, dimnames = list('',c('2.5%','97.5%')))))
sol_tables[['Grand mean: \n']] <- as.table(round(link_inv(matrix(quantile(samples_l2_param[, 'beta1_1'] + p_indicator * rowSums(l2_var)/2, c(0.025, 0.975)), nrow = 1, ncol = 2, dimnames = list('',c('2.5%','97.5%')))), digits = 4))
}else{
cat(round(link_inv(mean(samples_l2_param[, 'beta1'] + p_indicator*rowSums(l2_var)/2)), digits = 4))
cat('\n')
#sol_tables[['Grand mean: \n']] <- as.table(link_inv(matrix(coeff_table[1,2:3] + mean(rowSums(l2_var))/2, nrow = 1, ncol = 2, dimnames = list('',c('2.5%','97.5%')))))
sol_tables[['Grand mean: \n']] <- as.table(round(link_inv(matrix(quantile(samples_l2_param[, 'beta1'] + p_indicator * rowSums(l2_var)/2, c(0.025, 0.975)), nrow = 1, ncol = 2, dimnames = list('',c('2.5%','97.5%')))), digits = 4))
}
print(sol_tables[['Grand mean: \n']])
# means of main effect in level 1 and 2
if (length(X_classes) != 0){
l1_factors <- which(X_classes == 'factor')
if (length(l1_factors) != 0){
cat('\n')
#cat('Means for factors at level 1: \n')
l1_matrix <- list()
l2_v <- matrix(c(1, rep(0, num_l2 - 1)), nrow = 1) # only look at the intercept in level 2
for (i in 1:length(l1_factors)){
# l1_values also include y values
l1_matrix[[i]] <- effect.matrix.factor(l1_values[[l1_factors[i]+1]], X_assign, l1_factors[i], numeric_index_in_X, contrast = contrast)
#means <- l1_matrix[[i]] %*% est_matrix_mean %*% l2_v
#quantile_025 <- l1_matrix[[i]] %*% est_matrix_025 %*% l2_v
#quantile_975 <- l1_matrix[[i]] %*% est_matrix_975 %*% l2_v
# Compute median and quantile
est_samples <- matrix(0, nrow = nrow(l1_matrix[[i]]), ncol = n_sample)
for (n_s in 1:n_sample)
est_samples[ ,n_s] <- l1_matrix[[i]] %*% est_matrix[colnames(l1_matrix[[i]]), ,n_s] %*% t(l2_v) + p_indicator * sum(l2_var[n_s,])/2 #sum(l2_var[n_s,c(1,i)])/2
means <- apply(est_samples, 1, mean)
quantile_025 <- apply(est_samples, 1, quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_samples, 1, quantile, probs = 0.975, type = 3, na.rm = FALSE)
table <- matrix(NA, nrow = length(means), ncol = 4)
table[, 2] <- means
table[, 3] <- pmin(quantile_025, quantile_975)
table[, 4] <- pmax(quantile_025, quantile_975)
table <- round(link_inv(table), digits = 4)
table[, 1] <- attr(l1_matrix[[i]],'levels')
colnames(table) <- c(attr(X_classes, 'names')[l1_factors[i]], 'mean', '2.5%', '97.5%')
rownames(table) <- rep('', nrow(table))
cat('\n')
print(as.table(table))
sol_tables[['Means for factors at level 1: \n']] <- as.table(table)
}
}
}
if (length(Z_classes) != 0){
l2_factors <- which(Z_classes == 'factor')
if (length(l2_factors) != 0){
cat('\n')
#cat('Means for factors at level 2: \n')
l2_matrix <- list()
l1_v <- matrix(c(1, rep(0, num_l1 - 1)), nrow = 1) # only look at the intercept in level 1
for (i in 1:length(l2_factors)){
l2_matrix[[i]] <- effect.matrix.factor(l2_values[[l2_factors[i]]], Z_assign, l2_factors[i], numeric_index_in_Z, contrast = contrast)
#means <- l1_v %*% est_matrix_mean %*% t(l2_matrix[[i]])
#quantile_025 <- l1_v %*% est_matrix_025 %*% t(l2_matrix[[i]])
#quantile_975 <- l1_v %*% est_matrix_975 %*% t(l2_matrix[[i]])
est_samples <- matrix(0, nrow = nrow(l2_matrix[[i]]), ncol = n_sample)
for (n_s in 1:n_sample)
est_samples[ , n_s] <- l1_v %*% est_matrix[, colnames(l2_matrix[[i]]), n_s] %*% t(l2_matrix[[i]]) + p_indicator * sum(l2_var[n_s,])/2 #l2_var[n_s, 1]/2
means <- apply(est_samples, 1, mean)
quantile_025 <- apply(est_samples, 1, quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_samples, 1, quantile, probs = 0.975, type = 3, na.rm = FALSE)
table <- matrix(NA, nrow = length(means), ncol = 4)
table[, 2] <- means
table[, 3] <- pmin(quantile_025, quantile_975)
table[, 4] <- pmax(quantile_025, quantile_975)
table <- round(link_inv(table), digits = 4)
table[, 1] <- attr(l2_matrix[[i]],'levels')
colnames(table) <- c(attr(Z_classes, 'names')[l2_factors[i]], 'mean', '2.5%', '97.5%')
rownames(table) <- rep('', nrow(table))
cat('\n')
print(as.table(table))
sol_tables[['Means for factors at level 2: \n']] <- as.table(table)
}
}
}
# means of interactions between level 1 and 2
if (length(X_classes) != 0 && length(Z_classes) != 0){
if (length(l1_factors) != 0 && length(l2_factors) != 0){
cat('\n')
#cat('Means for interactions between level 1 and level 2 factors: \n')
for (i in 1:length(l1_factors)){
for (j in 1:length(l2_factors)){
#means <- l1_matrix[[i]] %*% est_matrix_mean %*% t(l2_matrix[[j]])
#quantile_025 <- l1_matrix[[i]] %*% est_matrix_025 %*% t(l2_matrix[[j]])
#quantile_975 <- l1_matrix[[i]] %*% est_matrix_975 %*% t(l2_matrix[[j]])
est_samples <- array(0, dim = c(nrow(l1_matrix[[i]]), nrow(l2_matrix[[j]]), n_sample))
for (n_s in 1:n_sample)
est_samples[ , , n_s] <- l1_matrix[[i]] %*% est_matrix[colnames(l1_matrix[[i]]), colnames(l2_matrix[[j]]), n_s] %*% t(l2_matrix[[j]]) + p_indicator * sum(l2_var[n_s,])/2 #sum(l2_var[n_s, c(1,i)])/2
means <- apply(est_samples, c(1,2), mean)
quantile_025 <- apply(est_samples, c(1,2), quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_samples, c(1,2), quantile, probs = 0.975, type = 3, na.rm = FALSE)
table <- matrix(NA, nrow = nrow(l1_matrix[[i]]) * nrow(l2_matrix[[j]]), ncol = 5)
for (k1 in 1:nrow(l1_matrix[[i]])){
temp <- ((k1-1) * nrow(l2_matrix[[j]]) + 1):((k1-1) * nrow(l2_matrix[[j]]) + nrow(l2_matrix[[j]]))
table[temp, 3] <- round(link_inv(means[k1,]), digits = 4)
table[temp, 4] <- pmin(round(link_inv(quantile_025[k1,]), digits = 4), round(link_inv(quantile_975[k1,]), digits = 4))
table[temp, 5] <- pmax(round(link_inv(quantile_025[k1,]), digits = 4), round(link_inv(quantile_975[k1,]), digits = 4))
table[temp, 1] <- rep(attr(l1_matrix[[i]],'levels')[k1], nrow(l2_matrix[[j]]))
table[temp, 2] <- attr(l2_matrix[[j]],'levels')
}
colnames(table) <- c(attr(X_classes, 'names')[l1_factors[i]], attr(Z_classes, 'names')[l2_factors[j]], 'mean', '2.5%', '97.5%')
rownames(table) <- rep('', nrow(table))
cat('\n')
print(as.table(table))
sol_tables[['Means for interactions between level 1 and level 2 factors: \n']] <- as.table(table)
}
}
}
}
# means of interactions in level 1 or 2
if (length(l1_interactions) > 0){
cat('\n')
#cat('Means for interactions at level 1: \n')
l1_inter_matrix <- list()
index <- 1
for (i in 1:length(l1_interactions)){
# y var is also included in l1_values, l1_interactions has considered this
temp1 <- l1_values[l1_interactions[[i]]]
if (length(temp1) >= 2){
#temp2 <- list()
#for (j in 1:length(temp1))
#temp2[[j]] <- levels(temp1[[j]])
l1_inter_matrix[[index]] <- effect.matrix.interaction(interaction_factors = temp1, assign = X_assign,
l1_interactions[[i]] - 1, index_inter_factor = l1_interactions_index[i],
numeric_index_in_X, contrast = contrast) #'-1' exclude the 'y'
est_samples <- matrix(0, nrow = nrow(l1_inter_matrix[[index]]), ncol = n_sample)
for (n_s in 1:n_sample)
est_samples[ ,n_s] <- l1_inter_matrix[[index]] %*% est_matrix[colnames(l1_inter_matrix[[index]]),,n_s] %*% t(l2_v) + p_indicator * sum(l2_var[n_s,])/2 #sum(l2_var[n_s,c('(Intercept)',colnames(l1_inter_matrix[[index]]))])/2
means <- apply(est_samples, 1, mean)
quantile_025 <- apply(est_samples, 1, quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_samples, 1, quantile, probs = 0.975, type = 3, na.rm = FALSE)
table <- cbind(attr(l1_inter_matrix[[index]], 'levels'),
round(link_inv(means), digits = 4),
pmin(round(link_inv(quantile_025), digits = 4), round(link_inv(quantile_975), digits = 4)),
pmax(round(link_inv(quantile_025), digits = 4), round(link_inv(quantile_975), digits = 4)))
colnames(table) <- c(attr(X_classes, 'names')[l1_interactions[[i]] - 1], 'mean', '2.5%', '97.5%') #'-1' is used, since 'y' is considered in interaction index
rownames(table) <- rep('', nrow(table))
cat('\n')
print(as.table(table))
sol_tables[['Means for interactions at level 1: \n']] <- as.table(table)
# print the interaction between this interaction and level 2 factors if there exists
if (length(Z_classes) != 0){
l2_factors <- which(Z_classes == 'factor')
if (length(l2_factors) != 0){
cat('\n')
#cat('Means for interactions between level 1 interactions and level 2 factors: \n')
for (j in 1:length(l2_factors)){
#means <- l1_inter_matrix[[index]] %*% est_matrix_mean %*% t(l2_matrix[[j]])
#quantile_025 <- l1_inter_matrix[[index]] %*% est_matrix_025 %*% t(l2_matrix[[j]])
#quantile_975 <- l1_inter_matrix[[index]] %*% est_matrix_975 %*% t(l2_matrix[[j]])
est_samples <- array(0, dim = c(nrow(l1_inter_matrix[[index]]), nrow(l2_matrix[[j]]), n_sample))
for (n_s in 1:n_sample)
est_samples[ , , n_s] <- l1_inter_matrix[[index]] %*% est_matrix[colnames(l1_inter_matrix[[index]]), colnames(l2_matrix[[j]]), n_s] %*% t(l2_matrix[[j]]) + p_indicator * sum(l2_var[n_s,])/2 #sum(l2_var[n_s,c('(Intercept)',colnames(l1_inter_matrix[[index]]))])/2
means <- apply(est_samples, c(1,2), mean)
quantile_025 <- apply(est_samples, c(1,2), quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_samples, c(1,2), quantile, probs = 0.975, type = 3, na.rm = FALSE)
table <- matrix(NA, nrow = nrow(l1_inter_matrix[[i]]) * nrow(l2_matrix[[j]]), ncol = 6)
for (k1 in 1:nrow(l1_inter_matrix[[i]])){
temp <- ((k1-1) * nrow(l2_matrix[[j]]) + 1):((k1-1) * nrow(l2_matrix[[j]]) + nrow(l2_matrix[[j]]))
table[temp, 4] <- round(link_inv(means[k1,]), digits = 4)
table[temp, 5] <- pmin(round(link_inv(quantile_025[k1,]), digits = 4), round(link_inv(quantile_975[k1,]), digits = 4))
table[temp, 6] <- pmax(round(link_inv(quantile_025[k1,]), digits = 4), round(link_inv(quantile_975[k1,]), digits = 4))
table[temp, 1] <- attr(l1_inter_matrix[[i]],'levels')[k1,][1]
table[temp, 2] <- attr(l1_inter_matrix[[i]],'levels')[k1,][2]
table[temp, 3] <- attr(l2_matrix[[j]],'levels')
}
colnames(table) <- c(attr(X_classes, 'names')[l1_interactions[[i]] - 1], attr(Z_classes, 'names')[l2_factors[j]], 'mean', '2.5%', '97.5%')
rownames(table) <- rep('', nrow(table))
cat('\n')
print(as.table(table))
sol_tables[['Means for interactions between level 1 interactions and level 2 factors: \n']] <- as.table(table)
}
}
}
index <- index + 1
}
}
}
if (length(l2_interactions) > 0){
cat('\n')
#cat('Means for interactions at level 2: \n')
l2_inter_matrix <- list()
index <- 1
for (i in 1:length(l2_interactions)){
temp1 <- l2_values[l2_interactions[[i]]]
if (length(temp1) >= 2){
#temp2 <- list()
#for (j in 1:length(temp1))
#temp2[[j]] <- levels(temp1[[j]])
l2_inter_matrix[[index]] <- effect.matrix.interaction(interaction_factors = temp1, assign = Z_assign,
l2_interactions[[i]], index_inter_factor = l2_interactions_index[i],
numeric_index_in_Z, contrast = contrast)
#means <- l1_v %*% est_matrix_mean %*% t(l2_inter_matrix[[index]])
#quantile_025 <- l1_v %*% est_matrix_025 %*% t(l2_inter_matrix[[index]])
#quantile_975 <- l1_v %*% est_matrix_975 %*% t(l2_inter_matrix[[index]])
est_samples <- matrix(0, nrow = nrow(l2_inter_matrix[[index]]), ncol = n_sample)
#print('debug')
#print(l2_inter_matrix[[index]])
for (n_s in 1:n_sample)
est_samples[ ,n_s] <- l1_v %*% est_matrix[, colnames(l2_inter_matrix[[index]]), n_s] %*% t(l2_inter_matrix[[index]]) + p_indicator * sum(l2_var[n_s,])/2 #l2_var[n_s,c('(Intercept)')]/2
means <- apply(est_samples, 1, mean)
quantile_025 <- apply(est_samples, 1, quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_samples, 1, quantile, probs = 0.975, type = 3, na.rm = FALSE)
table <- cbind(attr(l2_inter_matrix[[index]], 'levels'),
matrix(round(link_inv(means), digits = 4), ncol = 1),
matrix(pmin(round(link_inv(quantile_025), digits = 4), round(link_inv(quantile_975), digits = 4)), ncol = 1),
matrix(pmax(round(link_inv(quantile_025), digits = 4), round(link_inv(quantile_975), digits = 4)), ncol = 1))
colnames(table) <- c(attr(Z_classes, 'names')[l2_interactions[[i]]], 'mean', '2.5%', '97.5%')
rownames(table) <- rep('', nrow(table))
cat('\n')
print(as.table(table))
sol_tables[['Means for interactions at level 2: \n']] <- as.table(table)
# print the interaction between this interaction and level 1 factors if there exists
if (length(X_classes) != 0){
l1_factors <- which(X_classes == 'factor')
if (length(l1_factors) != 0){
cat('\n')
#cat('Means for interactions between level 2 interactions and level 1 factors: \n')
for (j in 1:length(l1_factors)){
#means <- l1_matrix[[j]] %*% est_matrix_mean %*% t(l2_inter_matrix[[index]])
#quantile_025 <- l1_matrix[[j]] %*% est_matrix_025 %*% t(l2_inter_matrix[[index]])
#quantile_975 <- l1_matrix[[j]] %*% est_matrix_975 %*% t(l2_inter_matrix[[index]])
est_samples <- array(0, dim = c(nrow(l1_matrix[[j]]), nrow(l2_inter_matrix[[index]]), n_sample))
for (n_s in 1:n_sample)
est_samples[,, n_s] <- l1_matrix[[j]] %*% est_matrix[colnames(l1_matrix[[j]]), colnames(l2_inter_matrix[[index]]), n_s] %*% t(l2_inter_matrix[[index]]) + p_indicator * sum(l2_var[n_s,])/2 #sum(l2_var[n_s,c('(Intercept)',colnames(colnames(l1_matrix[[j]])))])/2
means <- apply(est_samples, c(1,2), mean)
quantile_025 <- apply(est_samples, c(1,2), quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_samples, c(1,2), quantile, probs = 0.975, type = 3, na.rm = FALSE)
table <- matrix(NA, nrow = nrow(l1_matrix[[j]]) * nrow(l2_inter_matrix[[index]]), ncol = 6)
for (k1 in 1:nrow(l1_matrix[[j]])){
temp <- ((k1-1) * nrow(l2_inter_matrix[[index]]) + 1):((k1-1) * nrow(l2_inter_matrix[[index]]) + nrow(l2_inter_matrix[[index]]))
table[temp, 4] <- round(link_inv(means[k1,]), digits = 4)
table[temp, 5] <- pmin(round(link_inv(quantile_025[k1,]), digits = 4), round(link_inv(quantile_975[k1,]), digits = 4))
table[temp, 6] <- pmax(round(link_inv(quantile_025[k1,]), digits = 4), round(link_inv(quantile_975[k1,]), digits = 4))
table[temp, 1] <- attr(l1_matrix[[j]],'levels')[k1]
table[temp, 2:3] <- attr(l2_inter_matrix[[i]],'levels')
}
colnames(table) <- c(attr(X_classes, 'names')[l1_factors[[j]]], attr(Z_classes, 'names')[l2_interactions[[i]]], 'mean', '2.5%', '97.5%')
rownames(table) <- rep('', nrow(table))
cat('\n')
print(as.table(table))
sol_tables[['Means for interactions between level 2 interactions and level 1 factors: \n']] <- as.table(table)
}
}
}
index <- index + 1
}
}
}
}
if (model == 'MultinomialordNormal'){
# ordered multinomial
link_inv <- function(x) return(exp(x)/(exp(x) + 1))
n.cut <- ncol(samples_cutp_param) + 1
cut_samples <- cbind(0, 0, samples_cutp_param, 0) # the first cut point is 0, the previous is set to be 0 to compute the prob. of Y == 1 (1 - logit^-1), the last 0 is for the prob. Y == K
# compute the overall table of means(prediction of y)
cat('\n')
cat('Table of means of the response\n')
cat('------------------------------\n')
# grand mean
l1_v <- matrix(c(1, rep(0, num_l1 - 1)), nrow = 1)
l2_v <- matrix(c(1, rep(0, num_l2 - 1)), nrow = 1)
est_gmean <- 0
for (y in 1:(n.cut + 1)){
est_samples <- est(link_inv, est_matrix, n_sample, l1_v, l2_v, cut_samples[,y], cut_samples[,y+1])
est_gmean <- est_gmean + y*est_samples
}
means <- apply(est_gmean, 1, mean)
quantile_025 <- apply(est_gmean, 1, quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_gmean, 1, quantile, probs = 0.975, type = 3, na.rm = FALSE)
cat('\n')
cat('Grand mean: \n')
cat(round(means, digits = 4))
cat('\n')
sol_tables[['Grand mean: \n']] <- as.table(matrix(round(c(quantile_025,quantile_975), digits = 4), nrow = 1, ncol = 2, dimnames = list('',c('2.5%','97.5%'))))
print(sol_tables[['Grand mean: \n']])
# means of main effects in level 1 and 2
if (length(X_classes) != 0){
l1_factors <- which(X_classes == 'factor')
if (length(l1_factors) != 0){
cat('\n')
#cat('Means for factors at level 1: \n')
l1_matrix <- list()
for (i in 1:length(l1_factors)){
# y var is also included in l1_values
l1_matrix[[i]] <- effect.matrix.factor(l1_values[[l1_factors[i]+1]], X_assign, l1_factors[i], numeric_index_in_X, contrast = contrast)
# Compute median and quantile
est_l1mean <- 0
for (y in 1:(n.cut + 1)){
est_samples <- est(link_inv, est_matrix, n_sample, l1_matrix[[i]], l2_v, cut_samples[,y], cut_samples[,y + 1])
est_l1mean <- est_l1mean + y*est_samples
}
means <- apply(est_l1mean, 1, mean)
quantile_025 <- apply(est_l1mean, 1, quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_l1mean, 1, quantile, probs = 0.975, type = 3, na.rm = FALSE)
table <- matrix(NA, nrow = length(means), ncol = 4)
table[, 2] <- means
table[, 3] <- pmin(quantile_025, quantile_975)
table[, 4] <- pmax(quantile_025, quantile_975)
table <- round(table, digits = 4)
table[, 1] <- attr(l1_matrix[[i]],'levels')
colnames(table) <- c(attr(X_classes, 'names')[l1_factors[i]], 'mean', '2.5%', '97.5%')
rownames(table) <- rep('', nrow(table))
cat('\n')
print(as.table(table))
sol_tables[['Means for factors at level 1: \n']] <- as.table(table)
}
}
}
if (length(Z_classes) != 0){
l2_factors <- which(Z_classes == 'factor')
if (length(l2_factors) != 0){
cat('\n')
#cat('Means for factors at level 2: \n')
l2_matrix <- list()
#l1_v <- matrix(c(1, rep(0, num_l1 - 1)), nrow = 1) # only look at the intercept in level 1
for (i in 1:length(l2_factors)){
l2_matrix[[i]] <- effect.matrix.factor(l2_values[[l2_factors[i]]], Z_assign, l2_factors[i], numeric_index_in_Z, contrast = contrast)
est_l2mean <- 0
for (y in 1:(n.cut + 1)){
est_samples <- est(link_inv, est_matrix, n_sample, l1_v, l2_matrix[[i]], cut_samples[,y], cut_samples[,y+1])
est_l2mean <- est_l2mean + y*est_samples
}
means <- apply(est_l2mean, 1, mean)
quantile_025 <- apply(est_l2mean, 1, quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_l2mean, 1, quantile, probs = 0.975, type = 3, na.rm = FALSE)
table <- matrix(NA, nrow = length(means), ncol = 4)
table[, 2] <- means
table[, 3] <- pmin(quantile_025, quantile_975)
table[, 4] <- pmax(quantile_025, quantile_975)
table <- round(table, digits = 4)
table[, 1] <- attr(l2_matrix[[i]],'levels')
colnames(table) <- c(attr(Z_classes, 'names')[l2_factors[i]], 'mean', '2.5%', '97.5%')
rownames(table) <- rep('', nrow(table))
cat('\n')
print(as.table(table))
sol_tables[['Means for factors at level 2: \n']] <- as.table(table)
}
}
}
# means of interactions between level 1 and 2
if (length(X_classes) != 0 && length(Z_classes) != 0){
if (length(l1_factors) != 0 && length(l2_factors) != 0){
cat('\n')
#cat('Means for interactions between level 1 and level 2 factors: \n')
for (i in 1:length(l1_factors)){
for (j in 1:length(l2_factors)){
est_l1l2mean <- 0
for (y in 1:(n.cut + 1)){
est_samples <- est(link_inv, est_matrix, n_sample, l1_matrix[[i]], l2_matrix[[j]], cut_samples[,y], cut_samples[,y+1])
est_l1l2mean <- est_l1l2mean + y*est_samples
}
means <- apply(est_l1l2mean, c(1,2), mean)
quantile_025 <- apply(est_l1l2mean, c(1,2), quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_l1l2mean, c(1,2), quantile, probs = 0.975, type = 3, na.rm = FALSE)
table <- matrix(NA, nrow = nrow(l1_matrix[[i]]) * nrow(l2_matrix[[j]]), ncol = 5)
for (k1 in 1:nrow(l1_matrix[[i]])){
temp <- ((k1-1) * nrow(l2_matrix[[j]]) + 1):((k1-1) * nrow(l2_matrix[[j]]) + nrow(l2_matrix[[j]]))
table[temp, 3] <- round(means[k1,], digits = 4)
table[temp, 4] <- pmin(round(quantile_025[k1,], digits = 4), round(quantile_975[k1,], digits = 4))
table[temp, 5] <- pmax(round(quantile_025[k1,], digits = 4), round(quantile_975[k1,], digits = 4))
table[temp, 1] <- rep(attr(l1_matrix[[i]],'levels')[k1], nrow(l2_matrix[[j]]))
table[temp, 2] <- attr(l2_matrix[[j]],'levels')
}
colnames(table) <- c(attr(X_classes, 'names')[l1_factors[i]], attr(Z_classes, 'names')[l2_factors[j]], 'mean', '2.5%', '97.5%')
rownames(table) <- rep('', nrow(table))
cat('\n')
print(as.table(table))
sol_tables[['Means for interactions between level 1 and level 2 factors: \n']] <- as.table(table)
}
}
}
}
# means of interactions in level 1 or 2
if (length(l1_interactions) > 0){
cat('\n')
#cat('Means for interactions at level 1: \n')
l1_inter_matrix <- list()
index <- 1
for (i in 1:length(l1_interactions)){
# y var is also included in l1_values, l1_interactions has considered this
temp1 <- l1_values[l1_interactions[[i]]]
if (length(temp1) >= 2){
#temp2 <- list()
#for (j in 1:length(temp1))
#temp2[[j]] <- levels(temp1[[j]])
l1_inter_matrix[[index]] <- effect.matrix.interaction(interaction_factors = temp1, assign = X_assign,
l1_interactions[[i]] - 1, index_inter_factor = l1_interactions_index[i],
numeric_index_in_X, contrast = contrast) #'-1' exclude the 'y'
est_l1inmean <- 0
for (y in 1:(n.cut + 1)){
est_samples <- est(link_inv, est_matrix, n_sample, l1_inter_matrix[[index]], l2_v, cut_samples[,y], cut_samples[,y+1])
est_l1inmean <- est_l1inmean + y*est_samples
}
means <- apply(est_l1inmean, 1, mean)
quantile_025 <- apply(est_l1inmean, 1, quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_l1inmean, 1, quantile, probs = 0.975, type = 3, na.rm = FALSE)
table <- cbind(attr(l1_inter_matrix[[index]], 'levels'),
round(means, digits = 4),
pmin(round(quantile_025, digits = 4), round(quantile_975, digits = 4)),
pmax(round(quantile_025, digits = 4), round(quantile_975, digits = 4)))
colnames(table) <- c(attr(X_classes, 'names')[l1_interactions[[i]] - 1], 'mean', '2.5%', '97.5%') #'-1' is used, since 'y' is considered in interaction index
rownames(table) <- rep('', nrow(table))
cat('\n')
print(as.table(table))
sol_tables[['Means for interactions at level 1: \n']] <- as.table(table)
# print the interaction between this interaction and level 2 factors if there exists
if (length(Z_classes) != 0){
l2_factors <- which(Z_classes == 'factor')
if (length(l2_factors) != 0){
cat('\n')
#cat('Means for interactions between level 1 interactions and level 2 factors: \n')
for (j in 1:length(l2_factors)){
est_l1inl2mean <- 0
for (y in 1:(n.cut + 1)){
est_samples <- est(link_inv, est_matrix, n_sample, l1_inter_matrix[[index]], l2_matrix[[j]], cut_samples[,y], cut_samples[,y+1])
est_l1inl2mean <- est_l1inl2mean + y*est_samples
}
means <- apply(est_l1inl2mean, c(1,2), mean)
quantile_025 <- apply(est_l1inl2mean, c(1,2), quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_l1inl2mean, c(1,2), quantile, probs = 0.975, type = 3, na.rm = FALSE)
table <- matrix(NA, nrow = nrow(l1_inter_matrix[[i]]) * nrow(l2_matrix[[j]]), ncol = 6)
for (k1 in 1:nrow(l1_inter_matrix[[i]])){
temp <- ((k1-1) * nrow(l2_matrix[[j]]) + 1):((k1-1) * nrow(l2_matrix[[j]]) + nrow(l2_matrix[[j]]))
table[temp, 4] <- round(means[k1,], digits = 4)
table[temp, 5] <- pmin(round(quantile_025[k1,], digits = 4), round(quantile_975[k1,], digits = 4))
table[temp, 6] <- pmax(round(quantile_025[k1,], digits = 4), round(quantile_975[k1,], digits = 4))
table[temp, 1] <- attr(l1_inter_matrix[[i]],'levels')[k1,][1]
table[temp, 2] <- attr(l1_inter_matrix[[i]],'levels')[k1,][2]
table[temp, 3] <- attr(l2_matrix[[j]],'levels')
}
colnames(table) <- c(attr(X_classes, 'names')[l1_interactions[[i]] - 1], attr(Z_classes, 'names')[l2_factors[j]], 'mean', '2.5%', '97.5%')
rownames(table) <- rep('', nrow(table))
cat('\n')
print(as.table(table))
sol_tables[['Means for interactions between level 1 interactions and level 2 factors: \n']] <- as.table(table)
}
}
}
index <- index + 1
}
}
}
if (length(l2_interactions) > 0){
cat('\n')
#cat('Means for interactions at level 2: \n')
l2_inter_matrix <- list()
index <- 1
for (i in 1:length(l2_interactions)){
temp1 <- l2_values[l2_interactions[[i]]]
if (length(temp1) >= 2){
#temp2 <- list()
#for (j in 1:length(temp1))
#temp2[[j]] <- levels(temp1[[j]])
l2_inter_matrix[[index]] <- effect.matrix.interaction(interaction_factors = temp1, assign = Z_assign,
l2_interactions[[i]], index_inter_factor = l2_interactions_index[i],
numeric_index_in_Z, contrast = contrast)
est_l2inmean <- 0
for (y in 1:(n.cut + 1)){
est_samples <- est(link_inv, est_matrix, n_sample, l1_v, l2_inter_matrix[[index]], cut_samples[,y], cut_samples[,y+1])
est_l2inmean <- est_l2inmean + y * est_samples
}
means <- apply(est_l2inmean, 1, mean)
quantile_025 <- apply(est_l2inmean, 1, quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_l2inmean, 1, quantile, probs = 0.975, type = 3, na.rm = FALSE)
table <- cbind(attr(l2_inter_matrix[[index]], 'levels'),
matrix(round(means, digits = 4), ncol = 1),
matrix(pmin(round(quantile_025, digits = 4), round(quantile_975, digits = 4)), ncol = 1),
matrix(pmax(round(quantile_025, digits = 4), round(quantile_975, digits = 4)), ncol = 1))
colnames(table) <- c(attr(Z_classes, 'names')[l2_interactions[[i]]], 'mean', '2.5%', '97.5%')
rownames(table) <- rep('', nrow(table))
cat('\n')
print(as.table(table))
sol_tables[['Means for interactions at level 2: \n']] <- as.table(table)
# print the interaction between this interaction and level 1 factors if there exists
if (length(X_classes) != 0){
l1_factors <- which(X_classes == 'factor')
if (length(l1_factors) != 0){
cat('\n')
#cat('Means for interactions between level 2 interactions and level 1 factors: \n')
for (j in 1:length(l1_factors)){
est_l2inl1mean <- 0
for (y in 1:(n.cut + 1)){
est_samples <- est(link_inv, est_matrix, n_sample, l1_matrix[[j]], l2_inter_matrix[[index]], cut_samples[,y], cut_samples[,y+1])
est_l2inl1mean <- est_l2inl1mean + est_samples
}
means <- apply(est_l2inl1mean, c(1,2), mean)
quantile_025 <- apply(est_l2inl1mean, c(1,2), quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_l2inl1mean, c(1,2), quantile, probs = 0.975, type = 3, na.rm = FALSE)
table <- matrix(NA, nrow = nrow(l1_matrix[[j]]) * nrow(l2_inter_matrix[[index]]), ncol = 6)
for (k1 in 1:nrow(l1_matrix[[j]])){
temp <- ((k1-1) * nrow(l2_inter_matrix[[index]]) + 1):((k1-1) * nrow(l2_inter_matrix[[index]]) + nrow(l2_inter_matrix[[index]]))
table[temp, 4] <- round(means[k1,], digits = 4)
table[temp, 5] <- pmin(round(quantile_025[k1,], digits = 4), round(quantile_975[k1,], digits = 4))
table[temp, 6] <- pmax(round(quantile_025[k1,], digits = 4), round(quantile_975[k1,], digits = 4))
table[temp, 1] <- attr(l1_matrix[[j]],'levels')[k1]
table[temp, 2:3] <- attr(l2_inter_matrix[[i]],'levels')
}
colnames(table) <- c(attr(X_classes, 'names')[l1_factors[[j]]], attr(Z_classes, 'names')[l2_interactions[[i]]], 'mean', '2.5%', '97.5%')
rownames(table) <- rep('', nrow(table))
cat('\n')
print(as.table(table))
sol_tables[['Means for interactions between level 2 interactions and level 1 factors: \n']] <- as.table(table)
}
}
}
index <- index + 1
}
}
}
# compute the details of table of means corresponding to each category of y
cat('\n')
cat('Table of probabilities for each category of the response\n')
cat('-------------------------------------------------------\n')
for (y in 1:(n.cut + 1)){
cat('\n')
cat('Response : ', y, '\n')
temp_title <- paste('Table of probabilities for each category of the response ', y, sep = "")
sol_tables[[temp_title]] <- list()
# Grand mean
l1_v <- matrix(c(1, rep(0, num_l1 - 1)), nrow = 1)
l2_v <- matrix(c(1, rep(0, num_l2 - 1)), nrow = 1)
est_samples <- est(link_inv, est_matrix, n_sample, l1_v, l2_v, cut_samples[,y], cut_samples[,y+1])
means <- apply(est_samples, 1, mean)
quantile_025 <- apply(est_samples, 1, quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_samples, 1, quantile, probs = 0.975, type = 3, na.rm = FALSE)
cat('\n')
cat('Grand mean: \n')
cat(round(means, digits = 4))
cat('\n')
sol_tables[[temp_title]][['Grand mean: \n']] <- as.table(matrix(round(c(quantile_025,quantile_975), digits = 4), nrow = 1, ncol = 2, dimnames = list('',c('2.5%','97.5%'))))
print(sol_tables[[temp_title]][['Grand mean: \n']])
# means of main effect in level 1 and 2
if (length(X_classes) != 0){
l1_factors <- which(X_classes == 'factor')
if (length(l1_factors) != 0){
cat('\n')
#cat('Means for factors at level 1: \n')
l1_matrix <- list()
#l2_v <- matrix(c(1, rep(0, num_l2 - 1)), nrow = 1) # only look at the intercept in level 2
for (i in 1:length(l1_factors)){
# y var is also included in l1_values
l1_matrix[[i]] <- effect.matrix.factor(l1_values[[l1_factors[i]+1]], X_assign, l1_factors[i], numeric_index_in_X, contrast = contrast)
#means <- l1_matrix[[i]] %*% est_matrix_mean %*% l2_v
#quantile_025 <- l1_matrix[[i]] %*% est_matrix_025 %*% l2_v
#quantile_975 <- l1_matrix[[i]] %*% est_matrix_975 %*% l2_v
# Compute median and quantile
est_samples <- est(link_inv, est_matrix, n_sample, l1_matrix[[i]], l2_v, cut_samples[,y], cut_samples[,y+1])
means <- apply(est_samples, 1, mean)
quantile_025 <- apply(est_samples, 1, quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_samples, 1, quantile, probs = 0.975, type = 3, na.rm = FALSE)
table <- matrix(NA, nrow = length(means), ncol = 4)
table[, 2] <- means
table[, 3] <- pmin(quantile_025, quantile_975)
table[, 4] <- pmax(quantile_025, quantile_975)
table <- round(table, digits = 4)
table[, 1] <- attr(l1_matrix[[i]],'levels')
colnames(table) <- c(attr(X_classes, 'names')[l1_factors[i]], 'mean', '2.5%', '97.5%')
rownames(table) <- rep('', nrow(table))
cat('\n')
print(as.table(table))
sol_tables[[temp_title]][['Means for factors at level 1: \n']] <- as.table(table)
}
}
}
if (length(Z_classes) != 0){
l2_factors <- which(Z_classes == 'factor')
if (length(l2_factors) != 0){
cat('\n')
#cat('Means for factors at level 2: \n')
l2_matrix <- list()
#l1_v <- matrix(c(1, rep(0, num_l1 - 1)), nrow = 1) # only look at the intercept in level 1
for (i in 1:length(l2_factors)){
l2_matrix[[i]] <- effect.matrix.factor(l2_values[[l2_factors[i]]], Z_assign, l2_factors[i], numeric_index_in_Z, contrast = contrast)
#means <- l1_v %*% est_matrix_mean %*% t(l2_matrix[[i]])
#quantile_025 <- l1_v %*% est_matrix_025 %*% t(l2_matrix[[i]])
#quantile_975 <- l1_v %*% est_matrix_975 %*% t(l2_matrix[[i]])
est_samples <- est(link_inv, est_matrix, n_sample, l1_v, l2_matrix[[i]], cut_samples[,y], cut_samples[,y+1])
means <- apply(est_samples, 1, mean)
quantile_025 <- apply(est_samples, 1, quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_samples, 1, quantile, probs = 0.975, type = 3, na.rm = FALSE)
table <- matrix(NA, nrow = length(means), ncol = 4)
table[, 2] <- means
table[, 3] <- pmin(quantile_025, quantile_975)
table[, 4] <- pmax(quantile_025, quantile_975)
table <- round(table, digits = 4)
table[, 1] <- attr(l2_matrix[[i]],'levels')
colnames(table) <- c(attr(Z_classes, 'names')[l2_factors[i]], 'mean', '2.5%', '97.5%')
rownames(table) <- rep('', nrow(table))
cat('\n')
print(as.table(table))
sol_tables[[temp_title]][['Means for factors at level 2: \n']] <- as.table(table)
}
}
}
# means of interactions between level 1 and 2
if (length(X_classes) != 0 && length(Z_classes) != 0){
if (length(l1_factors) != 0 && length(l2_factors) != 0){
cat('\n')
#cat('Means for interactions between level 1 and level 2 factors: \n')
for (i in 1:length(l1_factors)){
for (j in 1:length(l2_factors)){
#means <- l1_matrix[[i]] %*% est_matrix_mean %*% t(l2_matrix[[j]])
#quantile_025 <- l1_matrix[[i]] %*% est_matrix_025 %*% t(l2_matrix[[j]])
#quantile_975 <- l1_matrix[[i]] %*% est_matrix_975 %*% t(l2_matrix[[j]])
est_samples <- est(link_inv, est_matrix, n_sample, l1_matrix[[i]], l2_matrix[[j]], cut_samples[,y], cut_samples[,y+1])
means <- apply(est_samples, c(1,2), mean)
quantile_025 <- apply(est_samples, c(1,2), quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_samples, c(1,2), quantile, probs = 0.975, type = 3, na.rm = FALSE)
table <- matrix(NA, nrow = nrow(l1_matrix[[i]]) * nrow(l2_matrix[[j]]), ncol = 5)
for (k1 in 1:nrow(l1_matrix[[i]])){
temp <- ((k1-1) * nrow(l2_matrix[[j]]) + 1):((k1-1) * nrow(l2_matrix[[j]]) + nrow(l2_matrix[[j]]))
table[temp, 3] <- round(means[k1,], digits = 4)
table[temp, 4] <- pmin(round(quantile_025[k1,], digits = 4), round(quantile_975[k1,], digits = 4))
table[temp, 5] <- pmax(round(quantile_025[k1,], digits = 4), round(quantile_975[k1,], digits = 4))
table[temp, 1] <- rep(attr(l1_matrix[[i]],'levels')[k1], nrow(l2_matrix[[j]]))
table[temp, 2] <- attr(l2_matrix[[j]],'levels')
}
colnames(table) <- c(attr(X_classes, 'names')[l1_factors[i]], attr(Z_classes, 'names')[l2_factors[j]], 'mean', '2.5%', '97.5%')
rownames(table) <- rep('', nrow(table))
cat('\n')
print(as.table(table))
sol_tables[[temp_title]][['Means for interactions between level 1 and level 2 factors: \n']] <- as.table(table)
}
}
}
}
# means of interactions in level 1 or 2
if (length(l1_interactions) > 0){
cat('\n')
#cat('Means for interactions at level 1: \n')
l1_inter_matrix <- list()
index <- 1
for (i in 1:length(l1_interactions)){
# y var is also included in l1_values, l1_interactions has considered this
temp1 <- l1_values[l1_interactions[[i]]]
if (length(temp1) >= 2){
#temp2 <- list()
#for (j in 1:length(temp1))
#temp2[[j]] <- levels(temp1[[j]])
l1_inter_matrix[[index]] <- effect.matrix.interaction(interaction_factors = temp1, assign = X_assign,
l1_interactions[[i]] - 1, index_inter_factor = l1_interactions_index[i],
numeric_index_in_X, contrast = contrast) #'-1' exclude the 'y'
#means <- l1_inter_matrix[[index]] %*% est_matrix_mean %*% l2_v
#quantile_025 <- l1_inter_matrix[[index]] %*% est_matrix_025 %*% l2_v
#quantile_975 <- l1_inter_matrix[[index]] %*% est_matrix_975 %*% l2_v
est_samples <- est(link_inv, est_matrix, n_sample, l1_inter_matrix[[index]], l2_v, cut_samples[,y], cut_samples[,y+1])
means <- apply(est_samples, 1, mean)
quantile_025 <- apply(est_samples, 1, quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_samples, 1, quantile, probs = 0.975, type = 3, na.rm = FALSE)
table <- cbind(attr(l1_inter_matrix[[index]], 'levels'),
round(means, digits = 4),
pmin(round(quantile_025, digits = 4), round(quantile_975, digits = 4)),
pmax(round(quantile_025, digits = 4), round(quantile_975, digits = 4)))
colnames(table) <- c(attr(X_classes, 'names')[l1_interactions[[i]] - 1], 'mean', '2.5%', '97.5%') #'-1' is used, since 'y' is considered in interaction index
rownames(table) <- rep('', nrow(table))
cat('\n')
print(as.table(table))
sol_tables[[temp_title]][['Means for interactions at level 1: \n']] <- as.table(table)
# print the interaction between this interaction and level 2 factors if there exists
if (length(Z_classes) != 0){
l2_factors <- which(Z_classes == 'factor')
if (length(l2_factors) != 0){
cat('\n')
#cat('Means for interactions between level 1 interactions and level 2 factors: \n')
for (j in 1:length(l2_factors)){
#means <- l1_inter_matrix[[index]] %*% est_matrix_mean %*% t(l2_matrix[[j]])
#quantile_025 <- l1_inter_matrix[[index]] %*% est_matrix_025 %*% t(l2_matrix[[j]])
#quantile_975 <- l1_inter_matrix[[index]] %*% est_matrix_975 %*% t(l2_matrix[[j]])
est_samples <- est(link_inv, est_matrix, n_sample, l1_inter_matrix[[index]], l2_matrix[[j]], cut_samples[,y], cut_samples[,y+1])
means <- apply(est_samples, c(1,2), mean)
quantile_025 <- apply(est_samples, c(1,2), quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_samples, c(1,2), quantile, probs = 0.975, type = 3, na.rm = FALSE)
table <- matrix(NA, nrow = nrow(l1_inter_matrix[[i]]) * nrow(l2_matrix[[j]]), ncol = 6)
for (k1 in 1:nrow(l1_inter_matrix[[i]])){
temp <- ((k1-1) * nrow(l2_matrix[[j]]) + 1):((k1-1) * nrow(l2_matrix[[j]]) + nrow(l2_matrix[[j]]))
table[temp, 4] <- round(means[k1,], digits = 4)
table[temp, 5] <- pmin(round(quantile_025[k1,], digits = 4), round(quantile_975[k1,], digits = 4))
table[temp, 6] <- pmax(round(quantile_025[k1,], digits = 4), round(quantile_975[k1,], digits = 4))
table[temp, 1] <- attr(l1_inter_matrix[[i]],'levels')[k1,][1]
table[temp, 2] <- attr(l1_inter_matrix[[i]],'levels')[k1,][2]
table[temp, 3] <- attr(l2_matrix[[j]],'levels')
}
colnames(table) <- c(attr(X_classes, 'names')[l1_interactions[[i]] - 1], attr(Z_classes, 'names')[l2_factors[j]], 'mean', '2.5%', '97.5%')
rownames(table) <- rep('', nrow(table))
cat('\n')
print(as.table(table))
sol_tables[[temp_title]][['Means for interactions between level 1 interactions and level 2 factors: \n']] <- as.table(table)
}
}
}
index <- index + 1
}
}
}
if (length(l2_interactions) > 0){
cat('\n')
#cat('Means for interactions at level 2: \n')
l2_inter_matrix <- list()
index <- 1
for (i in 1:length(l2_interactions)){
temp1 <- l2_values[l2_interactions[[i]]]
if (length(temp1) >= 2){
#temp2 <- list()
#for (j in 1:length(temp1))
#temp2[[j]] <- levels(temp1[[j]])
l2_inter_matrix[[index]] <- effect.matrix.interaction(interaction_factors = temp1, assign = Z_assign,
l2_interactions[[i]], index_inter_factor = l2_interactions_index[i],
numeric_index_in_Z, contrast = contrast)
#means <- l1_v %*% est_matrix_mean %*% t(l2_inter_matrix[[index]])
#quantile_025 <- l1_v %*% est_matrix_025 %*% t(l2_inter_matrix[[index]])
#quantile_975 <- l1_v %*% est_matrix_975 %*% t(l2_inter_matrix[[index]])
est_samples <- est(link_inv, est_matrix, n_sample, l1_v, l2_inter_matrix[[index]], cut_samples[,y], cut_samples[,y+1])
means <- apply(est_samples, 1, mean)
quantile_025 <- apply(est_samples, 1, quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_samples, 1, quantile, probs = 0.975, type = 3, na.rm = FALSE)
table <- cbind(attr(l2_inter_matrix[[index]], 'levels'),
matrix(round(means, digits = 4), ncol = 1),
matrix(pmin(round(quantile_025, digits = 4), round(quantile_975, digits = 4)), ncol = 1),
matrix(pmax(round(quantile_025, digits = 4), round(quantile_975, digits = 4)), ncol = 1))
colnames(table) <- c(attr(Z_classes, 'names')[l2_interactions[[i]]], 'mean', '2.5%', '97.5%')
rownames(table) <- rep('', nrow(table))
cat('\n')
print(as.table(table))
sol_tables[[temp_title]][['Means for interactions at level 2: \n']] <- as.table(table)
# print the interaction between this interaction and level 1 factors if there exists
if (length(X_classes) != 0){
l1_factors <- which(X_classes == 'factor')
if (length(l1_factors) != 0){
cat('\n')
#cat('Means for interactions between level 2 interactions and level 1 factors: \n')
for (j in 1:length(l1_factors)){
#means <- l1_matrix[[j]] %*% est_matrix_mean %*% t(l2_inter_matrix[[index]])
#quantile_025 <- l1_matrix[[j]] %*% est_matrix_025 %*% t(l2_inter_matrix[[index]])
#quantile_975 <- l1_matrix[[j]] %*% est_matrix_975 %*% t(l2_inter_matrix[[index]])
est_samples <- est(link_inv, est_matrix, n_sample, l1_matrix[[j]], l2_inter_matrix[[index]], cut_samples[,y], cut_samples[,y+1])
means <- apply(est_samples, c(1,2), mean)
quantile_025 <- apply(est_samples, c(1,2), quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(est_samples, c(1,2), quantile, probs = 0.975, type = 3, na.rm = FALSE)
table <- matrix(NA, nrow = nrow(l1_matrix[[j]]) * nrow(l2_inter_matrix[[index]]), ncol = 6)
for (k1 in 1:nrow(l1_matrix[[j]])){
temp <- ((k1-1) * nrow(l2_inter_matrix[[index]]) + 1):((k1-1) * nrow(l2_inter_matrix[[index]]) + nrow(l2_inter_matrix[[index]]))
table[temp, 4] <- round(means[k1,], digits = 4)
table[temp, 5] <- pmin(round(quantile_025[k1,], digits = 4), round(quantile_975[k1,], digits = 4))
table[temp, 6] <- pmax(round(quantile_025[k1,], digits = 4), round(quantile_975[k1,], digits = 4))
table[temp, 1] <- attr(l1_matrix[[j]],'levels')[k1]
table[temp, 2:3] <- attr(l2_inter_matrix[[i]],'levels')
}
colnames(table) <- c(attr(X_classes, 'names')[l1_factors[[j]]], attr(Z_classes, 'names')[l2_interactions[[i]]], 'mean', '2.5%', '97.5%')
rownames(table) <- rep('', nrow(table))
cat('\n')
print(as.table(table))
sol_tables[[temp_title]][['Means for interactions between level 2 interactions and level 1 factors: \n']] <- as.table(table)
}
}
}
index <- index + 1
}
}
}
}
}
return(sol_tables)
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/print.table.means.R |
printCoefmat <-
function (coef_table){
print(data.frame(coef_table))
cat('---')
cat('\nSignif. codes: 0 *** 0.001 ** 0.01 * 0.05 . 0.1 1 \n')
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/printCoefmat.R |
results.BANOVA.mlvNormal <- function(fit_beta, dep_var_names, dMatrice, single_level = F){
# This function combines tables for the multivariate (normal) models. The results for multivariate
# models are first obtained for each individual dependent variable (in a for loop) and then is
# combined in this function.
# Param: list_with_tables list with tables to be combined. Each element in the list is expected
# to have a name of the corresponding dependent variabel (for example "y1", "y2", etc).
# list_with_tables[["y1"]] is expected to have one or more elemnts which are matrices or data frames
# Param: list_names_first logical. If TRUE the rownames of tables have the names of dependent
# variables first, followed by default rownames (for example "y1 (Intercept)").
# If FLASE default rownames are followed by variable names (for example "(Intercept) y1")
# Param: list_elements_length numeric. how many elemnts are in each list (must be the same for all dep vars)
# Param: anova logical. Used to assign a class of the tables
# Param: conv logical. Used to assign a class of the tables
combine.tables <- function(list_with_tables, list_names_first = T, list_elements_length = 1,
anova = F, conv = F){
combine <- function(list_with_tables, element_name = "NA"){
row_names <- rownames(list_with_tables[[1]])
col_names <- colnames(list_with_tables[[1]])
if(is.null(row_names)){
if (is.null(dim(list_with_tables[[1]]))){
if (length(list_with_tables[[1]]) != 1){
row_names = " "
col_names = rep("", length(list_with_tables[[1]]))
} else {
row_names = " "
col_names = " "
}
} else {
dimensions <- dim(list_with_tables[[1]])
row_names = c(1:dimensions[1])
col_names = c(1:dimensions[2])
}
}
n_row <- length(row_names)
n_col <- length(col_names)
new_row_names <- c()
if(list_names_first){
for (element in list_names)
new_row_names <- c(new_row_names, format(paste0(element, " ", row_names)))
}else{
for (element in list_names)
new_row_names <- c(new_row_names, format(paste0(row_names, " ", element)))
}
combined_table <- matrix(NA, nrow = n_row*list_length, ncol = n_col)
for (i in 1:list_length){
dv_name <- list_names[i]
combined_table[(1+n_row*(i-1)):(n_row+n_row*(i-1)),] <- as.matrix(list_with_tables[[dv_name]])
}
if (element_name == "pass_ind"){
combined_table <- all(combined_table == TRUE)
} else if (element_name == "row_indices"){
colnames(combined_table) <- c(col_names)
rownames(combined_table) <- new_row_names
} else {
combined_table <- as.data.frame(combined_table)
colnames(combined_table) <- c(col_names)
rownames(combined_table) <- new_row_names
}
return(combined_table)
}
list_names <- names(list_with_tables)
list_length <- length(list_with_tables)
if (list_elements_length == 1){
combined_tables <- combine(list_with_tables)
} else {
element_names <- names(list_with_tables[[1]])
combined_tables <- list()
for (element_name in element_names){
temp_list <- list()
for (name in list_names)
temp_list[[name]] <- list_with_tables[[name]][[element_name]]
combined_tables[[element_name]] <- combine(temp_list, element_name)
}
if (anova){
class(combined_tables) <- "ancova.effect"
} else if (conv){
class(combined_tables) <- "conv.diag"
}
}
return(combined_tables)
}
combine.samples <- function(list_with_samples){
list_names <- names(list_with_samples)
list_length <- length(list_with_samples)
n_row <- nrow(list_with_samples[[1]])
n_col <- ncol(list_with_samples[[1]])
combined_samples <- matrix(NA, nrow = n_row, ncol = n_col*list_length)
new_colnames <- c()
init_val <- 1
term_val <- n_col
for (i in 1:list_length){
samples <- list_with_samples[[i]]
combined_samples[, init_val:term_val] <- samples
new_colnames <- c(new_colnames, paste0(list_names[i], "_", colnames(samples)))
init_val <- term_val + 1
term_val <- n_col*(i+1)
}
colnames(combined_samples) <- new_colnames
return(combined_samples)
}
prep.return.table <- function(matrix_with_samples){
mean <- apply(matrix_with_samples, 2, mean)
sd <- apply(matrix_with_samples, 2, sd)
quantile_025 <- apply(matrix_with_samples, 2, quantile, probs = 0.025, type = 3, na.rm = FALSE)
quantile_975 <- apply(matrix_with_samples, 2, quantile, probs = 0.975, type = 3, na.rm = FALSE)
p_value <- pValues(matrix_with_samples)
result <- cbind(mean, sd, pmin(quantile_025, quantile_975), pmax(quantile_025, quantile_975),
p_value)
result <- format(round(result, 4), nsmall = 4)
#format pValues
n_columns <- ncol(result)
p_values <- as.numeric(result[, n_columns])
result[, n_columns] <- ifelse(round(p_values, 4) == 0, '<0.0001', result[, n_columns])
colnames(result) <- c("Mean", "SD", "Quantile 0.025", "Quantile 0.975", "p-value")
return(result)
}
y <- dMatrice$y
X <- dMatrice$X
Z <- dMatrice$Z
X_names <- colnames(X)
Z_names <- colnames(Z)
n_iter <- dim(fit_beta$beta1)[1] # number MCMC iterations / number of samples
n_dv <- length(dep_var_names)
#####
#Extract R2
R2 = NULL
if (!is.null(fit_beta$r_2)){
R2 <- colMeans(fit_beta$r_2)
R2 <- round(R2, 4)
}
#Extract Sigma (covariane matrix) and variances of y variables
tau_ySq = NULL
Sigma = NULL
Sigma_samples <- fit_beta$Sigma
if (!is.null(Sigma_samples)){
Sigma <- colMeans(Sigma_samples)
tau_ySq <- diag(Sigma) # Vector with variances for dep vars
Sigma <- as.data.frame(round(Sigma, digits = 4), row.names = dep_var_names)
colnames(Sigma) <- dep_var_names
variance_samples <- matrix(NA, nrow = n_iter, ncol = dim(Sigma_samples)[2])
for (i in 1:n_iter){
variance_samples[i, ] <- diag(Sigma_samples[i, ,])
}
dep_var_sd <- prep.return.table(variance_samples)
dep_var_sd <- as.data.frame(dep_var_sd)
rownames(dep_var_sd) <- paste0(dep_var_names," SD")
}
#Extract Omega (correlation matrix) and variances of y variables
Omega = NULL
Omega_samples <- fit_beta$Omega
if (!is.null(Omega_samples)){
Omega <- colMeans(Omega_samples)
Omega <- as.data.frame(round(Omega, digits = 4), row.names = dep_var_names)
colnames(Omega) <- dep_var_names
correlation_samples <- matrix(NA, nrow = n_iter, ncol = length(Omega[upper.tri(Omega)]))
for (i in 1:n_iter){
Omega_sample <- Omega_samples[i, ,]
correlation_samples[i, ] <- Omega_sample[upper.tri(Omega_sample)]
}
cor_names <- c()
dep_var_names_temp <- dep_var_names
for (dep_var in dep_var_names[-n_dv]){
cor_name <- paste0("Corr(", dep_var, ",",
dep_var_names_temp[dep_var_names_temp!=dep_var],")")
cor_names <- c(cor_names, cor_name)
dep_var_names_temp <- dep_var_names_temp[dep_var_names_temp!=dep_var]
}
dep_var_corr <- prep.return.table(correlation_samples)
dep_var_corr <- as.data.frame(dep_var_corr)
rownames(dep_var_corr) <- cor_names
}
##### Extract first and second level coefficients #####
if (single_level){
samples_l2_param <- NULL
# Identify dimentsions
beta1_dim <- dim(fit_beta$beta1)
L = beta1_dim[2] # number of dependent variables
J = beta1_dim[3] # number of subject-level effects (1st level)
# Prepare names of the coefficients
beta1_names <- c()
for (i in 1:J)
beta1_names <- c(beta1_names, paste("beta1_",i, sep = ""))
##### Prepare results for each of L dependent variables #####
samples_l1.list <- list()
samples_l2.list <- NULL
anova.tables.list <- list()
coef.tables.list <- list()
pvalue.tables.list <- list()
conv.list <- list()
cat('Constructing ANOVA/ANCOVA tables...\n')
for (l in 1:L){
dep_var_name <- dep_var_names[l] #column name of the l_th dependent variable
# Reformat level one coefficient samples sample of the l_th dependent variable
samples_l1_param <- array(0, dim = c(n_iter, J), dimnames = list(NULL, beta1_names))
for (i in 1:J){
samples_l1_param[, i] <- fit_beta$beta1[, l, i]
}
samples_l1.list[[dep_var_name]] <- samples_l1_param
# Result tables for of the l_th dependent variable
anova.tables.list[[dep_var_name]] <- table.ANCOVA(samples_l2_param, Z, X, samples_l1_param,
y_val = array(y[,l], dim = c(length(y[,l]), 1)),
model = 'Normal')
coef.tables.list[[dep_var_name]] <- table.coefficients(samples_l1_param, beta1_names,
Z_names, X_names, attr(Z, 'assign') + 1,
attr(X, 'assign') + 1)
pvalue.tables.list[[dep_var_name]] <- table.pvalue(coef.tables.list[[dep_var_name]]$coeff_table,
coef.tables.list[[dep_var_name]]$row_indices,
l1_names = attr(dMatrice$Z, 'varNames'),
l2_names = attr(dMatrice$X, 'varNames'))
conv.list[[dep_var_name]] <- conv.geweke.heidel(samples_l1_param, Z_names, X_names)
class(conv.list[[dep_var_name]]) <- 'conv.diag'
}
combined.samples.l2 <- NULL
} else {
# Identify dimentsions
beta1_dim <- dim(fit_beta$beta1)
beta2_dim <- dim(fit_beta$beta2)
L = beta2_dim[2] # number of dependent variables
M = beta1_dim[2] # number of unique subjects
J = beta1_dim[4] # number of subject-level effects (1st level)
K = beta2_dim[3] # number of population-level effects (2nd level)
# Prepare names of the coefficients
beta1_names <- c()
for (i in 1:J){
for (j in 1:M){
beta1_names <- c(beta1_names, paste("beta1_",i,"_",j, sep = ""))
}
}
beta2_names <- c()
for (i in 1:J){
for (j in 1:K){
beta2_names <- c(beta2_names, paste("beta2_",i,"_",j, sep = ""))
}
}
##### Prepare results for each of L dependent variables #####
samples_l1.list <- list()
samples_l2.list <- list()
anova.tables.list <- list()
coef.tables.list <- list()
pvalue.tables.list <- list()
conv.list <- list()
cat('Constructing ANOVA/ANCOVA tables...\n')
for (l in 1:L){
dep_var_name <- dep_var_names[l] #column name of the l_th dependent variable
# Reformat level one and level two coefficient samples sample of the l_th dependent variable
samples_l1_param <- array(0, dim = c(n_iter, J*M), dimnames = list(NULL, beta1_names))
for (i in 1:J){
for (j in 1:M){
samples_l1_param[, (i-1) * M + j] <- fit_beta$beta1[, j, l, i]
}
}
samples_l2_param <- array(0, dim = c(n_iter, K*J), dimnames = list(NULL, beta2_names))
for (i in 1:J){
for (j in 1:K){
samples_l2_param[, (i-1) * K + j] <- fit_beta$beta2[, l, j, i]
}
}
samples_l1.list[[dep_var_name]] <- samples_l1_param
samples_l2.list[[dep_var_name]] <- samples_l2_param
# Result tables for of the l_th dependent variable
anova.tables.list[[dep_var_name]] <- table.ANCOVA(samples_l1_param, X, Z,
samples_l2_param, l1_error = tau_ySq[l])
coef.tables.list[[dep_var_name]] <- table.coefficients(samples_l2_param, beta2_names,
X_names, Z_names, attr(X, 'assign') + 1,
attr(Z, 'assign') + 1)
pvalue.tables.list[[dep_var_name]] <- table.pvalue(coef.tables.list[[dep_var_name]]$coeff_table,
coef.tables.list[[dep_var_name]]$row_indices,
l1_names = attr(dMatrice$X, 'varNames'),
l2_names = attr(dMatrice$Z, 'varNames'))
conv.list[[dep_var_name]] <- conv.geweke.heidel(samples_l2_param, X_names, Z_names)
class(conv.list[[dep_var_name]]) <- 'conv.diag'
}
combined.samples.l2 <- combine.samples(samples_l2.list)
}
##### Combine the results #####
combined.anova <- combine.tables(anova.tables.list, T, 2, anova = T)
combined.coef <- combine.tables(coef.tables.list, T, 3)
combined.pvalue <- combine.tables(pvalue.tables.list, T, 1)
combined.conv <- combine.tables(conv.list, T, 3, conv = T)
combined.samples.l1 <- combine.samples(samples_l1.list)
cat('Done.\n')
return(list(combined.anova = combined.anova,
combined.coef = combined.coef,
combined.pvalue = combined.pvalue,
combined.conv = combined.conv,
combined.samples.l1 = combined.samples.l1,
combined.samples.l2 = combined.samples.l2,
samples_l1.list = samples_l1.list,
samples_l2.list = samples_l2.list,
covariance.matrix = Sigma,
correlation.matrix = Omega,
dep_var_sd = dep_var_sd,
dep_var_corr = dep_var_corr,
R2 = R2,
tau_ySq = tau_ySq,
anova.tables.list = anova.tables.list,
coef.tables.list = coef.tables.list,
pvalue.tables.list = pvalue.tables.list,
conv.list = conv.list,
num_depenent_variables = length(dep_var_names),
names_of_dependent_variables = dep_var_names))
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/results.BANOVA.mlvNormal.R |
rowMatch <-
function(vector, matrix){
if (length(vector) == 1) return(match(vector, matrix))
for (i in 1:nrow(matrix)){
if (sum(vector == matrix[i,]) == length(vector))
return(i)
}
return(NA)
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/rowMatch.R |
ssquares <-
function (y, design_matrix, assign, factor_index){
n_f <- length(factor_index)
factor_SS <- array(NA, dim = c(1, n_f))
# get the new design matrix according to assign and factor_index
newassign <- array(0) #include intercept
index_of_factors <- array(1) #include intercept
for (i in 1:n_f){
newassign <- c(newassign, assign[assign == factor_index[i]])
index_of_factors <- c(index_of_factors, which(assign == factor_index[i]))
}
newdesign_matrix <- design_matrix[, index_of_factors]
if (length(index_of_factors) > 1)
if (qr(newdesign_matrix)$rank < length(index_of_factors)) stop ('Colinearity in level 2 design matrix, model is unidentified!')
#SS_TO <- sum((y - mean(y))^2) # total sum of squares for vectors
centered.y <- scale(y, scale = F)
SS_TO <- colSums(centered.y^2)
full <- lsfit(newdesign_matrix, y, intercept = F)
SSE <- colSums((full$residuals)^2)
SS_full <- SS_TO - SSE # sum of squares of the full model
if (n_f == 1){
factor_SS[1] <- round(mean(SS_full), digits = 5)
#paste(round(SS_full, digits = 5), ' (', round((SS_full)/SS_TO*100, digits = 2), '%)', sep="")
}else{
for (i in 1:n_f){
factor_index_i <- which(newassign == factor_index[i])
design_matrix_i <- newdesign_matrix[, -factor_index_i]
model_i <- lsfit(design_matrix_i, y, intercept = F)
SS_i <- SS_TO - colSums((model_i$residuals)^2)
factor_SS[i] <- round(mean(SS_full - SS_i), digits = 5)
#paste(round(SS_full - SS_i, digits = 5), ' (',round((SS_full - SS_i)/SS_TO*100, digits = 2),'%)',sep = '')
}
}
return(list(factor_SS = factor_SS, SS_TO = round(mean(SS_TO), digits = 5), SSE = round(mean(SSE), digits = 5)))
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/ssquares.R |
summary.BANOVA.Bernoulli <-
function(object, ...){
res <- list(anova.table = object$anova.table,
coef.table = object$coef.tables$full_table,
pvalue.table = object$pvalue.table, conv = object$conv, full_object = object, call = object$call)
class(res) <- "summary.BANOVA.Bernoulli"
res
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/summary.BANOVA.Bern.R |
summary.BANOVA.Binomial <-
function(object, ...){
sol <- list(anova.table = object$anova.table,
coef.table = object$coef.tables$full_table,
pvalue.table = object$pvalue.table, conv = object$conv, full_object = object, call = object$call)
class(sol) <- "summary.BANOVA.Binomial"
sol
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/summary.BANOVA.Bin.R |
summary.BANOVA.Multinomial <-
function(object, ...){
sol <- list(anova.table = object$anova.table,
coef.table = object$coef.tables$full_table,
pvalue.table = object$pvalue.table, conv = object$conv, full_object = object, call = object$call)
class(sol) <- "summary.BANOVA.Multinomial"
sol
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/summary.BANOVA.Multinomial.R |
summary.BANOVA.Normal <-
function(object, ...){
res <- list(anova.table = object$anova.table,
coef.table = object$coef.tables$full_table,
pvalue.table = object$pvalue.table, conv = object$conv, full_object = object, call = object$call)
class(res) <- "summary.BANOVA.Normal"
res
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/summary.BANOVA.Normal.R |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.