content
stringlengths
0
14.9M
filename
stringlengths
44
136
#' @export print.summary.befa <- function(x, ...) { cat('BEFA - Bayesian Exploratory Factor Analysis', 'Summary of posterior results\n', sep = '\n') args <- list(...) digits <- args$digits if (is.null(digits)) digits <- 3 cat('Maximum number of factors (Kmax) =', attr(x, 'Kmax'), '\n') cat('Identification restriction (Nid) =', attr(x, 'Nid'), '\n\n') cat('MCMC iterations =', attr(x, 'iter'), '\n') cat('burn-in period =', attr(x, 'burnin'), '\n\n') cat('Metropolis-Hastings acceptance rate =', round(x$MHacc, digits = 3)) cat('\n\n') what <- attr(x, 'what') hpd.prob <- attr(x, 'hpd.prob') if (what == 'hppm') { cat('-----------------------------------------------------------------', 'Indicator matrix\n', 'Dedicated structures visited by the sampler, with corresponding ', 'posterior probabilities and number of factors (K)\n', sep = '\n') cat(paste0('prob(', colnames(x$hppm$dedic), ') = ', sprintf('%.3f', x$hppm$prob), ', K = ', x$hppm$nfac), sep = '\n') cat('\n') print(x$hppm$dedic, print.gap = 3) cat('\n') } else { cat('Posterior frequency of number of latent factors:\n') freq <- sprintf('%3.2f%%', 100*x$nfac) nf <- sprintf('%2i', as.integer(names(x$nfac))) cat(paste(' K =', nf, ' ', freq), sep='\n') cat('\n') } # print MCMC summary results for model parameters cat('-----------------------------------------------------------------', 'Model parameters\n', sep = '\n') print.mcmc <- function(z, title) { res <- round(z, digits = digits) collab <- c('mean', 'sd', sprintf(paste0('[%', digits, '.0f%%'), 100*hpd.prob), sprintf(paste0('%', -(digits+1), 's]'), 'hpd')) if (ncol(z) == 5) collab <- c('dedic', collab) if (ncol(z) == 6) collab <- c('dedic', 'prob', collab) colnames(res) <- collab if (!missing(title)) cat(title, ':\n\n', sep='') print(as.matrix(res), print.gap = 3, na.print = ' ') cat('\n') } print.mcmc.all <- function(alpha, sigma, R, beta) { print.mcmc(alpha, title = 'Factor loadings') print.mcmc(sigma, title = 'Idiosyncratic variances') print.mcmc(R, title = 'Factor correlation matrix') if (!is.null(beta)) print.mcmc(beta, title = 'Regression coefficients') } if (what == 'hppm') { for (i in seq_along(x$hppm$prob)) { cat('-----------------------------------------------------------------\n') cat('Highest posterior probability model ', i, '\n\n', 'prob = ', round(x$hppm$prob[i], digits = 3), '\n', ' K = ', x$hppm$nfac[i], '\n\n', sep = '') print.mcmc.all(x$alpha[[i]], x$sigma[[i]], x$R[[i]], x$beta[[i]]) } } else { print.mcmc.all(x$alpha, x$sigma, x$R, x$beta) } }
/scratch/gouwar.j/cran-all/cranData/BayesFM/R/print.summary.befa.R
#' @export print.summary.simul.R.prior <- function(x, ...) { cat('prior distribution of correlation matrix of latent factors\n\n') cat('maximum correlation (in absolute value):\n\n') print(x$maxcor$stat, print.gap = 3) cat('\n') print(x$maxcor$quant, print.gap = 3) cat('\n') cat('minimum eigenvalue of correlation matrix:\n\n') print(x$mineig$stat, print.gap = 3) cat('\n') print(x$mineig$quant, print.gap = 3) }
/scratch/gouwar.j/cran-all/cranData/BayesFM/R/print.summary.simul.R.prior.R
#' @export print.summary.simul.nfac.prior <- function(x, ...) { cat('prior probabilities of numbers of factors:\n') out <- cbind(do.call(rbind, x$nfac), acc = unlist(x$acc)) out <- round(out, digits = 3) print(out, print.gap = 3) }
/scratch/gouwar.j/cran-all/cranData/BayesFM/R/print.summary.simul.nfac.prior.R
#' #' Simulate prior distribution of factor correlation matrix #' #' This function produces a sample of correlation matrices drawn from their #' prior distribution induced in the identified version of the factor model, #' given the prior distribution specified on the corresponding covariance #' matrices of the factors in the expanded model. #' #' @inheritParams befa #' @param Kmax Maximum number of latent factors. #' @param nrep Number of Monte Carlo replications. #' #' @details Covariance matrices are sampled from the prior distribution in the #' expanded model, and transformed to produce the corresponding correlation #' matrices. See section 2.3.5 of CFSHP (p.36-37), as well as the details of #' the function \code{\link{befa}}. #' #' To compare several prior specifications, different values of the parameters #' \code{nu0} and \code{S0} can be specified. The function then simulates for #' each pair of these parameters. \code{nu0} and \code{S0} should therefore be #' scalars or vectors of same length. #' #' @return A list of length equal to the number of pairs of parameters #' \code{nu0} and \code{S0}, where each element of the list is an array of #' dimension (\code{Kmax}, \code{Kmax}, \code{nrep}) that contains the #' correlation matrices of the latent factors drawn from the prior. #' #' @author Rémi Piatek \email{remi.piatek@@gmail.com} #' #' @references G. Conti, S. Frühwirth-Schnatter, J.J. Heckman, R. Piatek (2014): #' ``Bayesian Exploratory Factor Analysis'', \emph{Journal of Econometrics}, #' 183(1), pages 31-57, \doi{10.1016/j.jeconom.2014.06.008}. #' #' @examples #' # partial reproduction of figure 1 in CFSHP (p.38) #' # note: use larger number of replications nrep to increase smoothness #' Kmax <- 10 #' Rsim <- simul.R.prior(Kmax, nu0 = Kmax + c(1, 2, 5), S0 = .5, nrep = 1000) #' summary(Rsim) #' plot(Rsim) #' #' @export simul.R.prior #' @import checkmate #' @importFrom stats rWishart rgamma simul.R.prior <- function(Kmax, nu0 = Kmax + 1, S0 = 1, HW.prior = TRUE, nrep = 10^5, verbose = TRUE) { # sanity checks checkArgs <- makeAssertCollection() assertInt(Kmax, lower = 1, add = checkArgs) assertNumeric(nu0, lower = Kmax, finite = TRUE, any.missing = FALSE, min.len = 1, add = checkArgs) assertNumeric(S0, lower = 0.000001, finite = TRUE, any.missing = FALSE, min.len = 1, add = checkArgs) if (length(nu0) == 1) nu0 <- rep(nu0, length(S0)) if (length(S0) == 1) S0 <- rep(S0, length(nu0)) if (length(nu0) != length(S0)) checkArgs$push('nu0 and S0 must be of same length') assertFlag(HW.prior, add = checkArgs) assertCount(nrep, positive = TRUE, add = checkArgs) assertFlag(verbose, add = checkArgs) reportAssertions(checkArgs) Rmat <- list() par <- unique(cbind(nu0, S0)) for (i in 1:nrow(par)) { nu0i <- par[i, 1] S0i <- par[i, 2] cat('simulating prior for nu0 =', nu0i, 'and S0 =', S0i, '\n') omg <- rWishart(nrep, df = nu0i, Sigma = diag(Kmax)) if (HW.prior) { nus <- nu0i - Kmax + 1 Sk <- replicate(Kmax, rgamma(nrep, shape = .5, rate = 1/(2 * nus * S0i))) Sk <- sqrt(1/Sk) omg <- lapply(seq(nrep), function(x) diag(Sk[x,]) %*% solve(omg[,,x]) %*% diag(Sk[x,])) } else { S0d <- sqrt(1/S0i) * diag(Kmax) omg <- lapply(seq(nrep), function(x) S0d %*% solve(omg[,,x]) %*% S0d) } omg <- lapply(omg, cov2cor) lab <- paste0('nu0 = ', nu0i, ', S0 = ', S0i) Rmat[[lab]] <- simplify2array(omg) } attr(Rmat, 'call') <- match.call() attr(Rmat, 'Kmax') <- Kmax attr(Rmat, 'nrep') <- nrep class(Rmat) <- 'simul.R.prior' return(Rmat) }
/scratch/gouwar.j/cran-all/cranData/BayesFM/R/simul.R.prior.R
#' #' Generate synthetic data from a dedicated factor model #' #' This function simulates data from a dedicated factor model. The parameters of #' the model are either passed by the user or simulated by the function. #' #' @param N #' Number of observations in data set. #' @param dedic #' Vector of indicators. The number of manifest variables is equal to the #' length of this vector, and the number of factors is equal to the #' number of unique nonzero elements. Each integer element indicates on #' which latent factor the corresponding variable loads uniquely. #' @param alpha #' Vector of factor loadings, should be of same length as \code{dedic}. #' If missing, values are simulated (see details below). #' @param sigma #' Idiosyncratic variances, should be of same length as \code{dedic}. #' If missing, values are simulated (see details below). #' @param R #' Covariance matrix of the latent factors. #' If missing, values are simulated (see details below). #' @param R.corr #' If TRUE, covariance matrix \code{R} is rescaled to be a correlation #' matrix. #' @param max.corr #' Maximum correlation allowed between the latent factors. #' @param R.max.trial #' Maximum number of trials allowed to sample from the truncated #' distribution of the covariance matrix of the latent factors #' (accept/reject sampling scheme, to make sure \code{max.corr} is not #' exceeded). #' #' @details The function simulates data from the following dedicated factor #' model, for \eqn{i = 1, ..., N}: #' \deqn{Y_i = \alpha \theta_i + \epsilon_i} #' \deqn{\theta_i \sim \mathcal{N}(0, R)}{\theta_i ~ N(0, R)} #' \deqn{\epsilon_i \sim \mathcal{N}(0, \Sigma)}{\epsilon_i ~ N(0, \Sigma)} #' where the \eqn{K}-vector \eqn{\theta_i} contains the latent factors, and #' \eqn{\alpha} is the \eqn{(M \times K)}{(M*K)}-matrix of factor loadings. Each #' row \eqn{m} of \eqn{\alpha} contains only zeros, besides its element #' indicated by the \eqn{m}th element of \code{dedic} that is equal to the #' \eqn{m}th element of \code{alpha} (denoted \eqn{\alpha_m^\Delta} below). #' The \eqn{M}-vector \eqn{\epsilon_i} is the vector of error terms, with #' \eqn{\Sigma = diag(}\code{sigma}\eqn{)}. \eqn{M} is equal to the length of #' the vector \code{dedic}, and \eqn{K} is equal to the maximum value of this #' vector. #' #' Only \code{N} and \code{dedic} are required, all the other parameters can be #' missing, completely or partially. Missing values (\code{NA}) are #' independently sampled from the following distributions, for each manifest #' variable \eqn{m = 1, ..., M}: #' #' Factor loadings: #' \deqn{\alpha_m^\Delta = (-1)^{\phi_m}\sqrt{a_m}}{ #' \alpha_m^\Delta = (-1)^\phi_m\sqrt(a_m)} #' \deqn{\phi_m \sim \mathcal{B}er(0.5)}{\phi_m ~ Ber(0.5)} #' \deqn{a_m \sim \mathcal{U}nif (0.04, 0.64)}{a_m ~ Unif (0.04, 0.64)} #' #' Idiosyncratic variances: #' \deqn{\sigma^2_m \sim \mathcal{U}nif (0.2, 0.8)}{ #' \sigma^2_m ~ Unif (0.2, 0.8)} #' #' For the variables that do not load on any factors (i.e., for which the #' corresponding elements of \code{dedic} are equal to 0), it is specified that #' \eqn{\alpha_m^\Delta = 0} and \eqn{\sigma^2_m = 1}. #' #' Covariance matrix of the latent factors: #' \deqn{\Omega \sim \mathcal{I}nv-\mathcal{W}ishart(K+5, I_K)}{ #' \Omega ~ Inv-Wishart(K+5, I_K)} #' which is rescaled to be a correlation matrix if \code{R.corr = TRUE}: #' \deqn{R = \Lambda^{-1/2} \Omega \Lambda^{-1/2}}{ #' R = \Lambda^-1/2 \Omega \Lambda^-1/2} #' \deqn{\Lambda = diag(\Omega)} #' #' Note that the distribution of the covariance matrix is truncated such that #' all the off-diagonal elements of the implied correlation matrix \eqn{R} are #' below \code{max.corr} in absolute value. The truncation is also applied if #' the covariance matrix is used instead of the correlation matrix (i.e., if #' \code{R.corr = FALSE}). #' #' The distributions and the corresponding default values used to simulate the #' model parameters are specified as in the Monte Carlo study of CFSHP, see #' section 4.1 (p.43). #' #' @return The function returns a data frame with \code{N} observations #' simulated from the corresponding dedicated factor model. #' The parameters used to generate the data are saved as attributes: #' \code{dedic}, \code{alpha}, \code{sigma} and \code{R}. #' #' @author Rémi Piatek \email{remi.piatek@@gmail.com} #' #' @references #' G. Conti, S. Frühwirth-Schnatter, J.J. Heckman, #' R. Piatek (2014): ``Bayesian Exploratory Factor Analysis'', #' \emph{Journal of Econometrics}, 183(1), pages 31-57, #' \doi{10.1016/j.jeconom.2014.06.008}. #' #' @examples #' # generate 1000 observations from model with 4 factors and 20 variables #' # (5 variables loading on each factor) #' dat <- simul.dedic.facmod(N = 1000, dedic = rep(1:4, each = 5)) #' #' # generate data set with 5000 observations from the following model: #' dedic <- rep(1:3, each = 4) # 3 factors and 12 manifest variables #' alpha <- rep(c(1, NA, NA, NA), 3) # set first loading to 1 for each factor, #' # sample remaining loadings from default #' sigma <- rep(0.5, 12) # idiosyncratic variances all set to 0.5 #' R <- toeplitz(c(1, .6, .3)) # Toeplitz matrix #' dat <- simul.dedic.facmod(N = 5000, dedic, alpha, sigma, R) #' #' @export simul.dedic.facmod #' @import checkmate #' @importFrom stats rWishart rnorm runif cov2cor simul.dedic.facmod <- function(N, dedic, alpha, sigma, R, R.corr = TRUE, max.corr = 0.85, R.max.trial = 1000) { # sanity checks for N and dedic, relabel appropriately assertInt(N, lower = 1) assertIntegerish(dedic, lower = 0, any.missing = FALSE, min.len = 3) dedic <- relabel.dedic(dedic) nvar <- length(dedic) nfac <- max(dedic) # factor loading matrix if (missing(alpha)) { alpha <- rep(NA, nvar) } assertNumeric(alpha, finite = TRUE, len = nvar) nna <- sum(is.na(alpha)) if (nna > 0) { alpha[is.na(alpha)] <- sample(c(-1, 1), nna, replace = TRUE) * sqrt(runif(nna, min = 0.04, max = 0.64)) } alpha.mat <- matrix(0, nvar, nfac) for (i in 1:nvar) { if (dedic[i] > 0) alpha.mat[i, dedic[i]] <- alpha[i] } # error terms if (missing(sigma)) sigma <- rep(NA, nvar) assertNumeric(sigma, lower = 0.001, finite = TRUE, len = nvar) nna <- sum(is.na(sigma)) if (nna > 0) sigma[is.na(sigma)] <- runif(nna, min = 0.2, max = 0.8) sigma[dedic == 0] <- 1 eps <- matrix(rnorm(N * nvar), N, nvar) %*% diag(sqrt(sigma)) # latent factors assertLogical(R.corr, len = 1, any.missing = FALSE) assertNumber(max.corr, lower = 0, upper = 1) assertInt(R.max.trial, lower = 1, upper = 10^6) if (missing(R)) { for (i in 1:R.max.trial) { Omega <- rWishart(n = 1, df = nfac + 5, Sigma = diag(nfac)) R <- cov2cor(Omega[, , 1]) rho <- max(abs(R[lower.tri(R)])) if (rho <= max.corr) break } if (rho > max.corr) stop("R.max.trial exceeded, could not sample R") if (!R.corr) R <- Omega } else { if (!is.pos.semidefinite.matrix(R)) stop("R is not positive semidefinite.") if (R.corr & !all(diag(R) == 1)) stop("R is not a correlation matrix") } theta <- matrix(rnorm(N * nfac), N, nfac) %*% chol(R) # manifest variables Y <- theta %*% t(alpha.mat) + eps colnames(Y) <- paste0("Y", 1:nvar) rownames(Y) <- 1:N # label parameters names(dedic) <- paste0("Y", 1:nvar) names(alpha) <- paste0("alpha:", 1:nvar) names(sigma) <- paste0("sigma:", 1:nvar) rownames(R) <- colnames(R) <- paste0("R:", 1:nfac) # return simulated data output <- as.data.frame(Y) attr(output, "dedic") <- dedic attr(output, "alpha") <- alpha attr(output, "sigma") <- sigma attr(output, "R") <- R return(output) }
/scratch/gouwar.j/cran-all/cranData/BayesFM/R/simul.dedic.facmod.R
#' #' Simulate prior distribution of number of latent factors #' #' This function produces a sample from the prior distribution of the number of #' latent factors. It depends on the prior parameters used for the distribution #' of the indicators, on the size of the model (number of manifest variables #' and maximum number of latent factors), and on the identification restriction #' (minimum number of manifest variables dedicated to each factor). #' #' @inheritParams befa #' @param nvar Number of manifest variables. #' @param Kmax Maximum number of latent factors. #' @param kappa Concentration parameter of the Dirichlet prior distribution on #' the indicators. #' @param nrep Number of Monte Carlo replications. #' #' @details This function simulates the prior distribution of the number of #' latent factors for models that fulfill the identification restriction #' restriction that at least \code{Nid} manifest variables (or no variables) are #' loading on each latent factor. Several (scalar) parameters \code{kappa} can #' be passed to the function to simulate the prior for different prior parameter #' values and compare the results. #' #' An accept/reject sampling scheme is used: a vector of probabilities is drawn #' from a Dirichlet distribution with concentration parameter \code{kappa}, and #' the \code{nvar} manifest variables are randomly allocated to the \code{Kmax} #' latent factors. If each latent factor has at least \code{Nid} dedicated #' variables or no variables at all, the identification requirement is fulfilled #' and the draw is accepted. The number of factors loaded by at least \code{Nid} #' manifest variables is returned as a draw from the prior distribution. #' #' Note that this function does not use the two-level prior distribution #' implemented in CFSHP, where manifest variables can be discarded from the #' model according to a given probability. Therefore, this function only help #' understand the prior distribution conditional on all the manifest variables #' being included into the model. #' #' @return A list of length equal to the number of parameters specified in #' \code{kappa} is returned, where each element of the list contains: #' \itemize{ #' \item \code{nfac}: Vector of integers of length equal to the number of #' accepted draws. #' \item \code{acc}: Acceptance rate of the accept/reject sampling scheme. #' } #' #' @author Rémi Piatek \email{remi.piatek@@gmail.com} #' #' @references G. Conti, S. Frühwirth-Schnatter, J.J. Heckman, R. Piatek (2014): #' ``Bayesian Exploratory Factor Analysis'', \emph{Journal of Econometrics}, #' 183(1), pages 31-57, \doi{10.1016/j.jeconom.2014.06.008}. #' #' @examples #' # replicate first row of table 2 in CFSHP (p.44) #' # note: use larger number of replications nrep to improve accuracy #' prior.nfac <- simul.nfac.prior(nvar = 15, Kmax = 5, kappa = c(.3, .7, 1), #' nrep = 10000) #' summary(prior.nfac) #' plot(prior.nfac) #' #' @export simul.nfac.prior #' @import checkmate #' @useDynLib BayesFM, .registration = TRUE, .fixes = "F_" simul.nfac.prior <- function(nvar, Kmax, Nid = 3, kappa = 1/Kmax, nrep = 10^6) { # sanity checks checkArgs <- makeAssertCollection() assertInt(nvar, lower = 1, add = checkArgs) assertInt(Kmax, lower = 1, upper = nvar, add = checkArgs) assertInt(Nid, lower = 1, upper = floor(nvar/Kmax), add = checkArgs) assertNumeric(kappa, lower = 10^-7, finite = TRUE, any.missing = FALSE, min.len = 1, unique = TRUE, add = checkArgs) assertCount(nrep, positive = TRUE, add = checkArgs) reportAssertions(checkArgs) out <- list() for (kap in kappa) { seed <- round(runif(1) * 10^9) sim <- .Fortran(F_simnfacprior, as.integer (nvar), as.integer (Kmax), as.integer (Nid), as.double (rep(kap, Kmax)), as.integer (nrep), as.integer (seed), nfac = integer(nrep), restrid = logical(nrep), PACKAGE = 'BayesFM') lab <- paste('kappa =', kap) out[[lab]] <- list(nfac = sim$nfac[sim$restrid], acc = sum(sim$restrid) / nrep) } attr(out, 'call') <- match.call() attr(out, 'nvar') <- nvar attr(out, 'Kmax') <- Kmax attr(out, 'Nid') <- Nid attr(out, 'kappa') <- kappa attr(out, 'nrep') <- nrep class(out) <- 'simul.nfac.prior' return(out) }
/scratch/gouwar.j/cran-all/cranData/BayesFM/R/simul.nfac.prior.R
#' #' Summarize 'befa' object #' #' Generic function summarizing the posterior results of a 'befa' object. #' Optional arguments can be specified to customize the summary. #' #' @param object #' Object of class 'befa'. #' @param ... #' The following extra arguments can be specified: #' \itemize{ #' \item \code{what}: How to summarize the posterior distribution? #' \itemize{ #' \item \code{what = 'maxp'} (default): Only factor loadings with #' highest posterior probability of being different from zero or #' discarded from the model (if \code{dedic = 0}) are #' summarized. #' \item \code{what = 'all'}: All factor loadings with corresponding #' posterior probability to be allocated to a given factor (or #' to be discarded from the model) larger than \code{min.prob} #' are summarized. #' \item \code{what = 'hppm'}: Highest posterior probability models #' with probability larger than \code{min.prob} are summarized. #' } #' \item \code{byfac}: Sort factor loadings by factors if \code{TRUE}, #' otherwise by manifest variables if \code{FALSE} (default). #' \item \code{hpd.prob}: Probability used to compute the highest posterior #' density intervals of the posterior distribution of the model #' parameters (default: 0.95). #' \item \code{min.prob}: If \code{what = 'all'}, only factor loadings with #' posterior probability of being dedicated to a given factor (or #' discarded from the model) larger than this value are displayed. #' If \code{what = 'hppm'}, only highest posterior probability models #' with probability larger than this value are displayed. (default: #' 0.20) #' } #' #' @details #' This function summarizes the posterior distribution of the parameters. #' The algorithm may visit different configurations of the indicator matrix #' \eqn{\Delta} during sampling, where the manifest variables are allocated to #' different latent factors. When the posterior distribution of the factor #' loadings is summarized separately for each manifest variable #' (\code{what = 'maxp'} or \code{what = 'all'}), the function provides the #' latent factor each manifest variable is allocated to (\code{dedic}), and the #' corresponding posterior probability (\code{prob}). If \code{dedic = 0}, then #' \code{prob} corresponds to the posterior probability that the manifest #' variable is discarded. Discarded variables are listed last if #' \code{byfac = TRUE}. Low probability cases can be discarded by setting #' \code{min.prob} appropriately (default is 0.20). #' #' Idiosyncratic variances, factor correlation matrix and regression #' coefficients (if any) are summarized across all MCMC iterations if #' \code{what = 'all'} or \code{what = 'maxp'}, and within each HPP model if #' \code{what = 'hppm'}. #' #' \strong{Highest posterior probability model.} #' The HPP model is the model with a given allocation of the measurements to the #' latent factors (i.e., a given indicator matrix \eqn{\Delta}) that is visited #' most often by the algorithm. #' #' When specifying \code{what = 'hppm'}, the function sorts the models according #' to the posterior frequencies of their indicator matrices in decreasing order. #' Therefore, the first model returned (labeled 'm1') corresponds to the HPP #' model. #' Low probability models can be discarded by setting \code{min.prob} #' appropriately(default is 0.20, implying that only models with a posterior #' probability larger than 0.20 are displayed). #' #' HPP models can only be found if identification with respect to column #' switching has been restored \emph{a posteriori}. An error message is returned #' if this is not the case. #' #' @return If called directly, the summary is formatted and displayed on the #' standard output. Otherwise if saved in an object, a list of the following #' elements is returned: #' \itemize{ #' \item \code{MHacc}: Metropolis-Hastings acceptance rate. #' \item \code{alpha}: Data frame (or list of data frames if #' \code{what = 'hppm'}) containing posterior summary statistics for the #' factor loadings. #' \item \code{sigma}: Data frame (or list of matrices if \code{what = 'hppm'}) #' containing posterior summary statistics for the idiosyncratic #' variances. #' \item \code{R}: Data frame (or list of data frames if \code{what = 'hppm'}) #' containing posterior summary statistics for the factor correlations. #' \item \code{beta}: Data frame (or list of data frames if #' \code{what = 'hppm'}) containing posterior summary statistics for the #' regression coefficients (if any). #' \item \code{nfac} (only if \code{what = 'maxp'} or \code{what = 'all'}): #' Table of posterior frequencies of numbers of factors. #' \item \code{hppm} (only if \code{what = 'hppm'}): List of the following #' elements summarizing the different HPP models, sorted in decreasing #' order of their posterior probabilities: #' \itemize{ #' \item \code{prob}: Vector of posterior probabilities. #' \item \code{nfac}: Vector of numbers of factors. #' \item \code{dedic}: Data frame of factor indicators. #' } #' } #' Data frames of posterior summary statistics include the means (\code{mean}), #' standard deviations (\code{sd}) and highest posterior density intervals #' (\code{hpd.lo} and \code{hpd.up}, for the probability specified in #' \code{hpd.prob}) of the corresponding parameters. #' #' For the factor loadings, the matrix may also include a column labeled #' '\code{dedic}' indicating to which factors the corresponding manifest #' variables are dedicated (a zero value means that the manifest variable does #' not load on any factor), as well as a column labeled '\code{prob}' showing #' the corresponding posterior probabilities that the manifest variables load on #' these factors. #' #' Summary results are returned as lists of data frames for HPP models, where #' the elements of the list are labeled as '\code{m1}, '\code{m2}', etc. #' #' @author Rémi Piatek \email{remi.piatek@@gmail.com} #' #' @seealso \code{\link{plot.befa}} to plot posterior results. #' #' @examples #' set.seed(6) #' #' # generate fake data with 15 manifest variables and 3 factors #' Y <- simul.dedic.facmod(N = 100, dedic = rep(1:3, each = 5)) #' #' # run MCMC sampler and post process output #' # notice: 1000 MCMC iterations for illustration purposes only, #' # increase this number to obtain reliable posterior results! #' mcmc <- befa(Y, Kmax = 5, iter = 1000) #' mcmc <- post.column.switch(mcmc) #' mcmc <- post.sign.switch(mcmc) #' #' # summarize posterior results #' summary(mcmc) #' #' # summarize highest posterior probability (HPP) model #' hppm.sum <- summary(mcmc, what = 'hppm') #' #' # print summary with 6-digit precision #' print(hppm.sum, digits = 6) #' #' # extract posterior means of the factor loadings in HPP model #' alpha.mean <- hppm.sum$alpha$m1$mean #' print(alpha.mean) #' #' @examples \dontshow{ #' summary(mcmc, what = 'maxp', byfac = TRUE) #' summary(mcmc, what = 'all') #' summary(mcmc, what = 'all', byfac = TRUE) #' summary(mcmc, what = 'all', min.prob = 0) #' summary(mcmc, what = 'all', min.prob = 0, byfac = TRUE) #' summary(mcmc, what = 'hppm', byfac = TRUE) #' summary(mcmc, what = 'hppm', min.prob = 0) #' summary(mcmc, what = 'hppm', min.prob = 0, byfac = TRUE) #' } #' #' @export #' @import checkmate #' @importFrom stats sd #' @importFrom coda as.mcmc HPDinterval #' @importFrom plyr count summary.befa <- function(object, ...) { if (class(object) != 'befa') stop('object passed to print.befa should be of class befa') # extra arguments args <- list(...) min.prob <- ifelse (is.null(args$min.prob), .20, args$min.prob) hpd.prob <- ifelse (is.null(args$hpd.prob), .95, args$hpd.prob) byfac <- ifelse (is.null(args$byfac), FALSE, args$byfac) assertNumber(min.prob, lower = 0, upper = 1) assertNumber(hpd.prob, lower = 0, upper = 1) assertFlag(byfac) what <- match.arg(args$what, choices = c('maxp', 'all', 'hppm')) # container for summary object output <- list() ### column-switching and/or sign-switching problems if (!attr(object, "post.column.switch")) { warning("MCMC output not processed by function 'post.column.switch'. ", "Posterior results for factor loadings and factor correlations ", "may not be interpretable! Make sure column-switching problem has ", "been fixed before summarizing.\n", immediate. = TRUE) if (what == 'hppm') stop("Highest posterior probability model (hppm) can only be searched ", " for if columns have be reordered a posteriori. Use function ", "'post.column.switch' first.\n") } if (!attr(object, "post.sign.switch")) { warning("MCMC output not processed by function 'post.sign.switch'. ", "Posterior results for factor loadings and factor correlations ", "may not be interpretable! Make sure sign-switching problem has ", "been fixed before summarizing.\n", immediate. = TRUE) } ### Metropolis-Hastings acceptance rate output$MHacc <- mean(object$MHacc) if (output$MHacc < .2) warning('Metropolis-Hastings acceptance rate is low (< 0.20). ', 'Check convergence and mixing before summarizing.', immediate. = TRUE) ### function summarizing draws from posterior iter <- attr(object, 'iter') summarize.mcmc <- function(z, prob = FALSE) { if (length(z) == 1) { sd <- 0 hpd <- c(NA, NA) } else { sd <- sd(z) hpd <- coda::HPDinterval(coda::as.mcmc(z), prob = hpd.prob) } res <- c(mean = mean(z), sd = sd, hpd.lo = hpd[1], hpd.up = hpd[2]) if (prob) res <- c(prob = length(z)/iter, res) return(res) } ### function sorting manifest variables according to the factors they load on ### (variables loading on no factors are listed last) sort.byfac <- function(a) { a[a[, 'dedic'] == 0, 'dedic'] <- NA # make 0 -> NA a <- a[order(a[, 'dedic'], na.last = TRUE), ] # sort, putting NAs last a[is.na(a[, 'dedic']), 'dedic'] <- 0 # make NA -> 0 return(a) } ### highest posterior probability models if (what == 'hppm') { alpha <- object$alpha dedic <- object$dedic dedic.tab <- plyr::count(as.data.frame(dedic)) dedic.tab <- dedic.tab[order(dedic.tab$freq, decreasing = TRUE),] if (dedic.tab$freq[1] < iter*min.prob) stop('Probability of HPP model lower than min.prob. ', 'Try to decrease the value of min.prob') dedic.tab <- dedic.tab[dedic.tab$freq >= iter*min.prob,] hppm.freq <- dedic.tab$freq/iter hppm.dedic <- dedic.tab[-length(dedic.tab)] hppm.dedic <- as.data.frame(t(hppm.dedic)) colnames(hppm.dedic) <- paste0('m', 1:ncol(hppm.dedic)) hppm.nfac <- apply(hppm.dedic, 2, count.unique.nonzero) output$hppm <- list(prob = hppm.freq, nfac = hppm.nfac, dedic = hppm.dedic) output$alpha <- list() output$sigma <- list() output$R <- list() if (!is.null(object$beta)) output$beta <- list() for (i in seq_along(hppm.freq)) { if (hppm.freq[i] < min.prob) break hppm.id <- apply(t(dedic) == hppm.dedic[,i], 2, all) a <- apply(alpha[hppm.id, , drop = FALSE], 2, summarize.mcmc) a <- cbind(dedic = hppm.dedic[,i], t(a)) if (byfac) a <- sort.byfac(a) rownames(a) <- colnames(alpha) lab <- paste0('m', i) output$alpha[[lab]] <- a output$sigma[[lab]] <- t(apply(object$sigma[hppm.id, , drop = FALSE], 2, summarize.mcmc)) output$R[[lab]] <- t(apply(object$R[hppm.id, , drop = FALSE], 2, summarize.mcmc)) if (!is.null(object$beta)) output$beta[[lab]] <- t(apply(object$beta[hppm.id, , drop = FALSE], 2, summarize.mcmc)) } if (length(output$alpha) == 0) stop("No hpp model found! Try to decrease value of 'min.prob'.") # factor loadings: insert NA values when not dedicated to any factor for (i in 1:length(output$alpha)) for (j in 1:nrow(output$alpha[[i]])) { if (output$alpha[[i]][j, 'dedic'] == 0) output$alpha[[i]][j, c('mean', 'sd', 'hpd.lo', 'hpd.up')] <- NA } ### general case (not HPP models) } else { alpha <- mat2list(object$alpha) dedic <- mat2list(object$dedic) # posterior number of latent factors iter <- nrow(object$dedic) nfac <- table(object$nfac)/iter output$nfac <- nfac[nfac >= .05] # discard if prob < 0.05 # summarize posterior results for loadings if (what == 'all') { bysum <- function(x, d) by(x, d, summarize.mcmc, prob = TRUE) a <- mapply(bysum, alpha, dedic, SIMPLIFY = FALSE) a <- lapply(a, function(x) do.call(rbind, x)) a <- lapply(a, function(x) cbind(dedic = as.integer(rownames(x)), x)) for(i in 1:length(a)) rownames(a[[i]]) <- rep(names(a)[i], nrow(a[[i]])) a <- do.call(rbind, a) a <- a[a[, 'prob'] >= min.prob,] # drop rows for which prob < min.prob } else if (what == 'maxp') { get.max <- function(x) as.integer(names(which.max(table(x)))) dhp <- sapply(dedic, get.max) hpsum <- function(x, d, dhp) summarize.mcmc(x[d == dhp], prob = TRUE) a <- t(mapply(hpsum, alpha, dedic, dhp)) a <- cbind(dedic = dhp, a) rownames(a) <- names(alpha) } if (byfac) a <- sort.byfac(a) output$alpha <- a # summarize posterior results for remaining parameters output$sigma <- t(apply(object$sigma, 2, summarize.mcmc)) output$R <- t(apply(object$R, 2, summarize.mcmc)) if (!is.null(object$beta)) output$beta <- t(apply(object$beta, 2, summarize.mcmc)) # factor loadings: insert NA values when not dedicated to any factor for (i in 1:nrow(output$alpha)) if (output$alpha[i, 'dedic'] == 0) output$alpha[i, c('mean', 'sd', 'hpd.lo', 'hpd.up')] <- NA } # convert parameter summaries to data frames, # rename duplicate row names if necessary (esp. for factor loadings) mdf <- function(x) as.data.frame(x, row.names = make.unique(rownames(x))) if (what == 'hppm') { output$alpha <- lapply(output$alpha, mdf) output$sigma <- lapply(output$sigma, mdf) output$R <- lapply(output$R, mdf) if (!is.null(output$beta)) output$beta <- lapply(output$beta, mdf) } else { output$alpha <- mdf(output$alpha) output$sigma <- mdf(output$sigma) output$R <- mdf(output$R) if (!is.null(output$beta)) output$beta <- mdf(output$beta) } ### save attributes and return object attr(output, 'Kmax') <- attr(object, 'Kmax') attr(output, 'Nid') <- attr(object, 'Nid') attr(output, 'iter') <- attr(object, 'iter') attr(output, 'burnin') <- attr(object, 'burnin') attr(output, 'what') <- what attr(output, 'min.prob') <- min.prob attr(output, 'hpd.prob') <- hpd.prob attr(output, 'byfac') <- byfac class(output) <- "summary.befa" return(output) }
/scratch/gouwar.j/cran-all/cranData/BayesFM/R/summary.befa.R
#' @export #' @import checkmate #' @importFrom stats median sd quantile summary.simul.R.prior <- function(object, ...) { args <- list(...) if (is.null(args$probs)) { probs <- c(.05, .1, .25, .75, .9, .95) } else { probs <- args$probs } assertNumeric(probs, lower = 0, upper = 1, any.missing = FALSE, min.len = 1) sum.prior <- function(x, FUN) { val <- lapply(x, function(z) apply(z, 3, FUN)) stat <- lapply(val, function(z) return(c(mean = mean(z), median = median(z), sd = sd(z), min = min(z), max = max(z)))) quant <- lapply(val, quantile, probs) res <- list(stat = do.call(rbind, stat), quant = do.call(rbind, quant)) res <- lapply(res, round, digits = 3) return(res) } out <- list(maxcor = sum.prior(object, get.maxcor), mineig = sum.prior(object, get.mineig)) class(out) <- 'summary.simul.R.prior' return(out) }
/scratch/gouwar.j/cran-all/cranData/BayesFM/R/summary.simul.R.prior.R
#' @export summary.simul.nfac.prior <- function(object, ...) { Kmax <- attr(object, 'Kmax') comp.freq <- function(x) table(factor(x, levels = 1:Kmax))/length(x) acc <- lapply(object, '[[', 'acc') nfac <- lapply(object, '[[', 'nfac') nfac <- lapply(nfac, comp.freq) out <- list(nfac = nfac, acc = acc) class(out) <- 'summary.simul.nfac.prior' return(out) }
/scratch/gouwar.j/cran-all/cranData/BayesFM/R/summary.simul.nfac.prior.R
### check if object is a formula is.formula <- function(x) return(class(x) == "formula") ### check if matrix is positive semidefinite is.pos.semidefinite.matrix <- function(x) { if (!is.matrix(x)) return(FALSE) if (!isSymmetric(x, tol = 10^-9)) return(FALSE) return(all(eigen(x, only.values = TRUE)$values >= 0)) } ### check if matrix can be inverted is.invertible.matrix <- function(x) { return(class(try(solve(x), silent = TRUE))[1L] == "matrix") } ### relabel indicators for dedicated factor model ### example: ### > d <- c(6, 6, 6, 2, 2, 2, 0, 0, 4, 4, 4) ### > relabel(d) [1] 1 1 1 2 2 2 0 0 3 3 3 relabel.dedic <- function(d) { u <- unique(d[d != 0]) t <- rep(0, max(d)) t[u] <- 1:length(u) d[d != 0] <- t[d] return(d) } ### count number of unique nonzero elements in x count.unique.nonzero <- function(x) return(length(unique(x[x != 0]))) ### convert matrix to list mat2list <- function(x, byrow = FALSE) { if (byrow) { y <- split(x, c(row(x))) names(y) <- rownames(x) } else { y <- split(x, c(col(x))) names(y) <- colnames(x) } return(y) } ### get maximum correlation (in absolute value) from correlation matrix get.maxcor <- function(x) max(abs(x[lower.tri(x)])) ### get minimum eigenvalue of symmetric matrix get.mineig <- function(x) min(eigen(x, symmetric = TRUE, only.values = TRUE)$values)
/scratch/gouwar.j/cran-all/cranData/BayesFM/R/utils.R
#'Functions to compute Bayes factor hypothesis tests for common research designs #'and hypotheses. #' #'This package contains function to compute Bayes factors for a number of #'research designs and hypotheses, including t tests, ANOVA, and linear #'regression, correlations, proportions, and contingency tables. #' #'\tabular{ll}{ Package: \tab BayesFactor\cr Type: \tab Package\cr Version: \tab #'0.9.12-4.7\cr Date: \tab 2024-01-23\cr License: \tab GPL 2.0\cr LazyLoad: \tab #'yes\cr } The following methods are currently implemented, with more to follow: #' #'general linear models (including linear mixed effects models): \code{\link{generalTestBF}}, \code{\link{lmBF}} #' #'linear regression: \code{\link{regressionBF}}, \code{\link{lmBF}}, #'\code{\link{linearReg.R2stat}}; #' #'linear correlation: \code{\link{correlationBF}}; #' #'t tests: \code{\link{ttestBF}}, \code{\link{ttest.tstat}}; #' #'meta-analytic t tests: \code{\link{meta.ttestBF}} #' #'ANOVA: \code{\link{anovaBF}}, \code{\link{lmBF}}, \code{\link{oneWayAOV.Fstat}}; #' #'contingency tables: \code{\link{contingencyTableBF}}; #' #'single proportions: \code{\link{proportionBF}}; #' #'linear correlations: \code{\link{correlationBF}}; #' #'Other useful functions: \code{\link{posterior}}, for sampling from posterior #'distributions; \code{\link{recompute}}, for re-estimating a Bayes factor or #'posterior distribution; \code{\link{compare}}, to compare two model #'posteriors; and \code{\link{plot.BFBayesFactor}}, for plotting Bayes factor #'objects. #' #'@name BayesFactor-package #'@aliases BayesFactor-package BayesFactor #'@docType package #'@author Richard D. Morey and Jeffrey N. Rouder (with contributions from Tahira Jamil) #' #' Maintainer: Richard D. Morey <richarddmorey@@gmail.com> #'@references Liang, F. and Paulo, R. and Molina, G. and Clyde, M. A. and #' Berger, J. O. (2008). Mixtures of g-priors for Bayesian Variable Selection. #' Journal of the American Statistical Association, 103, pp. 410-423 #' #' Rouder, J. N., Speckman, P. L., Sun, D., Morey, R. D., and Iverson, G. #' (2009). Bayesian t-tests for accepting and rejecting the null hypothesis. #' Psychonomic Bulletin & Review, 16, 225-237 #' #' Rouder, J. N., Morey, R. D., Speckman, P. L., Province, J. M., (2012) #' Default Bayes Factors for ANOVA Designs. Journal of Mathematical Psychology. #' 56. p. 356-374. #' #'@keywords htest #'@examples #' #'## See specific functions for examples. #' #'@useDynLib BayesFactor NULL #'Puzzle completion times from Hays (1994) #' #'Puzzle completion time example data from Hays (1994). #' #'Hays (1994; section 13.21, table 13.21.2, p. 570) describes a experiment #'wherein 12 participants complete four puzzles each. Puzzles could be either #'square or round, and either monochromatic or in color. Each participant #'completed every combination of the two factors. #' #'@name puzzles #'@docType data #'@format A data frame with 48 observations on 3 variables. \describe{ #'\item{RT}{Puzzle completion time, in minutes} \item{ID}{the #'subject identifier} \item{shape}{shape of the puzzle (round or #'square)} \item{color}{color content of the puzzle (monochromatic or #'color)} } #'@source Hays, W. L. (1994), Statistics (5th edition), Harcourt Brace, Fort #'Worth, Texas #'@keywords datasets #'@examples #' #'data(puzzles) #' #'## classical ANOVA #'## Both color and shape are significant, interaction is not #'classical <- aov(RT ~ shape*color + Error(ID/(shape*color)), data=puzzles) #'summary(classical) #' #'## Bayes Factor #'## Best model is main effects model, no interaction #' anovaBF(RT ~ shape*color + ID, data = puzzles, whichRandom = "ID", progress=FALSE) #' #' NULL #'Hraba and Grant (1970) children's doll preference data #' #'Hraba and Grant (1970) describe a replication of Clark and Clark (1947) in which #'black and white children from Lincoln, Nebraska were shown dolls that were either black #'or white. They were then asked a series of questions, including "Give me the doll that is #'a nice doll." This data set contains the frequency of children giving the same-race or different race doll in #'response to this question. #'@name raceDolls #'@docType data #'@format A matrix with 2 rows and 2 columns. Rows give doll preference; colums give the #'race of the child. #'@source Hraba, J. and Grant, G. (1970). Black is Beautiful: A reexamination of #'racial preference and identification. Journal of Personality and Social Psychology, 16, 398-402. #' #'@keywords datasets #'@examples #' #'data(raceDolls) #' #'## chi-square test #'## Barely significant with continuity correction #'chisq.test(raceDolls) #' #'## Bayes factor test (assuming independent binomial sampling plan) #'## Very little evidence for the alternative of lack of independence #'bf = contingencyTableBF(raceDolls, sampleType = "indepMulti", fixedMargin = "cols") #'bf NULL
/scratch/gouwar.j/cran-all/cranData/BayesFactor/R/BayesFactorPCL-package.R
# Generated by using Rcpp::compileAttributes() -> do not edit by hand # Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 hFunc <- function(rho, n, r, hg_checkmod, hg_iter) { .Call('_BayesFactor_hFunc', PACKAGE = 'BayesFactor', rho, n, r, hg_checkmod, hg_iter) } jeffreys_approx_corr <- function(rho, n, r) { .Call('_BayesFactor_jeffreys_approx_corr', PACKAGE = 'BayesFactor', rho, n, r) } metropCorrRcpp_jeffreys <- function(r, n, a_prior, b_prior, approx, iterations, doInterval, intervalz, intervalCompl, nullModel, progress, callback, callbackInterval) { .Call('_BayesFactor_metropCorrRcpp_jeffreys', PACKAGE = 'BayesFactor', r, n, a_prior, b_prior, approx, iterations, doInterval, intervalz, intervalCompl, nullModel, progress, callback, callbackInterval) } dinvgamma1_Rcpp <- function(x, a, b) { .Call('_BayesFactor_dinvgamma1_Rcpp', PACKAGE = 'BayesFactor', x, a, b) } dinvgamma1_logx_Rcpp <- function(x, a, b) { .Call('_BayesFactor_dinvgamma1_logx_Rcpp', PACKAGE = 'BayesFactor', x, a, b) } ddinvgamma1_Rcpp <- function(x, a, b) { .Call('_BayesFactor_ddinvgamma1_Rcpp', PACKAGE = 'BayesFactor', x, a, b) } d2dinvgamma1_Rcpp <- function(x, a, b) { .Call('_BayesFactor_d2dinvgamma1_Rcpp', PACKAGE = 'BayesFactor', x, a, b) } genhypergeo_series_pos <- function(U, L, z, tol, maxiter, check_mod, check_conds, polynomial) { .Call('_BayesFactor_genhypergeo_series_pos', PACKAGE = 'BayesFactor', U, L, z, tol, maxiter, check_mod, check_conds, polynomial) } jzs_log_marginal_posterior_logg <- function(q, sumSq, N, XtCnX0, CnytCnX0, rscale, gMap, gMapCounts, priorX, incCont, limit, limits, which) { .Call('_BayesFactor_jzs_log_marginal_posterior_logg', PACKAGE = 'BayesFactor', q, sumSq, N, XtCnX0, CnytCnX0, rscale, gMap, gMapCounts, priorX, incCont, limit, limits, which) } jzs_Gibbs <- function(iterations, y, X, rscale, sig2start, gMap, gMapCounts, incCont, nullModel, ignoreCols, thin, progress, callback, callbackInterval) { .Call('_BayesFactor_jzs_Gibbs', PACKAGE = 'BayesFactor', iterations, y, X, rscale, sig2start, gMap, gMapCounts, incCont, nullModel, ignoreCols, thin, progress, callback, callbackInterval) } jzs_sampler <- function(iterations, y, X, rscale, gMap, incCont, importanceMu, importanceSig, progress, callback, callbackInterval, which) { .Call('_BayesFactor_jzs_sampler', PACKAGE = 'BayesFactor', iterations, y, X, rscale, gMap, incCont, importanceMu, importanceSig, progress, callback, callbackInterval, which) } GibbsLinearRegRcpp <- function(iterations, y, X, r, sig2start, nullModel, progress, callback, callbackInterval) { .Call('_BayesFactor_GibbsLinearRegRcpp', PACKAGE = 'BayesFactor', iterations, y, X, r, sig2start, nullModel, progress, callback, callbackInterval) } log_determinant_pos_def <- function(A) { .Call('_BayesFactor_log_determinant_pos_def', PACKAGE = 'BayesFactor', A) } logSummaryStats <- function(x) { .Call('_BayesFactor_logSummaryStats', PACKAGE = 'BayesFactor', x) } log1pExp <- function(x) { .Call('_BayesFactor_log1pExp', PACKAGE = 'BayesFactor', x) } logExpXplusExpY <- function(x, y) { .Call('_BayesFactor_logExpXplusExpY', PACKAGE = 'BayesFactor', x, y) } logExpXminusExpY <- function(x, y) { .Call('_BayesFactor_logExpXminusExpY', PACKAGE = 'BayesFactor', x, y) } metropMetaTRcpp <- function(t, n1, n2, twoSample, rscale, iterations, doInterval, interval, intervalCompl, nullModel, progress, callback, callbackInterval) { .Call('_BayesFactor_metropMetaTRcpp', PACKAGE = 'BayesFactor', t, n1, n2, twoSample, rscale, iterations, doInterval, interval, intervalCompl, nullModel, progress, callback, callbackInterval) } metropProportionRcpp <- function(y, n, p0, rscale, iterations, doInterval, interval, intervalCompl, nullModel, progress, callback, callbackInterval) { .Call('_BayesFactor_metropProportionRcpp', PACKAGE = 'BayesFactor', y, n, p0, rscale, iterations, doInterval, interval, intervalCompl, nullModel, progress, callback, callbackInterval) } gibbsTwoSampleRcpp <- function(ybar, s2, N, rscale, iterations, doInterval, interval, intervalCompl, nullModel, progress, callback, callbackInterval) { .Call('_BayesFactor_gibbsTwoSampleRcpp', PACKAGE = 'BayesFactor', ybar, s2, N, rscale, iterations, doInterval, interval, intervalCompl, nullModel, progress, callback, callbackInterval) } gibbsOneSampleRcpp <- function(ybar, s2, N, rscale, iterations, doInterval, interval, intervalCompl, nullModel, progress, callback, callbackInterval) { .Call('_BayesFactor_gibbsOneSampleRcpp', PACKAGE = 'BayesFactor', ybar, s2, N, rscale, iterations, doInterval, interval, intervalCompl, nullModel, progress, callback, callbackInterval) } # Register entry points for exported C++ functions methods::setLoadAction(function(ns) { .Call('_BayesFactor_RcppExport_registerCCallable', PACKAGE = 'BayesFactor') })
/scratch/gouwar.j/cran-all/cranData/BayesFactor/R/RcppExports.R
# https://stat.ethz.ch/pipermail/r-devel/2010-May/057506.html ## for 'i' in x[i] or A[i,] : (numeric = {double, integer}) # setClassUnion("index", members = c("numeric", "logical", "character")) #' General S4 classes for representing models for comparison #' #' The \code{BFmodel} is a general S4 class for representing models for comparison. The more classes #' \code{BFlinearModel}, \code{BFindepSample}, and \code{BFoneSample} inherit directly from \code{BFmodel}. #' #' \describe{ #' These model classes all have the following slots defined: #' \item{type}{Model type} #' \item{identifier}{a list uniquely identifying the model from other models of the same type} #' \item{prior}{list giving appropriate prior settings for the model} #' \item{dataTypes}{a character vector whose names are possible columns in the data; elements specify the corresponding data type, currently one of c("fixed","random","continuous")} #' \item{shortName}{a short, readable identifying string} #' \item{longName}{a longer, readable identifying string} #' \item{analysis}{object storing information about a previous analysis of this model} #' \item{version}{character string giving the version and revision number of the package that the model was created in} #' } #' @name BFmodel-class #' @rdname model-classes #' @export setClass("BFmodel", representation( type = "character", identifier = "list", prior = "list", dataTypes = "character", shortName = "character", longName = "character", analysis = "list", version = "character" )) #' @name BFcorrelation-class #' @rdname model-classes setClass("BFcorrelation", contains = "BFmodel") #' @name BFproportion-class #' @rdname model-classes setClass("BFproportion", contains = "BFmodel") #' @name BFcontingencyTable-class #' @rdname model-classes setClass("BFcontingencyTable", contains = "BFmodel") #' @name BFlinearModel-class #' @rdname model-classes setClass("BFlinearModel", contains = "BFmodel") #' @name BFoneSample-class #' @rdname model-classes setClass("BFoneSample", contains = "BFlinearModel") #' @name BFoneSample-class #' @rdname model-classes setClass("BFmetat", contains = "BFmodel") #' @name BFindepSample-class #' @rdname model-classes setClass("BFindepSample", contains = "BFlinearModel") #' General S4 class for representing multiple Bayes factor model comparisons, all against the same model #' #' The \code{BFBayesFactor} class is a general S4 class for representing models model comparison via Bayes factor. #' #' \code{BFBayesFactor} objects can be inverted by taking the reciprocal and can #' be divided by one another, provided both objects have the same denominator. In addition, #' the \code{t} (transpose) method can be used to invert Bayes factor objects. #' \describe{ #' The \code{BFBayesFactor} class has the following slots defined: #' \item{numerator}{a list of models all inheriting \code{BFmodel}, each providing a single denominator} #' \item{denominator}{a single \code{BFmodel} object serving as the denominator for all model comparisons} #' \item{bayesFactor}{a data frame containing information about the comparison between each numerator and the denominator} #' \item{data}{a data frame containing the data used for the comparison} #' \item{version}{character string giving the version and revision number of the package that the model was created in} #' } #' @name BFBayesFactor-class #' @export #' @examples #' ## Compute some Bayes factors to demonstrate division and indexing #' data(puzzles) #' bfs <- anovaBF(RT ~ shape*color + ID, data = puzzles, whichRandom = "ID", progress=FALSE) #' #' ## First and second models can be separated; they remain BFBayesFactor objects #' b1 = bfs[1] #' b2 = bfs[2] #' b1 #' #' ## We can invert them, or divide them to obtain new model comparisons #' 1/b1 #' b1 / b2 #' #' ## Use transpose to create a BFBayesFactorList #' t(bfs) setClass("BFBayesFactor", representation( numerator = "list", denominator = "BFmodel", bayesFactor = "data.frame", data = "data.frame", version = "character" )) #' General S4 class for representing a collection of Bayes factor model #' comprisons, each against a different denominator #' #' The \code{BFBayesFactorList} class is a general S4 class for representing #' models model comparison via Bayes factor. See the examples for demonstrations #' of BFBayesFactorList methods. #' #' \describe{ \code{BFBayesFactorList} objects inherit from lists, and contain a #' single slot: #' #' \item{version}{character string giving the version and revision number of the #' package that the model was created in} #' #' Each element of the list contains a single #' \code{"\link[=BFBayesFactor-class]{BFBayesFactor}"} object. Each element of #' the list must have the same numerators, in the same order, as all the others. #' The list object is displayed as a matrix of Bayes factors. } #' @name BFBayesFactorList-class #' @export #' @examples #' ## Compute some Bayes factors to demonstrate Bayes factor lists #' data(puzzles) #' bfs <- anovaBF(RT ~ shape*color + ID, data = puzzles, whichRandom = "ID", progress=FALSE) #' #' ## Create a matrix of Bayes factors #' bfList <- bfs / bfs #' bfList #' #' ## Use indexing to select parts of the 'matrix' #' bfList[1,] #' bfList[,1] #' #' ## We can use the t (transpose) function as well, to get back a BFBayesFactor #' t(bfList[2,]) #' #' ## Or transpose the whole matrix #' t(bfList) setClass("BFBayesFactorList", contains = "list", representation(version="character")) #' @name BFBayesFactorTop-class #' @rdname BFBayesFactor-class setClass("BFBayesFactorTop", contains = "BFBayesFactor") setOldClass("mcmc") setClass("BFmcmc", contains = "mcmc", representation(model="BFmodel",data = "data.frame")) setClassUnion("BFOrNULL", members = c("BFBayesFactor", "NULL")) #' General S4 class for representing multiple odds model comparisons, all against the same model #' #' The \code{BFodds} class is a general S4 class for representing models model comparison via prior or posterior odds. #' #' \code{BFodds} objects can be inverted by taking the reciprocal and can #' be divided by one another, provided both objects have the same denominator. In addition, #' the \code{t} (transpose) method can be used to invert odds objects. #' \describe{ #' The \code{BFodds} class has the following slots defined: #' \item{numerator}{a list of models all inheriting \code{BFmodel}, each providing a single numerator} #' \item{denominator}{a single \code{BFmodel} object serving as the denominator for all model comparisons} #' \item{logodds}{a data frame containing information about the (log) prior odds between each numerator and the denominator} #' \item{bayesFactor}{a \code{BFBayesFactor} object (possibly) containing the evidence from the data.} #' \item{version}{character string giving the version and revision number of the package that the model was created in} #' } #' @name BFodds-class #' @export setClass("BFodds", representation( numerator = "list", denominator = "BFmodel", logodds = "data.frame", bayesFactor = "BFOrNULL", version = "character" )) #' General S4 class for representing multiple model probability comparisons #' #' The \code{BFprobability} class is a general S4 class for representing models model comparison via prior or posterior probabilities. #' #' \describe{ #' The \code{BFprobability} class has the following slots defined: #' \item{odds}{A BFodds object containing the models from which to compute the probabilities} #' \item{normalize}{the sum of the probabilities of all models (will often be 1.0)} #' \item{version}{character string giving the version and revision number of the package that the model was created in} #' } #' @name BFprobability-class #' @export setClass("BFprobability", representation( odds = "BFodds", normalize = "numeric", version = "character" ))
/scratch/gouwar.j/cran-all/cranData/BayesFactor/R/aaClasses.R
#' Compare two objects to see if they are the 'same', for some loose definition #' of same #' @param x first object #' @param y second object #' @return Returns \code{TRUE} or \code{FALSE} setGeneric("%same%", function(x, y) standardGeneric("%same%")) #' Find a model term in a vector of model terms #' @param x the terms to be matched #' @param table the terms to be matched against #' @return A logical vector of the same length as x, indicating if a #' match was located for each element of x. setGeneric("%termin%", function(x, table) standardGeneric("%termin%")) #' Compare two models, with respect to some data #' #' This method is used primarily in the backend, and will only rarely be called #' by the end user. But see the examples below for a demonstration. #' @param numerator first model #' @param denominator second model (if omitted, compare to predefined null) #' @param data data for the comparison #' @param ... arguments passed to and from related methods #' @return The compare function will return a model comparison object, typically #' a Bayes factor #' @export #' @docType methods #' @rdname compare-methods #' @aliases compare,BFoneSample,missing,data.frame-method #' compare,BFlinearModel,BFlinearModel,data.frame-method #' compare,BFindepSample,missing,data.frame-method #' compare,BFlinearModel,missing,data.frame-method #' compare,BFmetat,missing,data.frame-method #' compare,BFproportion,missing,data.frame-method #' compare,BFcontingencyTable,BFcontingencyTable,data.frame-method #' compare,BFcontingencyTable,missing,data.frame-method #' compare,BFcorrelation,missing,data.frame-method #' compare,BFmcmc,BFmcmc,ANY-method #' compare,BFmcmc,missing,ANY-method #' @examples #' ## Sample from the posteriors for two models #' data(puzzles) #' #' ## Main effects model; result is a BFmcmc object, inheriting #' ## mcmc from the coda package #' mod1 = lmBF(RT ~ shape + color + ID, data = puzzles, whichRandom = "ID", #' progress = FALSE, posterior = TRUE, iterations = 1000) #' #' plot(mod1) #' #' ## Full model #' mod2 = lmBF(RT ~ shape*color + ID, data = puzzles, whichRandom = "ID", #' progress = FALSE, posterior = TRUE, iterations = 1000) #' #' ## Each BFmcmc object contains the model used to generate it, so we #' ## can compare them (data is not needed, it is contained in the objects): #' #' compare(mod1, mod2) setGeneric("compare", function(numerator, denominator, data, ...) standardGeneric("compare")) #' Recompute a Bayes factor computation or MCMC object. #' #' Take an object and redo the computation (useful for sampling). In cases where sampling is #' used to compute the Bayes factor, the estimate of the precision of new samples will be added #' to the estimate precision of the old sample will be added to produce a new estimate of the #' precision. #' @param x object to recompute #' @param progress report progress of the computation? #' @param multicore Use multicore, if available #' @param callback callback function for third-party interfaces #' @param ... arguments passed to and from related methods #' @return Returns an object of the same type, after repeating the sampling (perhaps with more iterations) #' @export #' @docType methods #' @rdname recompute-methods #' @examples #' ## Sample from the posteriors for two models #' data(puzzles) #' #' ## Main effects model; result is a BFmcmc object, inheriting #' ## mcmc from the coda package #' bf = lmBF(RT ~ shape + color + ID, data = puzzles, whichRandom = "ID", #' progress = FALSE) #' #' ## recompute Bayes factor object #' recompute(bf, iterations = 1000, progress = FALSE) #' #' ## Sample from posterior distribution of model above, and recompute: #' chains = posterior(bf, iterations = 1000, progress = FALSE) #' newChains = recompute(chains, iterations = 1000, progress=FALSE) setGeneric("recompute", function(x, progress=getOption('BFprogress', interactive()), multicore = FALSE, callback = function(...) as.integer(0), ...) standardGeneric("recompute")) #' Sample from the posterior distribution of one of several models. #' #' This function samples from the posterior distribution of a \code{BFmodel}, #' which can be obtained from a \code{BFBayesFactor} object. If there is more #' than one numerator in the \code{BFBayesFactor} object, the \code{index} #' argument can be passed to select one numerator. #' #' The data argument is used internally, and will y not be needed by #' end-users. #' #' Note that if there are fixed effects in the model, the reduced #' parameterzation used internally (see help for \code{\link{anovaBF}}) is #' unreduced. For a factor with two levels, the chain will contain two effect #' estimates that sum to 0. #' #' Two useful arguments that can be passed to related methods are \code{thin} #' and \code{columnFilter}, currently implemented for methods using #' \code{nWayAOV} (models with more than one categorical covariate, or a mix of #' categorical and continuous covariates). \code{thin}, an integer, will keep #' only every \code{thin} iterations. The default is \code{thin=1}, which keeps #' all iterations. Argument \code{columnFilter} is either \code{NULL} (for no #' filtering) or a character vector of extended regular expressions (see #' \link{regex} help for details). Any column from an effect that matches one of #' the filters will not be saved. #' @param model or set of models from which to sample #' @param index the index within the set of models giving the desired model #' @param data the data to be conditioned on #' @param iterations the number of iterations to sample #' @param ... arguments passed to and from related methods #' @return Returns an object containing samples from the posterior distribution #' of the specified model #' @export #' @docType methods #' @rdname posterior-methods #' @examples #' ## Sample from the posteriors for two models #' data(sleep) #' #' bf = lmBF(extra ~ group + ID, data = sleep, whichRandom="ID", progress=FALSE) #' #' ## sample from the posterior of the numerator model #' ## data argument not needed - it is included in the Bayes factor object #' chains = posterior(bf, iterations = 1000, progress = FALSE) #' #' plot(chains) #' #' ## demonstrate column filtering by filtering out participant effects #' data(puzzles) #' bf = lmBF(RT ~ shape + color + shape:color + ID, data=puzzles) #' chains = posterior(bf, iterations = 1000, progress = FALSE, columnFilter="^ID$") #' colnames(chains) # Contains no participant effects setGeneric("posterior", function(model, index, data, iterations, ...) standardGeneric("posterior")) #' Extract the Bayes factor from an object #' @param x object from which to extract the Bayes factors #' @param logbf return the logarithm of the Bayes factors #' @param onlybf return a vector of only the Bayes factors #' @return Returns an object containing Bayes factors extracted from the object #' @export #' @docType methods #' @rdname extractBF-methods #' @examples #' ## Sample from the posteriors for two models #' data(puzzles) #' #' bf = lmBF(RT ~ shape*color + ID, data = puzzles, whichRandom="ID", progress=FALSE) #' #' extractBF(bf) setGeneric("extractBF", function(x, logbf=FALSE, onlybf=FALSE) standardGeneric("extractBF")) #' Extract the odds from an object #' @param x object from which to extract #' @param logodds return the logarithm #' @param onlyodds return a vector of only the odds #' @return Returns an object containing odds extracted from the object #' @export #' @docType methods #' @rdname extractOdds-methods setGeneric("extractOdds", function(x, logodds=FALSE, onlyodds=FALSE) standardGeneric("extractOdds")) #' Extract the probabilities from an object #' @param x object from which to extract #' @param logprobs return the logarithm #' @param onlyprobs return a vector of only the probabilities #' @return Returns an object containing probabilities extracted from the object #' @export #' @docType methods #' @rdname extractProbabilities-methods setGeneric("extractProbabilities", function(x, logprobs=FALSE, onlyprobs=FALSE) standardGeneric("extractProbabilities")) #' Set prior odds in an object #' @docType methods #' @rdname priorOdds-method #' @param object object in which to set odds #' @param value odds setGeneric("priorOdds<-", function(object, value) standardGeneric("priorOdds<-")) #' Set prior log odds in an object #' @docType methods #' @rdname priorLogodds-method #' @param object object in which to set log odds #' @param value log odds setGeneric("priorLogodds<-", function(object, value) standardGeneric("priorLogodds<-")) #' Filter the elements of an object according to some pre-specified criteria #' @param x object #' @param name regular expression to search name #' @param perl logical. Should perl-compatible regexps be used? See ?grepl for details. #' @param fixed logical. If TRUE, pattern is a string to be matched as is. See ?grepl for details. #' @param ... arguments passed to and from related methods #' @return Returns a filtered object setGeneric("filterBF", function(x, name, perl = FALSE, fixed = FALSE, ...) standardGeneric("filterBF"))
/scratch/gouwar.j/cran-all/cranData/BayesFactor/R/aaGenerics.R
enumerateAnovaModelsWithMain<-function(factors){ nFactors = length(factors) mb = monotoneBooleanNice(nFactors) mb = mb[-c(1,2),-ncol(mb)] myModels = apply(mb,1,function(v) rev(((length(v):1))[v])) myTerms = sapply(1:(2^nFactors-1),makeTerm,factors=factors) lapply(myModels, function(v) myTerms[v]) } enumerateAnovaModels = function(fmla, whichModels, data){ trms <- attr(terms(fmla, data = data), "term.labels") ntrms <- length(trms) dv = stringFromFormula(fmla[[2]]) dv = composeTerm(dv) if(ntrms == 1 ) whichModels = "all" if(whichModels=="top"){ lst = combn2( trms, ntrms - 1 ) }else if(whichModels=='bottom'){ lst = as.list(combn( trms, 1 )) }else if(whichModels=="all"){ lst = combn2( trms, 1 ) }else if(whichModels=="withmain"){ lst = enumerateAnovaModelsWithMain( fmlaFactors(fmla, data)[-1] ) }else{ stop("Unknown whichModels value: ",whichModels) } strng <- sapply(lst,function(el){ paste(el,collapse=" + ") }) strng <- unique(strng) fmla <- lapply(strng, function(el){ formula(paste(dv,"~", el)) }) return(fmla) } createFixedAnovaModel <- function(dataTypes, formula){ fixedFactors <- names(dataTypes[dataTypes=="fixed"]) fixedPart <- paste(composeTerms(fixedFactors),collapse="*") # get LHS of formula dv = stringFromFormula(formula[[2]]) dv = composeTerm(dv) formula(paste(dv, "~", fixedPart, collapse="")) } addRandomModelPart <- function(formula, dataTypes, null = FALSE){ randomFactors <- names(dataTypes[dataTypes=="random"]) randomPart <- paste(randomFactors,collapse="+") fmla = stringFromFormula(formula) dv = stringFromFormula(formula[[2]]) dv = composeTerm(dv) if(null){ ret = formula(paste(dv, "~", randomPart, collapse="")) }else{ ret = formula(paste(fmla, "+", randomPart, collapse="")) } return(ret) }
/scratch/gouwar.j/cran-all/cranData/BayesFactor/R/anovaBF-utility.R
##' This function computes Bayes factors for all main-effects and interaction ##' contrasts in an ANOVA design. ##' ##' Models, priors, and methods of computation are provided in Rouder et al. ##' (2012). ##' ##' The ANOVA model for a vector of observations \eqn{y} is \deqn{ y = \mu + X_1 ##' \theta_1 + \ldots + X_p\theta_p +\epsilon,} where ##' \eqn{\theta_1,\ldots,\theta_p} are vectors of main-effect and interaction ##' effects, \eqn{X_1,\ldots,X_p} are corresponding design matrices, and ##' \eqn{\epsilon} is a vector of zero-centered noise terms with variance ##' \eqn{\sigma^2}. Zellner and Siow (1980) inspired g-priors are placed on ##' effects, but with a separate g-prior parameter for each covariate: ##' \deqn{\theta_1~N(0,g_1\sigma^2), \ldots, \theta_p~N(0,g_p \sigma^2).} A ##' Jeffries prior is placed on \eqn{\mu} and \eqn{\sigma^2}. Independent ##' scaled inverse-chi-square priors with one degree of freedom are placed on ##' \eqn{g_1,\ldots,g_p}. The square-root of the scale for g's corresponding to ##' fixed and random effects is given by \code{rscaleFixed} and ##' \code{rscaleRandom}, respectively. ##' ##' When a factor is treated as random, there are as many main effect terms in ##' the vector \eqn{\theta} as levels. When a factor is treated as fixed, the ##' sums-to-zero linear constraint is enforced by centering the corresponding ##' design matrix, and there is one fewer main effect terms as levels. The ##' Cornfield-Tukey model of interactions is assumed. Details are provided in ##' Rouder et al. (2012) ##' ##' Bayes factors are computed by integrating the likelihood with respect to the ##' priors on parameters. The integration of all parameters except ##' \eqn{g_1,\ldots,g_p} may be expressed in closed-form; the integration of ##' \eqn{g_1,\ldots,g_p} is performed through Monte Carlo sampling, and ##' \code{iterations} is the number of iterations used to estimate the Bayes ##' factor. ##' ##' \code{anovaBF} computes Bayes factors for either all submodels or select ##' submodels missing a single main effect or covariate, depending on the ##' argument \code{whichModels}. If no random factors are specified, the null ##' model assumed by \code{anovaBF} is the grand-mean only model. If random ##' factors are specified, the null model is the model with an additive model on ##' all random factors, plus a grand mean. Thus, \code{anovaBF} does not ##' currently test random factors. Testing random factors is possible with ##' \code{\link{lmBF}}. ##' ##' The argument \code{whichModels} controls which models are tested. Possible ##' values are 'all', 'withmain', 'top', and 'bottom'. Setting ##' \code{whichModels} to 'all' will test all models that can be created by ##' including or not including a main effect or interaction. 'top' will test all ##' models that can be created by removing or leaving in a main effect or ##' interaction term from the full model. 'bottom' creates models by adding ##' single factors or interactions to the null model. 'withmain' will test all ##' models, with the constraint that if an interaction is included, the ##' corresponding main effects are also included. ##' ##' For the \code{rscaleFixed} and \code{rscaleRandom} arguments, several named ##' values are recognized: "medium", "wide", and "ultrawide", corresponding to ##' \eqn{r} scale values of 1/2, \eqn{\sqrt{2}/2}{sqrt(2)/2}, and 1, ##' respectively. In addition, \code{rscaleRandom} can be set to the "nuisance", ##' which sets \eqn{r=1} (and is thus equivalent to "ultrawide"). The "nuisance" ##' setting is for medium-to-large-sized effects assumed to be in the data but ##' typically not of interest, such as variance due to participants. ##' @title Function to compute Bayes factors for ANOVA designs ##' @param formula a formula containing all factors to include in the analysis ##' (see Examples) ##' @param data a data frame containing data for all factors in the formula ##' @param whichRandom a character vector specifying which factors are random ##' @param whichModels which set of models to compare; see Details ##' @param iterations How many Monte Carlo simulations to generate, if relevant ##' @param progress if \code{TRUE}, show progress with a text progress bar ##' @param rscaleFixed prior scale for standardized, reduced fixed effects. A ##' number of preset values can be given as strings; see Details. ##' @param rscaleRandom prior scale for standardized random effects ##' @param rscaleEffects A named vector of prior settings for individual factors, ##' overriding rscaleFixed and rscaleRandom. Values are scales, names are factor names. ##' @param multicore if \code{TRUE} use multiple cores through the \code{doMC} ##' package. Unavailable on Windows. ##' @param method approximation method, if needed. See \code{\link{nWayAOV}} for ##' details. ##' @param noSample if \code{TRUE}, do not sample, instead returning NA. ##' @return An object of class \code{BFBayesFactor}, containing the computed ##' model comparisons. Bayes factors can be extracted using extractBF(), as.vector() ##' or as.data.frame(). ##' @param callback callback function for third-party interfaces ##' @author Richard D. Morey (\email{richarddmorey@@gmail.com}) ##' @export ##' @references Gelman, A. (2005) Analysis of Variance---why it is more ##' important than ever. Annals of Statistics, 33, pp. 1-53. ##' ##' Rouder, J. N., Morey, R. D., Speckman, P. L., Province, J. M., (2012) ##' Default Bayes Factors for ANOVA Designs. Journal of Mathematical ##' Psychology. 56. p. 356-374. ##' ##' Zellner, A. and Siow, A., (1980) Posterior Odds Ratios for Selected ##' Regression Hypotheses. In Bayesian Statistics: Proceedings of the First ##' Interanational Meeting held in Valencia (Spain). Bernardo, J. M., ##' Lindley, D. V., and Smith A. F. M. (eds), pp. 585-603. University of ##' Valencia. ##' ##' @note The function \code{anovaBF} will compute Bayes factors for all ##' possible combinations of fixed factors and interactions, against the null ##' hypothesis that \emph{all} effects are 0. The total number of tests ##' computed will be \eqn{2^{2^K - 1}}{2^(2^K - 1)} for \eqn{K} fixed factors. ##' This number increases very quickly with the number of factors. For ##' instance, for a five-way ANOVA, the total number of tests exceeds two ##' billion. Even though each test takes a fraction of a second, the time ##' taken for all tests could exceed your lifetime. An option is included to ##' prevent this: \code{options('BFMaxModels')}, which defaults to 50,000, is ##' the maximum number of models that `anovaBF` will analyze at once. This can ##' be increased by increasing the option value. ##' ##' It is possible to reduce the number of models tested by only testing the ##' most complex model and every restriction that can be formed by removing ##' one factor or interaction using the \code{whichModels} argument. Setting ##' this argument to 'top' reduces the number of tests to \eqn{2^K-1}, which ##' is more manageable. The Bayes factor for each restriction against the most ##' complex model can be interpreted as a test of the removed ##' factor/interaction. Setting \code{whichModels} to 'withmain' will not ##' reduce the number of tests as much as 'top' but the results may be more ##' interpretable, since an interaction is only allowed when all interacting ##' effects (main or interaction) are also included in the model. ##' ##' @examples ##' ## Classical example, taken from t.test() example ##' ## Student's sleep data ##' data(sleep) ##' plot(extra ~ group, data = sleep) ##' ##' ## traditional ANOVA gives a p value of 0.00283 ##' summary(aov(extra ~ group + Error(ID/group), data = sleep)) ##' ##' ## Gives a Bayes factor of about 11.6 ##' ## in favor of the alternative hypothesis ##' anovaBF(extra ~ group + ID, data = sleep, whichRandom = "ID", ##' progress=FALSE) ##' ##' ## Demonstrate top-down testing ##' data(puzzles) ##' result = anovaBF(RT ~ shape*color + ID, data = puzzles, whichRandom = "ID", ##' whichModels = 'top', progress=FALSE) ##' result ##' ##' ## In orthogonal designs, the top down Bayes factor can be ##' ## interpreted as a test of the omitted effect ##' @keywords htest ##' @seealso \code{\link{lmBF}}, for testing specific models, and ##' \code{\link{regressionBF}} for the function similar to \code{anovaBF} for ##' linear regression models. anovaBF <- function(formula, data, whichRandom = NULL, whichModels = "withmain", iterations = 10000, progress = getOption('BFprogress', interactive()), rscaleFixed = "medium", rscaleRandom = "nuisance", rscaleEffects = NULL, multicore = FALSE, method="auto", noSample=FALSE, callback=function(...) as.integer(0)) { data <- marshallTibble(data) checkFormula(formula, data, analysis = "anova") # pare whichRandom down to terms that appear in the formula whichRandom <- whichRandom[whichRandom %in% fmlaFactors(formula, data)[-1]] if(all(fmlaFactors(formula, data)[-1] %in% whichRandom)){ # No fixed factors! bf = lmBF(formula, data, whichRandom, rscaleFixed, rscaleRandom, rscaleEffects = rscaleEffects, progress = progress, method = method, noSample = noSample) return(bf) } dataTypes <- createDataTypes(formula, whichRandom, data, analysis = "anova") fmla <- createFixedAnovaModel(dataTypes, formula) models <- enumerateAnovaModels(fmla, whichModels, data) if(length(models)>getOption('BFMaxModels', 50000)) stop("Maximum number of models exceeded (", length(models), " > ",getOption('BFMaxModels', 50000) ,"). ", "The maximum can be increased by changing ", "options('BFMaxModels').") if(length(whichRandom) > 0 ){ models <- lapply(models, addRandomModelPart, dataTypes = dataTypes) models <- c(models, addRandomModelPart(fmla, dataTypes, null=TRUE)) } if(multicore){ message("Note: Progress bars and callbacks are suppressed when running multicore.") if(!requireNamespace("doMC", quietly = TRUE)){ stop("Required package (doMC) missing for multicore functionality.") } doMC::registerDoMC() if(foreach::getDoParWorkers()==1){ warning("Multicore specified, but only using 1 core. Set options(cores) to something >1.") } bfs <- foreach::"%dopar%"( foreach::foreach(gIndex=models, .options.multicore=mcoptions), lmBF(gIndex,data = data, whichRandom = whichRandom, rscaleFixed = rscaleFixed, rscaleRandom = rscaleRandom, rscaleEffects = rscaleEffects, iterations = iterations, method=method, progress=FALSE, noSample = noSample) ) }else{ # Single core checkCallback(callback,as.integer(0)) bfs = NULL myCallback <- function(prgs){ frac <- (i - 1 + prgs/1000)/length(models) ret <- callback(frac*1000) return(as.integer(ret)) } if(progress){ pb = txtProgressBar(min = 0, max = length(models), style = 3) }else{ pb = NULL } for(i in 1:length(models)){ oneModel <- lmBF(models[[i]],data = data, whichRandom = whichRandom, rscaleFixed = rscaleFixed, rscaleRandom = rscaleRandom, rscaleEffects = rscaleEffects, iterations = iterations, progress = FALSE, method = method, noSample=noSample,callback=myCallback) if(inherits(pb,"txtProgressBar")) setTxtProgressBar(pb, i) bfs = c(bfs,oneModel) } if(inherits(pb,"txtProgressBar")) close(pb) checkCallback(callback,as.integer(1000)) } # combine all the Bayes factors into one BFBayesFactor object bfObj = do.call("c", bfs) # If we have random effects, make those the denominator if(length(whichRandom) > 0) bfObj = bfObj[-length(bfObj)] / bfObj[length(bfObj)] if(whichModels=="top") bfObj = BFBayesFactorTop(bfObj) return(bfObj) }
/scratch/gouwar.j/cran-all/cranData/BayesFactor/R/anovaBF.R
# Author: Jonathon Love toB64Lookup <- c( 0x41, # A 0x42, # B 0x43, # C 0x44, # D 0x45, # E 0x46, # F 0x47, # G 0x48, # H 0x49, # I 0x4A, # J 0x4B, # K 0x4C, # L 0x4D, # M 0x4E, # N 0x4F, # O 0x50, # P 0x51, # Q 0x52, # R 0x53, # S 0x54, # T 0x55, # U 0x56, # V 0x57, # W 0x58, # X 0x59, # Y 0x5A, # Z 0x61, # a 0x62, # b 0x63, # c 0x64, # d 0x65, # e 0x66, # f 0x67, # g 0x68, # h 0x69, # i 0x6A, # j 0x6B, # k 0x6C, # l 0x6D, # m 0x6E, # n 0x6F, # o 0x70, # p 0x71, # q 0x72, # r 0x73, # s 0x74, # t 0x75, # u 0x76, # v 0x77, # w 0x78, # x 0x79, # y 0x7A, # z 0x30, # 0 0x31, # 1 0x32, # 2 0x33, # 3 0x34, # 4 0x35, # 5 0x36, # 6 0x37, # 7 0x38, # 8 0x39, # 9 0x2E, # . 0x5F) # _ fromB64Lookup <- c( rep(-1, 0x2D), 63, -1, 0x35:0x3E, # 0x30 rep(-1, 0x40 - 0x3A + 1), 1:26, # 0x41 rep(-1, 0x5E - 0x5B + 1), # 0x5B 64, # 0x5F -1, # 0x60 1:26+26, rep(-1, 0x7F - 0x7A + 1)) toB64 <- function(names) { sapply(names, toB64string, USE.NAMES=FALSE) } fromB64 <- function(names) { sapply(names, fromB64string, USE.NAMES=FALSE) } fromB64string <- function(string) { if ( ! startsWith(string, '.')) stop('b64 names should begin with a dot') string <- substring(string, 2) if (string == "") return("") array <- as.integer(charToRaw(string)) array <- fromB64Lookup[array] - 1 out <- c() i <- 1 j <- 1 while (i <= length(array)) { if (i + 1 <= length(array)) out[j + 0] <- 4 * array[i + 0] + floor(array[i + 1] / 16) else out[j + 0] <- 4 * array[i + 0] if (i + 2 <= length(array)) out[j + 1] <- 16 * (array[i + 1] %% 16) + as.integer(array[i + 2] / 4) if (i + 3 <= length(array)) out[j + 2] <- 64 * (array[i + 2] %% 4) + array[i + 3] i <- i + 4 j <- j + 3 } rawToChar(as.raw(out)) } toB64string <- function(string) { if (string == "") return("") array <- as.integer(charToRaw(string)) out <- c() i <- 1 j <- 1 while (i <= length(array)) { out[j + 0] <- floor(array[i + 0] / 4) if (i + 1 <= length(array)) { out[j + 1] <- (array[i + 0] %% 4) * 16 + floor((array[i + 1] / 16)) if (i + 2 <= length(array)) { out[j + 2] <- (array[i + 1] %% 16) * 4 + floor(array[i + 2] / 64) out[j + 3] <- array[i + 2] %% 64 } else { out[j + 2] <- (array[i + 1] %% 16) * 4 } } else { out[j + 1] <- (array[i + 0] %% 4) * 16 } i <- i + 3 j <- j + 4 } chars <- toB64Lookup[out + 1] paste0('.', rawToChar(as.raw(chars))) }
/scratch/gouwar.j/cran-all/cranData/BayesFactor/R/base64.R
checkCallback = function(callback, ... ){ ret = as.integer(callback(...)) if(ret) stop("Operation cancelled by callback function. ", ret) return(ret) }
/scratch/gouwar.j/cran-all/cranData/BayesFactor/R/checkCallback.R
createDataTypes <- function(formula, whichRandom, data, analysis){ factors <- rownames(attr(terms(formula, data = data),"factors"))[-1] factors <- unlist(decomposeTerms(factors)) cnames <- colnames(data) # check status of data columns types = sapply(cnames, function(name, data){ ifelse(is.factor(data[,name]), "fixed", "continuous") }, data = data) # restrict to only columns of interest types = types[ names(types) %in% factors ] if(length(types) <1 ) return(c()) if( any(types[ names(types) %in% whichRandom ] == "continuous") ) stop("Nonfactors are specified as random.") if(length(whichRandom)>0) types[ names(types) %in% whichRandom ] = "random" #### check various analysis types ## ANOVA can only accept factors if( any(types=="continuous") & analysis == "anova" ) stop("anovaBF() cannot be used with nonfactor independent variables. Use lmBF(), regressionBF(), or generalTestBF() instead.") ## regression can only accept nonfactors if( any(types %in% c("fixed", "random")) & analysis == "regression" ) stop("regressionBF() cannot be used with factor independent variables. Use lmBF(), anovaBF(), or generalTestBF() instead.") #### End checking analysis types return(types) } checkFormula <- function(formula, data, analysis){ if(length(formula) < 3) stop("LHS of formula must be given.") cnames = colnames(data) dv = stringFromFormula(formula[[2]]) if(!is.numeric(data[,dv])) stop("Dependent variable must be numeric.") if(any(is.na(data[,dv])) | any(is.infinite(data[,dv]))) stop("Dependent variable must not contain missing or infinite values.") factors = fmlaFactors(formula, data) terms = colnames(attr(terms(formula, data = data),"factors")) decom = decomposeTerms(terms) terms = unlist(decom) vars = rownames(attr(terms(formula, data = data),"factors")) vars = unlist(decomposeTerms(vars)) if(any(is.na(data[,vars]))) stop("Predictors must not contain missing values.") if(is.null(factors)) return() if(factors[1] %in% terms) stop("Dependent variable cannot be a predictor.") if(!all(factors %in% cnames)) stop("Some variables missing in data frame.") if(analysis=="regression"){ RHS = stringFromFormula(formula[[3]]) lengths = sapply(decom, length) if (any(lengths > 1)) stop("Interactions not allowed in regressionBF (try generalTestBF).") } if(analysis=="lm" | analysis=="anova" | analysis == "regression" | analysis == "indept") if(attr(terms(formula, data = data),"intercept") == 0) stop("Formula must include intercept.") if(analysis=="indept"){ if( length(decom) > 1 ) stop("Indep. groups t test can only support 1 factor as predictor.") if(length(decom[[1]]) > 1) stop("Interaction terms are not allowed in t test.") if(nlevels(as.factor(data[,terms])) > 2) stop("Indep. groups t test requires a factor with exactly 2 levels.") } invisible() } checkEffects <- function(effects, data, dataTypes){ if(!all(effects %in% colnames(data))) stop("Term in formula missing in data") if(!all(effects %in% names(dataTypes))) stop("Term in formula missing in dataTypes") # add more checking code here # most importantly, to check consistancy of data factors and dataTypes # no factors should be labeled as continuous, etc }
/scratch/gouwar.j/cran-all/cranData/BayesFactor/R/checking.R
if(getRversion() >= '2.15.1') globalVariables("gIndex") mcoptions <- list(preschedule=FALSE, set.seed=TRUE) # Create (new) factors out of factor and character columns reFactorData <- function(data){ if(is.data.frame(data)){ indChar <- sapply(data, is.character) indFac <- sapply(data, is.factor) data[indChar | indFac] <- lapply(data[indChar | indFac], factor) return(data) }else{ stop("Data must be in data.frame format.") } } filterVectorLogical <- function(columnFilter,myNames){ if(!is.null(columnFilter)){ ignoreMatrix = sapply(columnFilter, function(el,namedCols){ grepl(el,namedCols) },namedCols=myNames) if(length(myNames)==1){ ignoreCols = any(ignoreMatrix) }else{ ignoreCols = apply(ignoreMatrix,1,any) } return(ignoreCols) }else{ return(rep(FALSE,length(myNames))) } } expString <- function(x){ if(is.na(x)) return("NA") doubleBase = .Machine$double.base toBase10log = x / log(10) toBaselog = x / log(doubleBase) numMax = .Machine$double.max.exp numMin = .Machine$double.min.exp if(toBaselog>numMax){ first <- prettyNum( 10 ^ (toBase10log - floor(toBase10log)) ) second <- prettyNum( floor(toBase10log) ) return( paste( first, "e+", second, sep="" ) ) }else if(toBaselog < numMin){ first <- prettyNum( 10 ^ (1 - (ceiling(toBase10log) - toBase10log)) ) second <- prettyNum( ceiling(toBase10log)-1 ) return( paste( first, "e", second, sep="" ) ) }else{ return( prettyNum( exp(x) ) ) } } alphabetizeTerms <- function(trms){ splt = strsplit(trms,":",fixed=TRUE) sorted=lapply(splt, function(trm){ if(length(trm)==1) return(trm) trm = sort(trm) paste(trm,collapse=":") }) sorted = unlist(sorted) return(sorted) } whichOmitted <- function(numerator, full){ fullFmla <- formula(full@identifier$formula) numFmla <- formula(numerator@identifier$formula) fullTrms <- attr(terms(fullFmla), "term.labels") numTrms <- attr(terms(numFmla), "term.labels") fullTrms = alphabetizeTerms(fullTrms) numTrms = alphabetizeTerms(numTrms) omitted = fullTrms[!(fullTrms %in% numTrms)] if(any( !(numTrms %in% fullTrms) )) stop("Numerator not a proper restriction of full.") return(omitted) } propErrorEst = function(logX){ logX = logX[!is.na(logX)] summaries = logSummaryStats(logX) exp( ( summaries$logVar - log(length(logX)) )/2 - summaries$logMean) } combineModels <- function(modelList, checkCodes = TRUE){ are.same = sapply(modelList[-1],function(m) modelList[[1]] %same% m) if( any(!are.same) ) stop("Cannot combine models that are not the same.") if(!inherits(modelList[[1]], "BFlinearModel")) return(modelList[[1]]) hasanalysis = sapply(modelList, .hasSlot, name = "analysis") if( all(!hasanalysis) ) return(modelList[[1]]) modelList = modelList[hasanalysis] if(length(modelList)==1) return(modelList[[1]]) sampledTRUE = sapply(sapply(modelList, function(m) m@analysis[['sampled']]),identical,y=TRUE) if( !any(sampledTRUE)) return(modelList[[1]]) modelList = modelList[which(sampledTRUE)] if( length(modelList)==1 ) return(modelList[[1]]) bfs = unlist(sapply(modelList, function(m) m@analysis[['bf']])) properrs = unlist(sapply(modelList, function(m) m@analysis[['properror']])) # We need to make sure we don't combine analyses that are based on the same codes. codes = lapply(modelList, function(m) m@analysis[['code']]) if(checkCodes){ n = length(codes) X = diag(n) for(i in 2:n) for(j in 1:(i-1)) X[i,j] = X[j,i] = length(intersect(codes[[i]],codes[[j]]))>0 if(!identical(X,diag(n))) return(modelList[[which.min(properrs)]]) } # Convert prop to abs err logAbs = bfs + log(properrs) # Compute log precisions logPrec = -2*logAbs # log sum of precisions logSumPrec = logMeanExpLogs(logPrec) + log(length(logPrec)) # log weighted average logAvgBF = logMeanExpLogs(logPrec + bfs - logSumPrec) + log(length(logPrec)) # convert prec back to abs err logSumAbs = -logSumPrec/2 # convert back to prop err sumPropErr = exp(logSumAbs - logAvgBF) bf = logAvgBF properror = sumPropErr new.analysis = list(bf = bf, properror = properror, sampled = TRUE, method = "composite") all.codes = do.call("c",codes) new.mod = modelList[[1]] new.mod@analysis = new.analysis new.mod@analysis[['code']] = all.codes new.mod@version = BFInfo(FALSE) return(new.mod) } combn2 <- function(x,lower=1){ unlist(lapply(lower:length(x),function(m,x) combn(x,m,simplify=FALSE),x=x),recursive=FALSE) } stringFromFormula <- function(formula){ oneLine = paste(deparse(formula),collapse="") sub("\\s\\s+"," ", oneLine, perl=TRUE) # get rid of extra spaces } fmlaFactors <- function(formula, data){ names <- rownames(attr(terms(formula, data = data),"factors")) names <- decomposeTerms(names) names <- unlist(names) names } are.factors<-function(df) sapply(df, function(v) is.factor(v)) `%com%` <- function(x,y){ common = intersect(names(x),names(y)) if(length(common)==0) return(logical(0)) all(sapply(common, function(el,x,y) identical(x[el],y[el]), x=x,y=y)) } randomString <- function(x=1){ n = ifelse(length(x)>1, length(x), x) substring(tempfile(rep("",n),"",""),2) } rpriorValues <- function(modelType,effectType=NULL,priorType=NULL){ if(length(priorType)==0){ return(NULL) }else if(length(priorType)>1 | is.numeric(priorType)){ return(priorType) }else if( suppressWarnings( !is.na( as.numeric( priorType ) ) ) ){ return(as.numeric(priorType)) }else if(length(priorType)==0){ return(NULL) } if(modelType=="proptest"){ return( switch(priorType, ultrawide=1, wide=sqrt(2)/2, medium=1/2, stop("Unknown prior type.")) ) } if(modelType=="allNways"){ return( switch(effectType, fixed = switch(priorType, ultrawide=1, wide=sqrt(2)/2, medium=1/2, stop("Unknown prior type.")), random = switch(priorType, wide=sqrt(2)/2, medium=1/2, nuisance=1, ultrawide=1, stop("Unknown prior type.")), continuous = rpriorValues("regression",,priorType), stop("Unknown prior type.") ) ) } if(modelType=="ttestTwo"){ return( switch(priorType, ultrawide=sqrt(2), wide=1, medium=sqrt(2)/2, stop("Unknown prior type.")) ) } if(modelType=="ttestOne"){ return( switch(priorType, ultrawide=sqrt(2), wide=1, medium=sqrt(2)/2, stop("Unknown prior type.")) ) } if(modelType=="regression"){ #return(1) return( switch(priorType, ultrawide=sqrt(2)/2, wide=1/2, medium=sqrt(2)/4, stop("Unknown prior type.") ) ) } if(modelType=="correlation"){ return( switch(priorType, ultrawide=1, wide=1/sqrt(3), medium=1/3, medium.narrow = 1/sqrt(27), stop("Unknown prior type.") ) ) } stop("Unknown prior type.") } dinvgamma = function (x, shape, scale = 1, log = FALSE, logx = FALSE) { if (shape <= 0 | scale <= 0) { stop("Shape or scale parameter negative in dinvgamma().\n") } shape = rep(0, length(x)) + shape scale = rep(0, length(x)) + scale if(logx){ log.density = mapply(dinvgamma1_logx_Rcpp, x = x, a = shape, b = scale) }else{ log.density = mapply(dinvgamma1_Rcpp, x = x, a = shape, b = scale) } if(log){ return(log.density) }else{ return(exp(log.density)) } } # Taken from the WLE package source by Claudio Agostinelli <claudio at unive.it> binary <- function(x, dim) { if (x==0) { pos <- 1 } else { pos <- floor(log(x, 2))+1 } if (!missing(dim)) { if (pos<=dim) { pos <- dim } else { warning("the value of `dim` is too small") } } bin <- rep(0, pos) dicotomy <- rep(FALSE, pos) for (i in pos:1) { bin[i] <- floor(x/2^(i-1)) dicotomy[i] <- bin[i]==1 x <- x-((2^(i-1))*bin[i]) } return(list(binary=bin, dicotomy=dicotomy)) } # Construct all monotone Boolean functions for m arguments monotoneBoolean <- function(m){ if(m==0){ return(list(FALSE,TRUE)) }else{ m0 = monotoneBoolean(m-1) m1 = list() for(i in 1:length(m0)) for(j in 1:length(m0)){ if(identical((m0[[i]] | m0[[j]]), m0[[j]])){ m1[[length(m1)+1]] = c(m0[[i]],m0[[j]]) } } return(m1) } } # Construct all monotone Boolean functions for m arguments # but output in nice format (matrix) monotoneBooleanNice = function(m){ mb = monotoneBoolean(m) n = length(mb) mb = unlist(mb) dim(mb) = c(length(mb)/n,n) t(mb) } makeTerm <- function(m,factors){ trms = factors[binary(m,length(factors))$dicotomy] trms = composeTerm(trms) trms } setMethod("%termin%", signature = c(x="character",table="character"), function(x,table){ table = strsplit(table,":",fixed=TRUE) x = strsplit(x,":",fixed=TRUE) returnVector = rep(FALSE,length(x)) for(i in 1:length(x)) for(j in 1:length(table)){ found = all(table[[j]] %in% x[[i]]) & all(x[[i]] %in% table[[j]]) returnVector[i] = returnVector[i] | found } return(returnVector) }) setMethod("%termin%", signature = c(x="character",table="NULL"), function(x,table){ return(rep(FALSE,length(x))) }) termMatch <- function(x, table, nomatch = NA_integer_){ returnVector = rep(nomatch,length(x)) if(is.null(table)){ return(returnVector) } table = strsplit(table,":",fixed=TRUE) x = strsplit(x,":",fixed=TRUE) for(i in 1:length(x)) for(j in 1:length(table)){ found = all(table[[j]] %in% x[[i]]) & all(x[[i]] %in% table[[j]]) if(is.na(returnVector[i]) & found) returnVector[i] = j } return(returnVector) } # Add two values for which the proportional error is known # and return the proportional error sumWithPropErr <- function(x1,x2,err1,err2){ # convert proportional error to abs err logAbs1 = x1 + log(err1) logAbs2 = x2 + log(err2) logSum = logExpXplusExpY( x1, x2 ) absSum = .5 * logExpXplusExpY(2*logAbs1, 2*logAbs2) propErr = exp(absSum - logSum) return(c(logSum,propErr)) } BFtry <- function(expression, silent=FALSE) { result <- base::try(expression, silent=silent) if (inherits(result, "try-error")) { message <- as.character(result) split <- base::strsplit(as.character(message), " : ")[[1]] error <- split[[length(split)]] while (substr(error, 1, 1) == ' ' || substr(error, 1, 1) == '\n') # trim front error <- substring(error, 2) while (substring(error, nchar(error)) == ' ' || substring(error, nchar(error)) == '\n') # trim back error <- substr(error, 1, nchar(error)-1) if (error == "Operation cancelled by callback function.") stop("Operation cancelled by callback function.") if (error == "Operation cancelled by interrupt.") stop("Operation cancelled by interrupt.") } result } marshallTibble <- function(data) { if (inherits(data, 'tbl_df')) { data <- as.data.frame(data) warning('data coerced from tibble to data frame', call.=FALSE) } data } # compose functions from jmvcore package composeTerm <- function(components) { components <- sapply(components, function(component) { if (make.names(component) != component) { component <- gsub('\\', '\\\\', component, fixed=TRUE) component <- gsub('`', '\\`', component, fixed=TRUE) component <- paste0('`', component, '`') } component }, USE.NAMES=FALSE) term <- paste0(components, collapse=':') term } composeTerms <- function(listOfComponents) { sapply(listOfComponents, composeTerm, USE.NAMES=FALSE) } decomposeTerms <- function(terms) { decomposed <- list() for (i in seq_along(terms)) decomposed[[i]] <- decomposeTerm(terms[[i]]) decomposed } decomposeTerm <- function(term) { chars <- strsplit(term, '')[[1]] components <- character() componentChars <- character() inQuote <- FALSE i <- 1 n <- length(chars) while (i <= n) { char <- chars[i] if (char == '`') { inQuote <- ! inQuote } else if (char == '\\') { i <- i + 1 char <- chars[i] componentChars <- c(componentChars, char) } else if (char == ':' && inQuote == FALSE) { component <- paste0(componentChars, collapse='') components <- c(components, component) componentChars <- character() } else { componentChars <- c(componentChars, char) } i <- i + 1 } component <- paste0(componentChars, collapse='') components <- c(components, component) components }
/scratch/gouwar.j/cran-all/cranData/BayesFactor/R/common.R
# By Tahira Jamil, edited by Richard Morey (July 2014) # Bayes Factor from Gunel & Dickey Paper, For different sampling models # (BF1: Poisson; BF2: Multinomial; BF3: Poisson; BF4: Hypergeometric) #The Bayes factor are provided in favour of alternative hypothesis(against the null hypothesis: no association) ############################################## ## Utility functions ############################################## ldirich <- function(a) { val <- sum(lgamma(a)) - lgamma(sum(a)) return(val) } ldirich1 <- function(y, a) { val <- sum(lgamma(a) - lgamma(a+y)) return(val) } pcomb <- function( x, log=TRUE ) { x <- as.vector(x) n <- sum(x) ans = lgamma(n+1) - sum(lgamma(x+1)) if(log){ return(ans) }else{ return(exp(ans)) } } ######################################################################################### # Bayes Factor Gunel & Dickey Equation 4.2 # Poisson Sampling ######################################################################################### contingencyPoisson<-function (y, a){ if( a < 1 ) stop("Prior concentration cannot be less than 1.") n <- sum(y) d <- dim(y) I <- d[1] J <- d[2] b <- I*J*a/n a <- a + 0 * y ac <- colSums(a) ar <- rowSums(a) yc <- colSums(y) yr <- rowSums(y) oc <- 1 + 0 * yc or <- 1 + 0 * yr lbf<-lgamma(sum(a) - (I-1)*(J-1)) - ((I-1)*(J-1)*log(1 + 1/b)) - lgamma(sum(y) + sum(a) - (I-1)*(J-1)) - ldirich(yr + ar-(J- 1)*or) + ldirich( ar - (J - 1) * or) - ldirich(yc + ac - (I - 1) * oc) + ldirich( ac - (I - 1) * oc) - ldirich1(y,a) return(lbf) } ######################################################################################### # Bayes Factor Gunel & Dickey Equation 4.4 # Joint Multinomial Sampling ######################################################################################### contingencyJointMultinomial <-function (y, a){ if( a < 1 ) stop("Prior concentration cannot be less than 1.") a <- a + 0 * y ac <- colSums(a) ar <- rowSums(a) yc <- colSums(y) yr <- rowSums(y) d <- dim(y) oc <- 1 + 0 * yc or <- 1 + 0 * yr I <- d[1] J <- d[2] lbf <- ldirich(c(y) + c(a)) + ldirich(ar - (J - 1) * or) + ldirich(ac - (I - 1) * oc) - ldirich(c(a)) - ldirich(yr + ar - (J - 1) * or) - ldirich(yc + ac - (I - 1) * oc) return(lbf) } ######################################################################################### # Bayes Factor Gunel & Dickey Equation 4.7 #Binomial/ Independent Multinomial Sampling ######################################################################################### contingencyIndepMultinomial<-function (y, a){ if( a < 1 ) stop("Prior concentration cannot be less than 1.") a <- a + 0 * y ac <- colSums(a) ar <- rowSums(a) yc <- colSums(y) yr <- rowSums(y) d <- dim(y) oc <- 1 + 0 * yc or <- 1 + 0 * yr I <- d[1] J <- d[2] lbf <- ldirich(ac - (I - 1) * oc) + ldirich(ar) + ldirich(c(y) + c(a)) - ldirich(yc + ac - (I - 1) * oc) - ldirich(yr + ar) - ldirich(c(a)) return(lbf) } ######################################################################################### # Bayes Factor Gunel & Dickey Equation 4.11 # Hypergeometric Condition on both Margins ######################################################################################### contingencyHypergeometric<-function (y, a) { if( a < 1 ) stop("Prior concentration cannot be less than 1.") if(!identical(dim(y),as.integer(c(2,2)))) stop("hypergeometric contingency tables restricted to 2 x 2 tables; see help for contingencyTableBF()") a <- a + 0 * y ac <- colSums(a) ar <- rowSums(a) yc <- colSums(y) yr <- rowSums(y) d <- dim(y) oc <- 1 + 0 * yc or <- 1 + 0 * yr I <- d[1] J <- d[2] sumg<-function(y,a) { M <- c(yc,yr) stopifnot(M[1]+M[2] == M[3]+M[4]) # To check both marginal totals are equal upper <- min(M[c(1,3)]) lower <- 0 if (min(M) < upper) lower <- upper - min(M) all.M <- t(sapply(lower:upper, function(i) c(a=i, b=M[1] - i, c=M[3] - i, d=M[4] - M[1] + i))) a <- a + 0 * y n.sim<-n.sim<-dim(all.M)[1] g1<- rep(NA,n.sim) for (s in 1:n.sim) { y1<-matrix(all.M[s,],2,2) g1[s]<-pcomb(y1) + ldirich(c(y1)+c(a)) - ldirich(c(a)) } return (logMeanExpLogs(g1) + log(length(g1))) } sum.mar<- sumg(y,a) lbf<-ldirich(c(y) + c(a)) + pcomb(yc) + pcomb(yr) - ldirich(c(a)) - sumg(y,a) return(lbf) } ########################### ## Sampling ## All code below by Richard Morey ########################### sampleContingency <- function(model, type, fixedMargin, prior, data, iterations, ...) { if(type == "poisson"){ if(model == "non-independence"){ chains = samplePoissonContingencyAlt(prior, data, iterations, ...) }else if(model == "independence"){ chains = samplePoissonContingencyNull(prior, data, iterations, ...) } }else if(type == "joint multinomial"){ if(model == "non-independence"){ chains = sampleJointMultiContingencyAlt(prior, data, iterations, ...) }else if(model == "independence"){ chains = sampleJointMultiContingencyNull(prior, data, iterations, ...) } }else if(type == "independent multinomial"){ if(model == "non-independence"){ chains = sampleIndepMultiContingencyAlt(fixedMargin, prior, data, iterations, ...) }else if(model == "independence"){ chains = sampleIndepMultiContingencyNull(fixedMargin, prior, data, iterations, ...) } }else if(type == "hypergeometric"){ if(model == "non-independence"){ chains = sampleHypergeomContingencyAlt(prior, data, iterations, ...) }else if(model == "independence"){ chains = sampleHypergeomContingencyNull(prior, data, iterations, ...) } }else{ stop("Unknown model type.") } } samplePoissonContingencyNull <- function(prior, data, iterations, noSample=FALSE, ...) { a = prior b = length(data) * a / sum(data) I = nrow(data) J = ncol(data) if( a < 1 ) stop("Prior concentration cannot be less than 1.") if(noSample){ samples = data.frame(matrix(as.numeric(NA), 1, I*J + 1 + I + J)) }else{ lambda = rgamma(iterations, sum(data) + I*J*(a - 1) + I + J - 1, b + 1) pi_i = rdirichlet(iterations, rowSums(data) + a - J + 1) pi_j = rdirichlet(iterations, colSums(data) + a - I + 1) lambda_ij = t(sapply( 1:iterations, function(i) as.vector( lambda[i] * outer( pi_i[i,], pi_j[i,] ) ) ) ) samples = data.frame( lambda_ij, lambda, pi_i, pi_j ) } cn1 = paste0("lambda[",outer(1:nrow(data), 1:ncol(data),paste,sep=","),"]") cn2 = paste0("pi[",1:nrow(data),",*]") cn3 = paste0("pi[*,",1:ncol(data),"]") colnames(samples) = c(cn1,"lambda..",cn2,cn3) return(mcmc(samples)) } samplePoissonContingencyAlt <- function(prior, data, iterations, noSample=FALSE, ...) { data = as.matrix(data) a = prior IJ = length(data) b = IJ * a / sum(data) if( a < 1 ) stop("Prior concentration cannot be less than 1.") a.post = data + a b.post = data*0 + b + 1 if(noSample){ samples = data.frame(matrix(as.numeric(NA), 1, IJ)) }else{ samples = rgamma(iterations * IJ, a.post, rate = b.post) dim(samples) = c(IJ, iterations) samples = data.frame(t(samples)) } cn = paste0("lambda[",outer(1:nrow(data), 1:ncol(data),paste,sep=","),"]") colnames(samples) = cn return(mcmc(samples)) } sampleJointMultiContingencyNull <- function(prior, data, iterations, noSample = FALSE, ...) { a = prior I = nrow(data) J = ncol(data) if( a < 1 ) stop("Prior concentration cannot be less than 1.") if(noSample){ samples = data.frame(matrix(as.numeric(NA), 1, I*J + I + J)) }else{ pi_i = rdirichlet(iterations, rowSums(data) + a - J + 1) pi_j = rdirichlet(iterations, colSums(data) + a - I + 1) pi_ij = t(sapply( 1:iterations, function(i) as.vector( outer( pi_i[i,], pi_j[i,] ) ) ) ) samples = data.frame( pi_ij, pi_i, pi_j ) } cn1 = paste0("pi[",outer(1:nrow(data), 1:ncol(data),paste,sep=","),"]") cn2 = paste0("pi[",1:nrow(data),",*]") cn3 = paste0("pi[*,",1:ncol(data),"]") colnames(samples) = c(cn1,cn2,cn3) return(mcmc(samples)) } sampleJointMultiContingencyAlt <- function(prior, data, iterations, noSample = FALSE, ...) { a = prior I = nrow(data) J = ncol(data) if( a < 1 ) stop("Prior concentration cannot be less than 1.") if(noSample){ samples = data.frame(matrix(as.numeric(NA), 1, I*J)) }else{ pi_ij = rdirichlet( iterations, as.matrix(data) + a ) samples = data.frame( pi_ij ) } cn = paste0("pi[",outer(1:nrow(data), 1:ncol(data),paste,sep=","),"]") colnames(samples) = cn return(mcmc(samples)) } sampleIndepMultiContingencyNull <- function(fixedMargin, prior, data, iterations, noSample = FALSE, ...) { a = prior I = nrow(data) J = ncol(data) if( a < 1 ) stop("Prior concentration cannot be less than 1.") if(noSample){ if(fixedMargin == "rows"){ samples = data.frame(matrix(as.numeric(NA), 1, I*J + I + J)) }else{ samples = data.frame(matrix(as.numeric(NA), 1, I*J + J + J)) } }else{ if(fixedMargin == "rows"){ pi_star = rdirichlet( iterations, rowSums(data) + J*a ) omega = rdirichlet( iterations, colSums(data) + a ) pi_ij = t(sapply(1:iterations, function(i){ as.vector(outer( pi_star[i,], omega[i,] )) })) }else{ pi_star = rdirichlet( iterations, colSums(data) + I*a ) omega = rdirichlet( iterations, rowSums(data) + a ) pi_ij = t(sapply(1:iterations, function(i){ as.vector(outer( omega[i,], pi_star[i,] )) })) } samples = data.frame( pi_ij, pi_star, omega ) } cn1 = paste0("pi[",outer(1:nrow(data), 1:ncol(data),paste,sep=","),"]") if(fixedMargin == "rows"){ cn2 = paste0("pi[",1:nrow(data),",*]") cn3 = paste0("omega[*,",1:ncol(data),"]") }else{ cn2 = paste0("pi[*,",1:ncol(data),"]") cn3 = paste0("omega[",1:nrow(data),",*]") } colnames(samples) = c(cn1,cn2,cn3) return(mcmc(samples)) } sampleIndepMultiContingencyAlt <- function(fixedMargin, prior, data, iterations, noSample = FALSE, ...) { a = prior I = nrow(data) J = ncol(data) if( a < 1 ) stop("Prior concentration cannot be less than 1.") if(noSample){ if(fixedMargin == "rows"){ samples = data.frame(matrix(as.numeric(NA), 1, I*J + I + I*J)) }else{ samples = data.frame(matrix(as.numeric(NA), 1, I*J + J + I*J)) } }else{ if(fixedMargin == "rows"){ pi_star = rdirichlet( iterations, rowSums(data) + J*a ) omega = t(replicate(iterations, as.vector(t(apply(data, 1, function( v ) rdirichlet( 1, v + a )))))) pi_ij = t(sapply(1:iterations, function(i){ as.vector(rep(pi_star[i,], J) * omega[i,]) })) }else{ pi_star = rdirichlet( iterations, colSums(data) + I*a ) omega = t(replicate(iterations, as.vector(apply(data, 2, function( v ) rdirichlet( 1, v + a ))))) pi_ij = t(sapply(1:iterations, function(i){ as.vector(rep(pi_star[i,], each = I ) * omega[i,]) })) } samples = data.frame( pi_ij, pi_star, omega ) } cn1 = paste0("pi[",outer(1:nrow(data), 1:ncol(data),paste,sep=","),"]") if(fixedMargin == "rows"){ cn2 = paste0("pi[",1:nrow(data),",*]") }else{ cn2 = paste0("pi[*,",1:ncol(data),"]") } cn3 = paste0("omega[",outer(1:nrow(data), 1:ncol(data),paste,sep=","),"]") colnames(samples) = c(cn1,cn2,cn3) return(mcmc(samples)) } sampleHypergeomContingencyNull <- function(prior, data, iterations, noSample = FALSE, ...) { if( prior < 1 ) stop("Prior concentration cannot be less than 1.") if(noSample){ samples = data.frame(matrix(as.numeric(NA), 1)) }else{ samples = data.frame(matrix(0, iterations, 1)) } colnames(samples) = c("log.odds.ratio") return(mcmc(samples)) } sampleHypergeomContingencyAlt <- function(prior, data, iterations, noSample = FALSE, ...) { if( prior < 1 ) stop("Prior concentration cannot be less than 1.") if(noSample){ samples = data.frame(matrix(as.numeric(NA), 1)) }else{ stop("Sampling for this model not yet implemented.") } colnames(samples) = c("log.odds.ratio") return(mcmc(samples)) } rdirichlet <- function(n, alpha) { l <- length(alpha) x <- matrix(stats::rgamma(l * n, alpha), ncol = l, byrow = TRUE) sm <- x %*% rep(1, l) x / as.vector(sm) }
/scratch/gouwar.j/cran-all/cranData/BayesFactor/R/contingency-utility.R
##' This function computes Bayes factors for contingency tables. ##' ##' The Bayes factor provided by \code{contingencyTableBF} tests the independence assumption in ##' contingency tables under various sampling plans, each of which is described below. ##' See Gunel and Dickey (1974) for more details. ##' ##' For \code{sampleType="poisson"}, the sampling plan is assumed to be ##' one in which observations occur as a poisson process with an overall ##' rate, and then assignment to particular factor levels occurs with ##' fixed probability. Under the null hypothesis, the assignments to the ##' two factors are independent. Importantly, the total N is not fixed. ##' ##' For \code{sampleType="jointMulti"} (joint multinomial), the sampling ##' plan is assumed to be one in which the total N is fixed, and observations ##' are assigned to cells with fixed probability. Under the null hypothesis, the ##' assignments to the two factors are independent. ##' ##' For \code{sampleType="indepMulti"} (independent multinomial), the ##' sampling plan is assumed to be one in which row or column totals are fixed, ##' and each row or column is assumed to be multinomially distributed. ##' Under the null hypothesis, each row or column is assumed to have the ##' same multinomial probabilities. The fixed margin must be given by ##' the \code{fixedMargin} argument. ##' ##' For \code{sampleType="hypergeom"} (hypergeometric), the sampling ##' plan is assumed to be one in which both the row and column totals are fixed. ##' Under the null hypothesis, the cell counts are assumed to be governed by the ##' hypergeometric distribution. ##' ##' For all models, the argument \code{priorConcentration} indexes ##' the expected deviation from the null hypothesis under the alternative, ##' and corresponds to Gunel and Dickey's (1974) "a" parameter. ##' ##' @title Function for Bayesian analysis of one- and two-sample designs ##' @param x an m by n matrix of counts (integers m,n > 1) ##' @param sampleType the sampling plan (see details) ##' @param fixedMargin for the independent multinomial sampling plan, which margin is fixed ("rows" or "cols") ##' @param priorConcentration prior concentration parameter, set to 1 by default (see details) ##' @param posterior if \code{TRUE}, return samples from the posterior instead ##' of Bayes factor ##' @param callback callback function for third-party interfaces ##' @param ... further arguments to be passed to or from methods. ##' @return If \code{posterior} is \code{FALSE}, an object of class ##' \code{BFBayesFactor} containing the computed model comparisons is ##' returned. ##' ##' If \code{posterior} is \code{TRUE}, an object of class \code{BFmcmc}, ##' containing MCMC samples from the posterior is returned. ##' @export ##' @keywords htest ##' @author Richard D. Morey (\email{richarddmorey@@gmail.com}) ##' @author Tahira Jamil (\email{tahjamil@@gmail.com}) ##' @references Gunel, E. and Dickey, J., (1974) ##' Bayes Factors for Independence in Contingency Tables. Biometrika, 61, 545-557 ##' ##' @note Posterior sampling for the hypergeometric model under the alternative ##' has not yet been implemented. ##' ##' @examples ##' ## Hraba and Grant (1970) doll race data ##' data(raceDolls) ##' ##' ## Compute Bayes factor for independent binomial design, with ##' ## columns as the fixed margin ##' bf = contingencyTableBF(raceDolls, sampleType = "indepMulti", fixedMargin = "cols") ##' bf ##' ##' ## Posterior distribution of difference in probabilities, under alternative ##' chains = posterior(bf, iterations = 10000) ##' sameRaceGivenWhite = chains[,"pi[1,1]"] / chains[,"pi[*,1]"] ##' sameRaceGivenBlack = chains[,"pi[1,2]"] / chains[,"pi[*,2]"] ##' hist(sameRaceGivenWhite - sameRaceGivenBlack, xlab = "Probability increase", ##' main = "Increase in probability of child picking\nsame race doll (white - black)", ##' freq=FALSE, yaxt='n') ##' box() ##' contingencyTableBF <- function(x, sampleType, fixedMargin = NULL, priorConcentration = 1, posterior = FALSE, callback = function(...) as.integer(0), ...) { x.mat = as.matrix(as.integer(x)) dim(x.mat) = dim(x) x = as.data.frame(x.mat) if( sampleType == "indepMulti" ) if( is.null(fixedMargin) ){ stop("Argument fixedMargin ('rows' or 'cols') required with independent multinomial sampling plan.") }else if( !(fixedMargin %in% c("rows","cols")) ){ stop("Argument fixedMargin must be either 'rows' or 'cols'.") } checkCallback(callback,as.integer(0)) numerator = switch(sampleType, poisson = BFcontingencyTable(type = "poisson", identifier = list(formula = "non-independence"), prior=list(a=priorConcentration), shortName = paste0("Non-indep. (a=",priorConcentration,")"), longName = paste0("Alternative, non-independence, a = ", priorConcentration)), jointMulti = BFcontingencyTable(type = "joint multinomial", identifier = list(formula = "non-independence"), prior=list(a=priorConcentration), shortName = paste0("Non-indep. (a=",priorConcentration,")"), longName = paste0("Alternative, non-independence, a = ", priorConcentration)), indepMulti = BFcontingencyTable(type = "independent multinomial", identifier = list(formula = "non-independence", fixedMargin = fixedMargin), prior=list(a=priorConcentration, fixedMargin = fixedMargin), shortName = paste0("Non-indep. (a=",priorConcentration,")"), longName = paste0("Alternative, non-independence, a = ", priorConcentration)), hypergeom = BFcontingencyTable(type = "hypergeometric", identifier = list(formula = "non-independence"), prior=list(a=priorConcentration), shortName = paste0("Non-indep. (a=",priorConcentration,")"), longName = paste0("Alternative, non-independence, a = ", priorConcentration)), stop("Unknown value of sampleType (see help for contingencyTableBF).") ) if(posterior){ chains = posterior(numerator, data = x, callback = callback, ...) checkCallback(callback,as.integer(1000)) return(chains) }else{ bf = compare(numerator = numerator, data = x) checkCallback(callback,as.integer(1000)) return(bf) } }
/scratch/gouwar.j/cran-all/cranData/BayesFactor/R/contingency.R
## The code in this file is from the JASP project ## (https://github.com/jasp-stats/jasp-desktop/blob/development/JASP-Engine/JASP/R/correlationbayesian.R) ## and written by Alexander Ly ([email protected]) .bf10Exact <- function(n, r, kappa=1) { # Ly et al 2015 # This is the exact result with symmetric beta prior on rho # with parameter alpha. If kappa = 1 then uniform prior on rho # # if (n <= 2){ return(list(bf = 0, properror=0,method="exact")) } else if (any(is.na(r))){ return(list(bf = NA, properror=NA,method=NA)) } # TODO: use which check.r <- abs(r) >= 1 # check whether |r| >= 1 if (kappa >= 1 && n > 2 && check.r) { return(list(bf = Inf, properror=0,method="exact")) } #log.hyper.term <- log(hypergeo::hypergeo(((n-1)/2), ((n-1)/2), ((n+2/kappa)/2), r^2)) log.hyper.term <- Re( genhypergeo_series_pos(U=c((n-1)/2, (n-1)/2), L=((n+2/kappa)/2), z=r^2, 0, 2000, TRUE, TRUE, FALSE) ) log.result <- (1-2/kappa)*log(2)+0.5*log(pi)-lbeta(1/kappa, 1/kappa)+ lgamma((n+2/kappa-1)/2)-lgamma((n+2/kappa)/2)+log.hyper.term real.result <- log.result return(list(bf = real.result, properror=0,method="exact")) } # 2.2 Two-sided secondary Bayes factor .bf10JeffreysIntegrate <- function(n, r, kappa=1) { # Jeffreys' test for whether a correlation is zero or not # Jeffreys (1961), pp. 289-292 # This is the exact result, see EJ ## if (n <= 2){ return(list(bf = 0, properror=0,method="exact")) } else if ( any(is.na(r)) ){ return(list(bf = NA, properror=NA,method=NA)) } # TODO: use which if (n > 2 && abs(r)==1) { return(list(bf = Inf, properror=0,method="exact")) } hyper.term <- Re( genhypergeo_series_pos(U=c((2*n-3)/4, (2*n-1)/4), L=(n+2/kappa)/2, z=r^2, 0, 2000, TRUE, TRUE, FALSE) ) log.term <- lgamma((n+2/kappa-1)/2)-lgamma((n+2/kappa)/2)-lbeta(1/kappa, 1/kappa) result <- .5*log(pi) + (1-2/kappa)*log(2) + log.term + hyper.term return(list(bf = result, properror=NA, method="Jeffreys' approximation")) } # 2.3 Two-sided third Bayes factor .bfCorNumerical <- function(n, r, kappa=1, lowerRho=-1, upperRho=1, approx = TRUE) { # Numerically integrate Jeffreys approximation of the likelihood if(approx){ likeFun = jeffreys_approx_corr }else{ likeFun = function(rho,n,r){ hFunc(rho, n, r, FALSE, 2000) } } log.const = likeFun(r,n,r) integrand <- Vectorize(function(rho){ exp(likeFun(rho, n, r) + dbeta(rho/2+.5,1/kappa,1/kappa,log=TRUE) - log(2) - log.const) },"rho") some.integral <- try(integrate(integrand, lowerRho, upperRho)) if (is(some.integral, "try-error")) { return(NULL) } if (some.integral$message=="OK"){ some.integral$value = exp(log(some.integral$value) + log.const) return(some.integral) } else { return(NULL) } } .bf10Numerical <- function(n, r, kappa=1, lowerRho=-1, upperRho=1,approx=TRUE) { # Jeffreys' test for whether a correlation is zero or not # Jeffreys (1961), pp. 289-292 # This is a numerical approximation for .bf10JeffreysIntegrate, # when it explodes # # # TODO: 1. check for n=1, n=2, as r is then undefined # 2. check for r=1, r=-1 # # TODO: REMOVE ALL NUMERICAL STUFF if ( any(is.na(r)) ){ return(list(bf = NA, properror=NA, method=NA)) } # TODO: use which if (n > 2 && abs(r)==1) { return(list(bf = Inf, properror=0, method="exact")) } # TODO: be very careful here, might integrate over non-finite function jeffreysNumericalIntegrate <- .bfCorNumerical(n, r, kappa, lowerRho=-1, upperRho=1,approx) if (is.null(jeffreysNumericalIntegrate)){ return(list(bf = NA, properror=NA, method=NA)) }else if(jeffreysNumericalIntegrate$value < 0){ return(list(bf = NA, properror=NA, method=NA)) } else if (jeffreysNumericalIntegrate$value >= 0){ # jeffreys numerical integrate success log.bf = log(jeffreysNumericalIntegrate$value) err = jeffreysNumericalIntegrate$abs.error prop.error = exp(log(err) - log.bf) return(list(bf = log.bf, properror=err, method="quadrature")) } else { # NO IDEA, EVERYTHING FAILED :( return(list(bf = NA, properror=NA, method=NA)) } return(list(bf = NA, properror=NA, method=NA)) }
/scratch/gouwar.j/cran-all/cranData/BayesFactor/R/correlation-JASP.R
makeCorrHypothesisNames = function(rscale, nullInterval=NULL){ if(is.null(nullInterval)){ shortName = paste("Alt., r=",round(rscale,3),sep="") longName = paste("Alternative, r = ",rscale,", rho =/= 0", sep="") }else{ if(!is.null(attr(nullInterval,"complement"))){ shortName = paste("Alt., r=",round(rscale,3)," !(",nullInterval[1],"<rho<",nullInterval[2],")",sep="") longName = paste("Alternative, r = ",rscale,", rho =/= 0 !(",nullInterval[1],"<rho<",nullInterval[2],")",sep="") }else{ shortName = paste("Alt., r=",round(rscale,3)," ",nullInterval[1],"<rho<",nullInterval[2],sep="") longName = paste("Alternative, r = ",rscale,", rho =/= 0 ",nullInterval[1],"<rho<",nullInterval[2],sep="") } } return(list(shortName=shortName,longName=longName)) } corr.test.bf.interval <- function(y, x, rscale, nullInterval){ intervalProb = pbeta(nullInterval/2+.5, 1/rscale, 1/rscale, log.p=TRUE) prior.interval = logExpXminusExpY(intervalProb[2], intervalProb[1]) r = cor(y, x, use="pairwise.complete.obs") n = length(x) - sum(is.na(y) | is.na(x)) # if(n != length(x)) note(paste("Ignored",sum(is.na(y) | is.na(x)), # "rows containing missing observations.")) intgl = .bfCorNumerical(n, r, rscale, nullInterval[1], nullInterval[2]) val = log(intgl$value) - prior.interval err = NA return( list( bf = val, properror = err, method = "mixed" ) ) } corr.test.bf <- function(y, x, rscale, nullInterval, complement){ if(length(nullInterval)!=2 & !is.null(nullInterval)) stop("argument interval must have two elements.") r = cor(y, x, use="pairwise.complete.obs") n = length(x) - sum(is.na(y) | is.na(x)) if(n != length(x)) message(paste("Ignored",sum(is.na(y) | is.na(x)), "rows containing missing observations.")) if(is.null(nullInterval)){ return(.bf10Exact(n, r, rscale)) } interval = range(nullInterval) if(nullInterval[1]<=-1 & nullInterval[2]>=1){ if(complement){ return(list(bf=NA,properror=NA)) }else{ return(return(.bf10Exact(n, r, rscale))) } } if(any(abs(nullInterval)>=1)){ bf = corr.test.bf.interval(y, x, rscale, nullInterval) if(interval[1]<=-1){ bf.compl = corr.test.bf.interval(y, x, rscale, c(nullInterval[2], 1)) }else{ bf.compl = corr.test.bf.interval(y, x, rscale, c(-1,nullInterval[1])) } }else{ logPriorProbs = pbeta(c(-1,nullInterval,1)/2+.5, 1/rscale, 1/rscale, log.p=TRUE) prior.interval1 = logExpXminusExpY(logPriorProbs[2], logPriorProbs[1]) prior.interval3 = logExpXminusExpY(logPriorProbs[4], logPriorProbs[3]) prior.interval.1.3 = logMeanExpLogs(c(prior.interval1,prior.interval3)) + log(2) bf1 = corr.test.bf.interval(y, x, rscale, c(-1,nullInterval[1])) bf = corr.test.bf.interval(y, x, rscale, nullInterval) bf3 = corr.test.bf.interval(y, x, rscale, c(nullInterval[2],1)) bf.compl = sumWithPropErr(bf1[['bf']] + prior.interval1, bf3[['bf']] + prior.interval3, bf1[['properror']], bf3[['properror']]) bf.compl[1] = bf.compl[1] - prior.interval.1.3 } if(complement){ return( list( bf = bf.compl[[1]], properror = bf.compl[[2]], method = "quadrature" )) }else{ return( list( bf = bf[['bf']], properror = bf[['properror']], method = bf[['method']] )) } } correlation.Metrop <- function(y, x, nullModel, iterations=10000, nullInterval=NULL, rscale, progress=getOption('BFprogress', interactive()), noSample=FALSE, callback = NULL, callbackInterval = 1){ if(length(y)!=length(x)) stop("lengths of y and x must be equal.") iterations = as.integer(iterations) progress = as.logical(progress) if(is.null(callback) | !is.function(callback)) callback=function(...) as.integer(0) if(is.null(nullInterval) | nullModel){ doInterval = FALSE nullInterval = c(-1, 1) intervalCompl = FALSE }else{ doInterval = TRUE intervalCompl = ifelse(!is.null(attr(nullInterval,"complement")),TRUE,FALSE) nullInterval = range(nullInterval) } r = cor(y, x, use="pairwise.complete.obs") n = length(x) - sum(is.na(y) | is.na(x)) if(n != length(x)) message(paste("Ignored",sum(is.na(y) | is.na(x)), "rows containing missing observations.")) if(noSample){ chains = matrix(as.numeric(NA),1,1) }else{ if(nullModel) rscale = 0 chains = metropCorrRcpp_jeffreys(r, n, 1/rscale, 1/rscale, TRUE, iterations, doInterval, .5*log((1+nullInterval)/(1-nullInterval)), intervalCompl, nullModel, progress, callback, callbackInterval) if(!nullModel & !noSample){ acc.rate = mean(diff(chains) != 0) message("Independent-candidate M-H acceptance rate: ",round(100*acc.rate),"%") } } chains = mcmc(data.frame(chains)) return(chains) }
/scratch/gouwar.j/cran-all/cranData/BayesFactor/R/correlation-utility.R
##' Bayes factors or posterior samples for correlations. ##' ##' The Bayes factor provided by \code{ttestBF} tests the null hypothesis that ##' the true linear correlation \eqn{\rho}{rho} between two samples (\eqn{y}{y} and \eqn{x}{x}) ##' of size \eqn{n}{n} from normal populations is equal to 0. The Bayes factor is based on Jeffreys (1961) ##' test for linear correlation. Noninformative priors are assumed for the population means and ##' variances of the two population; a shifted, scaled beta(1/rscale,1/rscale) prior distribution ##' is assumed for \eqn{\rho}{rho} (note that \code{rscale} is called \eqn{\kappa}{kappa} by ##' Ly et al. 2015; we call it \code{rscale} for consistency with other BayesFactor functions). ##' ##' For the \code{rscale} argument, several named values are recognized: ##' "medium.narrow", "medium", "wide", and "ultrawide". These correspond ##' to \eqn{r} scale values of \eqn{1/\sqrt(27)}{1/sqrt(27)}, \eqn{1/3}{1/3}, ##' \eqn{1/\sqrt(3)}{1/sqrt(3)} and 1, respectively. ##' ##' The Bayes factor is computed via several different methods. ##' @title Function for Bayesian analysis of correlations ##' @param y first continuous variable ##' @param x second continuous variable ##' @param rscale prior scale. A number of preset values can be given as ##' strings; see Details. ##' @param nullInterval optional vector of length 2 containing ##' lower and upper bounds of an interval hypothesis to test, in correlation units ##' @param posterior if \code{TRUE}, return samples from the posterior instead ##' of Bayes factor ##' @param callback callback function for third-party interfaces ##' @param ... further arguments to be passed to or from methods. ##' @return If \code{posterior} is \code{FALSE}, an object of class ##' \code{BFBayesFactor} containing the computed model comparisons is ##' returned. If \code{nullInterval} is defined, then two Bayes factors will ##' be computed: The Bayes factor for the interval against the null hypothesis ##' that the probability is 0, and the corresponding Bayes factor for ##' the complement of the interval. ##' ##' If \code{posterior} is \code{TRUE}, an object of class \code{BFmcmc}, ##' containing MCMC samples from the posterior is returned. ##' @export ##' @keywords htest ##' @author Richard D. Morey (\email{richarddmorey@@gmail.com}) ##' @examples ##' bf = correlationBF(y = iris$Sepal.Length, x = iris$Sepal.Width) ##' bf ##' ## Sample from the corresponding posterior distribution ##' samples = correlationBF(y = iris$Sepal.Length, x = iris$Sepal.Width, ##' posterior = TRUE, iterations = 10000) ##' plot(samples[,"rho"]) ##' @seealso \code{\link{cor.test}} ##' @references Ly, A., Verhagen, A. J. & Wagenmakers, E.-J. (2015). ##' Harold Jeffreys's Default Bayes Factor Hypothesis Tests: Explanation, Extension, and Application in Psychology. ##' Journal of Mathematical Psychology, Available online 28 August 2015, https://dx.doi.org/10.1016/j.jmp.2015.06.004. ##' ##' Jeffreys, H. (1961). Theory of probability, 3rd edn. Oxford, UK: Oxford University Press. correlationBF <- function(y, x, rscale = "medium", nullInterval = NULL, posterior=FALSE, callback = function(...) as.integer(0), ...) { if(!is.null(nullInterval)){ if(any(nullInterval< -1) | any(nullInterval>1)) stop("nullInterval endpoints must be in [-1,1].") nullInterval = range(nullInterval) } rscale = rpriorValues("correlation",,rscale) if( length(y) != length(x) ) stop("Length of y and x must be the same.") if(!is.null(nullInterval)) if(any(abs(nullInterval)>1)) stop("Invalid interval hypothesis; endpoints must be in [-1,1].") if( length(y)<3 ) stop("N must be >2.") n = length(x) - sum(is.na(y) | is.na(x)) if(n < 3) stop("Need at least 3 complete observations.") hypNames = makeCorrHypothesisNames(rscale, nullInterval) mod1 = BFcorrelation(type = "Jeffreys-beta*", identifier = list(formula = "rho =/= 0", nullInterval = nullInterval), prior=list(rscale=rscale, nullInterval = nullInterval), shortName = hypNames$shortName, longName = hypNames$longName ) data = data.frame(y = y, x = x) checkCallback(callback,as.integer(0)) if(posterior) return(posterior(mod1, data = data, callback = callback, ...)) bf1 = compare(numerator = mod1, data = data) if(!is.null(nullInterval)){ mod2 = mod1 attr(mod2@identifier$nullInterval, "complement") = TRUE attr(mod2@prior$nullInterval, "complement") = TRUE hypNames = makeCorrHypothesisNames(rscale, mod2@identifier$nullInterval) mod2@shortName = hypNames$shortName mod2@longName = hypNames$longName bf2 = compare(numerator = mod2, data = data) checkCallback(callback,as.integer(1000)) return(c(bf1, bf2)) }else{ checkCallback(callback,as.integer(1000)) return(c(bf1)) } }
/scratch/gouwar.j/cran-all/cranData/BayesFactor/R/correlationBF.R
Qg <- function(q,sumSq,N,XtCnX,CnytCnX,rscale,gMap,gMapCounts,priorX=NULL,incCont=0,limit=TRUE) { qLimits = getOption('BFapproxLimits', c(-15,15)) zz = jzs_log_marginal_posterior_logg(q, sumSq, N, XtCnX, CnytCnX, rscale, gMap, gMapCounts, priorX, incCont, limit, qLimits, which = 0) return(zz[["d0g"]]) } dQg <- function(q,sumSq,N,XtCnX,CnytCnX,rscale,gMap, gMapCounts, priorX=NULL, incCont=0) { zz = jzs_log_marginal_posterior_logg(q, sumSq, N, XtCnX, CnytCnX, rscale, gMap, gMapCounts, priorX, incCont, FALSE, c(-Inf,Inf), which = 1) return(zz[['d1g']]) } d2Qg <- function(q,sumSq,N,XtCnX,CnytCnX,rscale,gMap,gMapCounts,priorX=NULL,incCont=0) { zz = jzs_log_marginal_posterior_logg(q, sumSq, N, XtCnX, CnytCnX, rscale, gMap, gMapCounts, priorX, incCont, FALSE, c(-Inf, Inf), which = 2) return(zz[['d2g']]) } hessianQg <- function(q,sumSq,N,XtCnX,CnytCnX,rscale,gMap,gMapCounts,priorX=NULL,incCont=0) { diag(d2Qg(q,sumSq,N,XtCnX,CnytCnX,rscale,gMap,gMapCounts,priorX,incCont)) } Qg_nlm <- function(q,sumSq,N,XtCnX,CnytCnX,rscale,gMap,gMapCounts,priorX=NULL,incCont=0) { zz = jzs_log_marginal_posterior_logg(q, sumSq, N, XtCnX, CnytCnX, rscale, gMap, gMapCounts, priorX, incCont, FALSE, c(-Inf,Inf), which = 2) res = -zz[['d0g']] attr(res, "gradient") <- -zz[['d1g']] attr(res, "hessian") <- -zz[['d2g']] return(res) } gaussianApproxAOV <- function(y,X,rscale,gMap,incCont=0) { optMethod = getOption('BFapproxOptimizer', 'optim') # dumb starting values qs = rscale * 0 N = length(y) if(!incCont){ priorX = matrix(1,0,0) }else if(incCont == 1){ priorX = matrix(sum(X[,1]^2),1,1) / N }else{ priorX = crossprod(X[,1:incCont]) / N } Cny = matrix(y - mean(y), N) CnX = t(t(X) - colMeans(X)) XtCnX = crossprod(CnX) CnytCnX = crossprod(Cny, CnX) sumSq = var(y) * (N-1) gMapCounts = table(gMap) if(optMethod=="optim"){ opt = optim(qs, Qg, gr = dQg,control=list(fnscale=-1),method="BFGS",sumSq=sumSq,N=N,XtCnX=XtCnX,CnytCnX=CnytCnX,rscale=rscale,gMap=gMap,gMapCounts=gMapCounts,priorX=priorX,incCont=incCont) if(opt$convergence) stop("Convergence not achieved in optim: ",opt$convergence) mu = opt$par val = opt$value }else if(optMethod=="nlm"){ opt = nlm(Qg_nlm, qs, sumSq=sumSq,N=N,XtCnX=XtCnX,CnytCnX=CnytCnX,rscale=rscale,gMap=gMap,gMapCounts=gMapCounts, priorX=priorX,incCont=incCont, hessian=FALSE, check.analyticals=FALSE) if(opt$code>2) stop("Convergence not achieved in nlm: ",opt$code) val = -opt$minimum mu = opt$estimate }else{ stop("unknown method in gaussianApproxAOV: ",optMethod) } hess = hessianQg(mu,sumSq=sumSq,N=N,XtCnX=XtCnX,CnytCnX=CnytCnX,rscale=rscale,gMap=gMap,gMapCounts=gMapCounts,priorX=priorX,incCont=incCont) sig2 = -1/diag(hess) return(list(mu=mu,sig=sqrt(sig2),val=val)) } laplaceAOV <- function(y,X,rscale,gMap,incCont=0) { apx = gaussianApproxAOV(y,X,rscale,gMap,incCont) approxVal = sum(dnorm(apx$mu,apx$mu,apx$sig,log=TRUE)) apx$val - approxVal }
/scratch/gouwar.j/cran-all/cranData/BayesFactor/R/gaussApproxAOV.R
requiredFor = Vectorize(function(t1,t2){ t1 = unique(unlist(strsplit(t1,":",fixed=TRUE))) t2 = unique(unlist(strsplit(t2,":",fixed=TRUE))) return(all(t1 %in% t2)) },c("t1","t2")) ##' Generate lists of nested models, given a model formula ##' ##' This is a backend function not intended for users. It is exposed for third-party ##' applications. ##' @title Function for generation of nested linear models ##' @param fmla formula for the "full" model ##' @param whichModels which subsets of models to generate ##' @param neverExclude a character vector of terms to never remove ##' @param includeBottom Include the base model containing only \code{neverExclude} terms ##' @param data a data frame containing the columns mentioned in \code{fmla} ##' @keywords internal enumerateGeneralModels = function(fmla, whichModels, neverExclude=NULL, includeBottom=TRUE, data=NULL){ trms <- attr(terms(fmla, data = data), "term.labels") # Remove everything we never exclude, to replace them later logicalToInclude = filterVectorLogical(neverExclude,trms) if(any(logicalToInclude)){ alwaysIncluded = trms[logicalToInclude] if(whichModels=="withmain"){ rq = matrix(outer(trms,alwaysIncluded,requiredFor),nrow=length(trms)) rq = apply(rq,1,any) logicalToInclude[rq] = TRUE alwaysIncluded = unique(c(trms[rq], alwaysIncluded)) } alwaysIncludedString = paste(alwaysIncluded,collapse=" + ") } trms = trms[!logicalToInclude] ntrms <- length(trms) dv = stringFromFormula(fmla[[2]]) dv = composeTerm(dv) if(ntrms == 0 ) return(list(fmla)) if(ntrms == 1 ) whichModels = "all" if(whichModels=="top"){ lst = combn2( trms, ntrms - 1 ) }else if(whichModels=='bottom'){ lst = as.list(combn( trms, 1 )) }else if(whichModels=="all"){ lst = combn2( trms, 1 ) }else if(whichModels=="withmain"){ if(any(logicalToInclude)){ lst = possibleRestrictionsWithMainGeneral( trms, alwaysIncluded ) }else{ lst = possibleRestrictionsWithMainGeneral( trms, NULL ) } }else{ stop("Unknown whichModels value: ",whichModels) } strng <- sapply(lst,function(el, suffix){ paste(el,collapse=" + ") }) # Add back in the terms to always include if(any(logicalToInclude)){ strng <- sapply(strng,function(el, suffix){ paste(el,suffix,collapse=" + ",sep=" + ") },suffix=alwaysIncludedString) if(includeBottom) strng <- c(strng,alwaysIncludedString) } strng <- unique(strng) fmlaOut <- lapply(strng, function(el){ formula(paste(dv,"~", el)) }) return(fmlaOut) } possibleRestrictionsWithMainGeneralFallback <- function(trms, alwaysKept){ ntrms = length( trms ) if(ntrms==1) return(NULL) thisLevelRestrictions = lapply(1:ntrms,function(i, trms, alwaysKept ){ removed = unlist(strsplit(trms[i],":",fixed=TRUE)) remaining = trms[-i] containsRemoved = sapply(remaining,function(el){ splt = unlist(strsplit(el,":",fixed=TRUE)) all(removed %in% splt) }) if(any(containsRemoved)){ return(NULL) }else{ return(remaining) } },trms=trms,alwaysKept=alwaysKept) thisLevelRestrictions = thisLevelRestrictions[!sapply(thisLevelRestrictions, is.null)] nextLevelRestrictions <- lapply(thisLevelRestrictions, possibleRestrictionsWithMainGeneralFallback, alwaysKept=alwaysKept) bothLevelRestrictions = c(thisLevelRestrictions,unlist(nextLevelRestrictions,recursive=FALSE)) bothLevelRestrictions = bothLevelRestrictions[!sapply(bothLevelRestrictions, is.null)] return(unique(bothLevelRestrictions)) } possibleRestrictionsWithMainGeneral <- function(trms, alwaysKept=NULL){ if(length(trms)==1) return(list(trms)) myFactors = unique(unlist(decomposeTerms(trms))) nFactors = length(myFactors) # If there are more than 5 factors involved then the total number of models is # over 7 million; fall back to search-based method (becase there may not be # that many) if(nFactors>getOption('BFfactorsMax', 5)){ warning("Falling back to slow recursive method of enumerating models due to many factors.") retList = possibleRestrictionsWithMainGeneralFallback(trms, alwaysKept) return(c(retList,list(trms))) } myTerms = sapply(1:(2^nFactors-1),makeTerm,factors=myFactors) # These terms MUST be in the model toKeep = rev(myTerms) %termin% alwaysKept # These terms should not be in the model, because they were not in the original # specification toDiscard = !(rev(myTerms) %termin% c(trms, alwaysKept)) # The specified full model, specified as TRUE/FALSE on the list of terms row = rep(FALSE,2^nFactors-1) row[termMatch(c(trms,alwaysKept),rev(myTerms))]=TRUE # Get all possible models with nFactors factors, as matrix mb = monotoneBooleanNice(nFactors) mb = mb[-c(1,2),-ncol(mb)] if(dim(mb)[1]==0) stop("No models left in analysis. Please check that your model is valid under 'withmain'.") # Remove rows that have include invalidRows = apply(mb,1,function(v) any(v[toDiscard])) mb = matrix(mb[!invalidRows,], ncol = ncol(mb)) if(dim(mb)[1]==0) stop("No models left in analysis. Please check that your model is valid under 'withmain'.") # Remove rows that do NOT include required terms validRows = apply(mb,1,function(v) all(v[toKeep])) mb = matrix(mb[validRows,], ncol = ncol(mb)) if(dim(mb)[1]==0) stop("No models left in analysis. Please check that your model is valid under 'withmain'.") # Get all submodels of the specified model subMods = subModelsMatrix(row,mb) # Turn logicals into term numbers myModels = apply(subMods,1,function(v) rev(((length(v):1))[v])) if(nrow(subMods)==1){ retVec = myTerms[myModels] # eliminate anything that should be always kept, to be added in later retVec = retVec[!(retVec %termin% alwaysKept)] if(length(retVec)>0){ return(list(retVec)) }else{ return(NULL) } }else{ retList = lapply(myModels, function(v){ retVec = myTerms[v] # eliminate anything that should be always kept, to be added in later retVec = retVec[!(retVec %termin% alwaysKept)] if(length(retVec)>0){ return(retVec) }else{ return(NULL) } }) return(retList[!sapply(retList, is.null)]) } } subModelsMatrix<-function(row,monoBool){ if(length(row) != ncol(monoBool)) stop("Invalid number of terms in submodel") rows = apply(monoBool,1,function(v) all(row[v])) rowNum = which(apply(monoBool,1,function(v) all(row==v))) if(!any(rows)) return(matrix(row,nrow=1)) retMatrix = matrix(monoBool[rows,],nrow=sum(rows)) if(length(rowNum)>0){ return(retMatrix) }else{ return(rbind(retMatrix,row)) } }
/scratch/gouwar.j/cran-all/cranData/BayesFactor/R/generalTest-utility.R
##' This function computes Bayes factors corresponding to restrictions on a full model. ##' ##' See the help for \code{\link{anovaBF}} and \code{\link{anovaBF}} or details. ##' ##' Models, priors, and methods of computation are provided in Rouder et al. ##' (2012) and Liang et al (2008). ##' ##' @title Function to compute Bayes factors for general designs ##' @param formula a formula containing the full model for the analysis ##' (see Examples) ##' @param data a data frame containing data for all factors in the formula ##' @param whichRandom a character vector specifying which factors are random ##' @param whichModels which set of models to compare; see Details ##' @param neverExclude a character vector containing a regular expression (see ##' help for \link{regex} for details) that indicates which terms to always keep ##' in the analysis ##' @param iterations How many Monte Carlo simulations to generate, if relevant ##' @param progress if \code{TRUE}, show progress with a text progress bar ##' @param rscaleFixed prior scale for standardized, reduced fixed effects. A ##' number of preset values can be given as strings; see Details. ##' @param rscaleRandom prior scale for standardized random effects ##' @param rscaleCont prior scale for standardized slopes ##' @param rscaleEffects A named vector of prior settings for individual factors, ##' overriding rscaleFixed and rscaleRandom. Values are scales, names are factor names. ##' @param multicore if \code{TRUE} use multiple cores through the \code{doMC} ##' package. Unavailable on Windows. ##' @param method approximation method, if needed. See \code{\link{nWayAOV}} for ##' details. ##' @param noSample if \code{TRUE}, do not sample, instead returning NA. ##' @return An object of class \code{BFBayesFactor}, containing the computed ##' model comparisons ##' @param callback callback function for third-party interfaces ##' @author Richard D. Morey (\email{richarddmorey@@gmail.com}) ##' @export ##' @references ##' Rouder, J. N., Morey, R. D., Speckman, P. L., Province, J. M., (2012) ##' Default Bayes Factors for ANOVA Designs. Journal of Mathematical ##' Psychology. 56. p. 356-374. ##' ##' Liang, F. and Paulo, R. and Molina, G. and Clyde, M. A. and ##' Berger, J. O. (2008). Mixtures of g-priors for Bayesian Variable ##' Selection. Journal of the American Statistical Association, 103, pp. ##' 410-423 ##' ##' @note The function \code{generalTestBF} can compute Bayes factors for all ##' restrictions of a full model against the null ##' hypothesis that all effects are 0. The total number of tests ##' computed -- if all tests are requested -- will be \eqn{2^K-1}{2^K - 1} ##' for \eqn{K} factors or covariates. ##' This number increases very quickly with the number of tested predictors. An option is included to ##' prevent testing too many models: \code{options('BFMaxModels')}, which defaults to 50,000, is ##' the maximum number of models that will be analyzed at once. This can ##' be increased by increased using \code{\link{options}}. ##' ##' It is possible to reduce the number of models tested by only testing the ##' most complex model and every restriction that can be formed by removing ##' one factor or interaction using the \code{whichModels} argument. See the ##' help for \code{\link{anovaBF}} for details. ##' ##' @examples ##' ## Puzzles example: see ?puzzles and ?anovaBF ##' data(puzzles) ##' ## neverExclude argument makes sure that participant factor ID ##' ## is in all models ##' result = generalTestBF(RT ~ shape*color + ID, data = puzzles, whichRandom = "ID", ##' neverExclude="ID", progress=FALSE) ##' result ##' ##' @keywords htest ##' @seealso \code{\link{lmBF}}, for testing specific models, and ##' \code{\link{regressionBF}} and \code{anovaBF} for other functions for ##' testing multiple models simultaneously. generalTestBF <- function(formula, data, whichRandom = NULL, whichModels = "withmain", neverExclude=NULL, iterations = 10000, progress = getOption('BFprogress', interactive()), rscaleFixed = "medium", rscaleRandom = "nuisance", rscaleCont="medium", rscaleEffects = NULL, multicore = FALSE, method="auto", noSample=FALSE, callback=function(...) as.integer(0)) { data <- marshallTibble(data) checkFormula(formula, data, analysis = "lm") # pare whichRandom down to terms that appear in the formula whichRandom <- whichRandom[whichRandom %in% fmlaFactors(formula, data)[-1]] dataTypes <- createDataTypes(formula, whichRandom, data, analysis = "lm") models = enumerateGeneralModels(formula, whichModels, neverExclude, includeBottom = whichModels!="top", data = data) if(length(models)>getOption('BFMaxModels', 50000)) stop("Maximum number of models exceeded (", length(models), " > ",getOption('BFMaxModels', 50000) ,"). ", "The maximum can be increased by changing ", "options('BFMaxModels').") if(multicore){ message("Note: Progress bars and callbacks are suppressed when running multicore.") if(!requireNamespace("doMC", quietly = TRUE)){ stop("Required package (doMC) missing for multicore functionality.") } doMC::registerDoMC() if(foreach::getDoParWorkers()==1){ warning("Multicore specified, but only using 1 core. Set options(cores) to something >1.") } bfs <- foreach::"%dopar%"( foreach::foreach(gIndex=models, .options.multicore=mcoptions), lmBF(gIndex,data = data, whichRandom = whichRandom, rscaleFixed = rscaleFixed, rscaleRandom = rscaleRandom, rscaleCont = rscaleCont, rscaleEffects = rscaleEffects, iterations = iterations, method=method, progress=FALSE,noSample=noSample) ) }else{ # Single core checkCallback(callback,as.integer(0)) bfs = NULL myCallback <- function(prgs){ frac <- (i - 1 + prgs/1000)/length(models) ret <- callback(frac*1000) return(as.integer(ret)) } if(progress){ pb = txtProgressBar(min = 0, max = length(models), style = 3) }else{ pb = NULL } for(i in 1:length(models)){ oneModel <- lmBF(models[[i]],data = data, whichRandom = whichRandom, rscaleFixed = rscaleFixed, rscaleRandom = rscaleRandom, rscaleCont = rscaleCont, rscaleEffects = rscaleEffects, iterations = iterations, progress = FALSE, method = method,noSample=noSample,callback=myCallback) if(inherits(pb,"txtProgressBar")) setTxtProgressBar(pb, i) bfs = c(bfs,oneModel) } if(inherits(pb,"txtProgressBar")) close(pb) checkCallback(callback,as.integer(1000)) } # combine all the Bayes factors into one BFBayesFactor object bfObj = do.call("c", bfs) if(whichModels=="top") bfObj = BFBayesFactorTop(bfObj) return(bfObj) }
/scratch/gouwar.j/cran-all/cranData/BayesFactor/R/generalTestBF.R
##' Using the classical R^2 test statistic for (linear) regression designs, this ##' function computes the corresponding Bayes factor test. ##' ##' This function can be used to compute the Bayes factor corresponding to a ##' multiple regression, using the classical R^2 (coefficient of determination) ##' statistic. It can be used when you don't have access to the full data set ##' for analysis by \code{\link{lmBF}}, but you do have the test statistic. ##' ##' For details about the model, see the help for \code{\link{regressionBF}}, ##' and the references therein. ##' ##' The Bayes factor is computed via Gaussian quadrature. ##' @title Use R^2 statistic to compute Bayes factor for regression designs ##' @param N number of observations ##' @param p number of predictors in model, excluding intercept ##' @param R2 proportion of variance accounted for by the predictors, excluding ##' intercept ##' @param rscale numeric prior scale ##' @param simple if \code{TRUE}, return only the Bayes factor ##' @return If \code{simple} is \code{TRUE}, returns the Bayes factor (against the ##' intercept-only null). If \code{FALSE}, the function returns a ##' vector of length 3 containing the computed log(e) Bayes factor, ##' along with a proportional error estimate on the Bayes factor and the method used to compute it. ##' @author Richard D. Morey (\email{richarddmorey@@gmail.com}) and Jeffrey N. ##' Rouder (\email{rouderj@@missouri.edu}) ##' @keywords htest ##' @export ##' @references Liang, F. and Paulo, R. and Molina, G. and Clyde, M. A. and ##' Berger, J. O. (2008). Mixtures of g-priors for Bayesian Variable ##' Selection. Journal of the American Statistical Association, 103, pp. ##' 410-423 ##' ##' Rouder, J. N. and Morey, R. D. (in press, Multivariate Behavioral Research). Bayesian testing in ##' regression. ##' ##' @seealso \code{\link{integrate}}, \code{\link{lm}}; see ##' \code{\link{lmBF}} for the intended interface to this function, using ##' the full data set. ##' @examples ##' ## Use attitude data set ##' data(attitude) ##' ## Scatterplot ##' lm1 = lm(rating~complaints,data=attitude) ##' plot(attitude$complaints,attitude$rating) ##' abline(lm1) ##' ## Traditional analysis ##' ## p value is highly significant ##' summary(lm1) ##' ##' ## Bayes factor ##' ## The Bayes factor is over 400,000; ##' ## the data strongly favor hypothesis that ##' ## the slope is not 0. ##' result = linearReg.R2stat(30,1,0.6813) ##' exp(result[['bf']]) linearReg.R2stat=function(N,p,R2,rscale="medium", simple = FALSE) { rscale = rpriorValues("regression",,rscale) if(p<1) stop("Number of predictors must be >0") if(p>=(N-1)) stop("Number of predictors must be less than N - 1 (number of data points minus 1).") if( (R2>=1) | (R2<0) ) stop("Illegal R2 value (must be 0 <= R2 < 1)") ### Compute approximation to posterior mode of g ### Liang et al Eq. A.3, assuming a=b=0 g3 = -(1 - R2) * (p + 3) #* g^3 g2 = (N - p - 4 - 2 * (1 - R2)) #* g^2 g1 = (N * (2 - R2) - 3) #*g g0 = N sol = polyroot(c(g0, g1, g2, g3)) ## Pick the real solution modeg = Re(sol[which.min(Im(sol)^2)]) if(modeg<=0) modeg = N/20 log.const = integrand.regression.u(0, N, p , R2, rscaleSqr=rscale^2, log=TRUE, shift=log(modeg)) h=integrate(integrand.regression.u,lower=-Inf,upper=Inf,N=N,p=p,R2=R2,rscaleSqr=rscale^2,log.const=log.const,shift=log(modeg)) properror = exp(log(h[[2]]) - log(h[[1]])) bf = log(h$value) + log.const if(simple){ return(c(B10=exp(bf))) }else{ return(list(bf=bf, properror=properror, method="quadrature")) } }
/scratch/gouwar.j/cran-all/cranData/BayesFactor/R/linearReg_R2stat.R
##' This function computes Bayes factors, or samples from the posterior, of ##' specific linear models (either ANOVA or regression). ##' ##' This function provides an interface for computing Bayes factors for ##' specific linear models against the intercept-only null; other tests may be ##' obtained by computing two models and dividing their Bayes factors. Specifics ##' about the priors for regression models -- and possible settings for ##' \code{rscaleCont} -- can be found in the help for \code{\link{regressionBF}}; ##' likewise, details for ANOVA models -- and settings for \code{rscaleFixed} ##' and \code{rscaleRandom} -- can be found in the help for \code{\link{anovaBF}}. ##' ##' Currently, the function does not allow for general linear models, containing ##' both continuous and categorical predcitors, but this support will be added ##' in the future. ##' @title Function to compute Bayes factors for specific linear models ##' @param formula a formula containing all factors to include in the analysis ##' (see Examples) ##' @param data a data frame containing data for all factors in the formula ##' @param whichRandom a character vector specifying which factors are random ##' @param rscaleFixed prior scale for standardized, reduced fixed effects. A ##' number of preset values can be given as strings; see Details. ##' @param rscaleRandom prior scale for standardized random effects ##' @param rscaleCont prior scale for standardized slopes. A ##' number of preset values can be given as strings; see Details. ##' @param rscaleEffects A named vector of prior settings for individual factors, ##' overriding rscaleFixed and rscaleRandom. Values are scales, names are factor names. ##' @param posterior if \code{TRUE}, return samples from the posterior ##' distribution instead of the Bayes factor ##' @param progress if \code{TRUE}, show progress with a text progress bar ##' @param ... further arguments to be passed to or from methods. ##' @return If \code{posterior} is \code{FALSE}, an object of class ##' \code{BFBayesFactor}, containing the computed model comparisons is ##' returned. Otherwise, an object of class \code{BFmcmc}, containing MCMC ##' samples from the posterior is returned. ##' @author Richard D. Morey (\email{richarddmorey@@gmail.com}) ##' @export ##' @keywords htest ##' @examples ##' ## Puzzles data; see ?puzzles for details ##' data(puzzles) ##' ## Bayes factor of full model against null ##' bfFull = lmBF(RT ~ shape + color + shape:color + ID, data = puzzles, whichRandom = "ID") ##' ##' ## Bayes factor of main effects only against null ##' bfMain = lmBF(RT ~ shape + color + ID, data = puzzles, whichRandom = "ID") ##' ##' ## Compare the main-effects only model to the full model ##' bfMain / bfFull ##' ##' ## sample from the posterior of the full model ##' samples = lmBF(RT ~ shape + color + shape:color + ID, ##' data = puzzles, whichRandom = "ID", posterior = TRUE, ##' iterations = 1000) ##' ##' ## Aother way to sample from the posterior of the full model ##' samples2 = posterior(bfFull, iterations = 1000) ##' @seealso \code{\link{regressionBF}} and \code{anovaBF} for ##' testing many regression or ANOVA models simultaneously. lmBF <- function(formula, data, whichRandom = NULL, rscaleFixed="medium", rscaleRandom="nuisance", rscaleCont="medium", rscaleEffects=NULL, posterior=FALSE,progress=getOption('BFprogress', interactive()), ...) { data <- marshallTibble(data) data <- reFactorData(data) checkFormula(formula, data, analysis="lm") dataTypes <- createDataTypes(formula, whichRandom = whichRandom, data = data, analysis="lm") rscales = list(fixed=rpriorValues("allNways","fixed",rscaleFixed), random=rpriorValues("allNways","random",rscaleRandom), continuous=rpriorValues("regression",,rscaleCont), effects=rscaleEffects) numerator = BFlinearModel(type = "JZS", identifier = list(formula = stringFromFormula(formula)), prior=list(rscale=rscales), dataTypes = dataTypes, shortName = paste(stringFromFormula(formula[[3]]),sep=""), longName = paste(stringFromFormula(formula),sep="") ) if(posterior){ chains = posterior(numerator, data = data, progress=progress, ...) return(chains) }else{ bf = compare(numerator = numerator, data = data, progress=progress, ...) return(bf) } }
/scratch/gouwar.j/cran-all/cranData/BayesFactor/R/lmBF.R
#'Functions to compute the logarithm of the mean (and cumulative means) of #'vectors of logarithms #' #'Given a vector of numeric values of real values represented in log form, #'\code{logMeanExpLogs} computes the logarithm of the mean of the #'(exponentiated) values. \code{logCumMeanExpLogs} computes the logarithm of #'the cumulative mean. #' #'Given a vector of values of log values \var{v}, one could compute #'\code{log(mean(exp(v)))} in R. However, exponentiating and summing will cause #'a loss of precision, and possibly an overflow. These functions use the #'identity \deqn{\log(e^a + e^b) = a + \log(1+e^{b-a})}{log(e^a + e^b) = a + #'log[ 1 + e^(b-a) ]} and the method of computing \eqn{\log(1+e^x)}{log(1+e^x)} #'that avoids overflow (see the references). The code is written in C for very #'fast computations. #' #'@aliases logMeanExpLogs logCumMeanExpLogs logSummaryStats #'@param v A vector of (log) values #'@return \code{logMeanExpLogs} returns a single value, #'\code{logCumMeanExpLogs} returns a vector of values of the same length as #'\var{v}, and \code{logSummaryStats} returns a list of the #'log mean, log variance, and cumulative log means. #'@author Richard D. Morey (\email{richarddmorey@@gmail.com}) #'@references For details of the approximation of \eqn{\log(1+e^x)}{log(1+e^x)} #'used to prevent loss of precision, see #'\url{https://www.codeproject.com/Articles/25294/Avoiding-Overflow-Underflow-and-Loss-of-Precision} and #'\url{https://www.johndcook.com/blog/standard_deviation/}. #'@keywords arith misc #'@examples #' #'# Sample 100 values #'y = log(rexp(100,1)) #' #'# These will give the same value, #'# since e^y is "small" #'logMeanExpLogs(y) #'log(mean(exp(y))) #' #'# We can make e^x overflow by multiplying #'# e^y by e^1000 #'largeVals = y + 1000 #' #'# This will return 1000 + log(mean(exp(y))) #'logMeanExpLogs(largeVals) #' #'# This will overflow #'log(mean(exp(largeVals))) #' logMeanExpLogs = function(v) { logSummaryStats(v)$logMean } logCumMeanExpLogs = function(v) { logSummaryStats(v)$cumLogMean }
/scratch/gouwar.j/cran-all/cranData/BayesFactor/R/logMean.R
#'Opens the HTML manual for the BayesFactor package #' #'This function opens the HTML manual for the BayesFactor package in whatever #'browser is configured. #' #'This function opens the HTML manual for the BayesFactor package in whatever #'browser is configured. #'@return \code{BFManual} returns \code{NULL} invisibly. #'@author Richard D. Morey (\email{richarddmorey@@gmail.com}) #'@keywords misc #'@export BFManual <- function(){ vignette('index', package = 'BayesFactor') }
/scratch/gouwar.j/cran-all/cranData/BayesFactor/R/manual.R
makeMetaTtestHypothesisNames = function(rscale, nullInterval=NULL){ if(is.null(nullInterval)){ shortName = paste("Alt., r=",round(rscale,3),sep="") longName = paste("Alternative, r = ",rscale,", delta =/= 0", sep="") }else{ if(!is.null(attr(nullInterval,"complement"))){ shortName = paste("Alt., r=",round(rscale,3)," !(",nullInterval[1],"<d<",nullInterval[2],")",sep="") longName = paste("Alternative, r = ",rscale,", delta =/= 0 !(",nullInterval[1],"<d<",nullInterval[2],")",sep="") }else{ shortName = paste("Alt., r=",round(rscale,3)," ",nullInterval[1],"<d<",nullInterval[2],sep="") longName = paste("Alternative, r = ",rscale,", delta =/= 0 ",nullInterval[1],"<d<",nullInterval[2],sep="") } } return(list(shortName=shortName,longName=longName)) } meta.ttest.tstat <- function(t,n1,n2=NULL,nullInterval=NULL,rscale, complement = FALSE) { if( ((length(n1) != length(n2)) & !is.null(n2)) | (length(n1) != length(t))){ stop("Number of t statistics must equal number of sample sizes.") } if(!is.null(n2)){ rscale = rpriorValues("ttestTwo",,rscale) }else{ rscale = rpriorValues("ttestOne",,rscale) } if(is.null(n2)){ nu = n1 - 1 n <- n1 }else{ nu = n1 + n2 - 2 n <- n1 * n2 / (n1 + n2) } if( any(n < 1) | any(nu < 1)) stop("Insufficient sample size for t analysis.") if(any(is.infinite(t))) stop("At least one t statistic is infinite.") if(is.null(nullInterval)){ return(meta.t.bf(t,n,nu,rscale=rscale)) }else{ return(meta.t.bf(t,n,nu,interval=nullInterval,rscale=rscale, complement = complement)) } } meta.t.bf <- function(t,N,df,interval=NULL,rscale, complement = FALSE){ if(length(interval)!=2 & !is.null(interval)) stop("argument interval must have two elements.") if(is.null(interval)){ return(meta.bf.interval(-Inf,Inf,t,N,df,rscale)) } interval = range(interval) if(interval[1]==-Inf & interval[2]==Inf){ if(complement){ return(list(bf=NA,properror=NA,method=NA)) }else{ return(meta.bf.interval(-Inf,Inf,t,N,df,rscale)) } } if(any(is.infinite(interval))){ if(!complement){ bf = meta.bf.interval(interval[1],interval[2],t,N,df,rscale) }else{ if( ( interval[1]==-Inf ) ){ bf.compl = meta.bf.interval(interval[2],Inf,t,N,df,rscale) }else{ bf.compl = meta.bf.interval(-Inf,interval[1],t,N,df,rscale) } } }else{ logPriorProbs = pcauchy(c(-Inf,interval,Inf),scale=rscale,log.p=TRUE) prior.interval1 = logExpXminusExpY(logPriorProbs[2], logPriorProbs[1]) prior.interval3 = logExpXminusExpY(logPriorProbs[4], logPriorProbs[3]) prior.interval.1.3 = logExpXplusExpY(prior.interval1,prior.interval3) bf1 = meta.bf.interval(-Inf,interval[1],t,N,df,rscale) bf = meta.bf.interval(interval[1],interval[2],t,N,df,rscale) bf3 = meta.bf.interval(interval[2],Inf,t,N,df,rscale) if(complement){ bf.compl = sumWithPropErr(bf1[['bf']] + prior.interval1, bf3[['bf']] + prior.interval3, bf1[['properror']], bf3[['properror']]) bf.compl[1] = bf.compl[1] - prior.interval.1.3 } } if(complement){ return( list( bf = bf.compl[[1]], properror = bf.compl[[2]], method = "Savage-Dickey t approximation" )) }else{ return( list( bf = bf[['bf']], properror = bf[['properror']], method = bf[['method']] )) } } meta.bf.interval <- function(lower,upper,t,N,df,rscale){ nullLike = sum(dt(t,df,log=TRUE)) logPriorProbs = pcauchy(c(upper,lower),scale=rscale,log.p=TRUE) prior.interval = logExpXminusExpY(logPriorProbs[1], logPriorProbs[2]) delta.est = t/sqrt(N) mean.delta = sum((delta.est * N)/sum(N)) scale.delta = 1/sqrt(sum(N)) log.const = meta.t.like(mean.delta,t,N,df,rscale,log=TRUE) intgl = integrate(meta.t.like, lower = (lower-mean.delta)/scale.delta, upper = (upper-mean.delta)/scale.delta, t=t,N=N,df=df,rscale=rscale,log.const=log.const, shift=mean.delta,scale=scale.delta) if(intgl[[1]] == 0 || is.nan(intgl[[1]]) || is.na(intgl[[1]])){ message("t approximation invoked.") return(meta.bf.interval_approx(lower,upper,t,N,df,rscale)) } val = log(intgl[[1]]*scale.delta) + log.const - prior.interval - nullLike err = exp(log(intgl[[2]]) - val) return( list( bf = val, properror = err, method = "quadrature" ) ) } meta.t.like <- Vectorize(function(delta,t,N,df,rscale=1,log.const=0,log=FALSE,shift=0,scale=1){ ans = suppressWarnings( sum(dt(t,df,ncp=(scale*delta + shift)*sqrt(N),log=TRUE)) + dcauchy(scale*delta+shift,scale=rscale,log=TRUE) - log.const ) if(log){ return(ans) }else{ return(exp(ans)) } },"delta") meta.t.Metrop <- function(t, n1, n2=NULL, nullModel, iterations=10000, nullInterval=NULL, rscale, progress=getOption('BFprogress', interactive()), noSample=FALSE, callback = NULL, callbackInterval = 1){ if(length(t)!=length(n1)) stop("lengths of t and n1 must be equal.") if(!is.null(n2)){ if(length(t) != length(n2)) stop("If n2 is defined, it must have the same length as t.") } iterations = as.integer(iterations) if( is.null(n2) ){ n2 = n1*0 twoSample = FALSE }else{ twoSample = TRUE } progress = as.logical(progress) if(is.null(callback) | !is.function(callback)) callback=function(...) as.integer(0) if(is.null(nullInterval) | nullModel){ doInterval = FALSE nullInterval = c(-Inf, Inf) intervalCompl = FALSE }else{ doInterval = TRUE intervalCompl = ifelse(!is.null(attr(nullInterval,"complement")),TRUE,FALSE) nullInterval = range(nullInterval) } if(noSample){ chains = matrix(as.numeric(NA),1,1) }else{ if(nullModel) rscale = 0 chains = metropMetaTRcpp(t, n1, n2, twoSample, rscale, iterations, doInterval, nullInterval, intervalCompl, nullModel, progress, callback, callbackInterval) if(!nullModel & !noSample){ acc.rate = mean(diff(chains) != 0) message("Independent-candidate M-H acceptance rate: ",round(100*acc.rate),"%") } } return(mcmc(data.frame(delta=chains))) } meta.bf.interval_approx <- function(lower,upper,t,N,df,rscale){ ## Using t approximation to posterior of delta delta.est = t/sqrt(N) mean.delta = sum((delta.est * N)/sum(N)) var.delta = 1/sum(N) logPriorProbs = pcauchy(c(upper,lower),scale=rscale,log.p=TRUE) logPostProbs = pt((c(upper,lower) - mean.delta)/sqrt(var.delta),sum(df),log.p=TRUE) prior.interval = logExpXminusExpY(logPriorProbs[1], logPriorProbs[2]) post.interval = logExpXminusExpY(logPostProbs[1], logPostProbs[2]) log.bf.interval = post.interval - prior.interval log.bf.point = meta.bf.interval(-Inf, Inf, t, N, df, rscale) if(lower == -Inf & upper == Inf){ val = log.bf.point$bf err = log.bf.point$properror }else{ val = log.bf.interval + log.bf.point$bf err = NA } return( list( bf = val, properror = err, method = "t approximation to posterior" ) ) }
/scratch/gouwar.j/cran-all/cranData/BayesFactor/R/meta-ttest-utility.R
##' This function computes mata-analytic Bayes factors, or samples from the posterior, for ##' one- and two-sample designs where multiple t values have been observed. ##' ##' The Bayes factor provided by \code{meta.ttestBF} tests the null hypothesis that ##' the true effect size (or alternatively, the noncentrality parameters) underlying a ##' set of t statistics is 0. Specifically, the Bayes factor compares two ##' hypotheses: that the standardized effect size is 0, or that the standardized ##' effect size is not 0. Note that there is assumed to be a single, common effect size ##' \eqn{\delta}{delta} underlying all t statistics. For one-sample tests, the standardized effect size is ##' \eqn{(\mu-\mu_0)/\sigma}{(mu-mu0)/sigma}; for two sample tests, the ##' standardized effect size is \eqn{(\mu_2-\mu_1)/\sigma}{(mu2-mu1)/sigma}. ##' ##' A Cauchy prior is placed on the standardized effect size. ##' The \code{rscale} argument controls the scale of the prior distribution, ##' with \code{rscale=1} yielding a standard Cauchy prior. See the help for ##' \code{\link{ttestBF}} and the references below for more details. ##' ##' The Bayes factor is computed via Gaussian quadrature. Posterior samples are ##' drawn via independent-candidate Metropolis-Hastings. ##' @title Function for Bayesian analysis of one- and two-sample designs ##' @param t a vector of t statistics ##' @param n1 a vector of sample sizes for the first (or only) condition ##' @param n2 a vector of sample sizes. If \code{NULL}, a one-sample design is assumed ##' @param nullInterval optional vector of length 2 containing lower and upper bounds of ##' an interval hypothesis to test, in standardized units ##' @param rscale prior scale. A number of preset values can be given as ##' strings; see Details. ##' @param posterior if \code{TRUE}, return samples from the posterior instead ##' of Bayes factor ##' @param callback callback function for third-party interfaces ##' @param ... further arguments to be passed to or from methods. ##' @return If \code{posterior} is \code{FALSE}, an object of class ##' \code{BFBayesFactor} containing the computed model comparisons is ##' returned. If \code{nullInterval} is defined, then two Bayes factors will ##' be computed: The Bayes factor for the interval against the null hypothesis ##' that the standardized effect is 0, and the corresponding Bayes factor for ##' the compliment of the interval. ##' ##' If \code{posterior} is \code{TRUE}, an object of class \code{BFmcmc}, ##' containing MCMC samples from the posterior is returned. ##' @export ##' @keywords htest ##' @author Richard D. Morey (\email{richarddmorey@@gmail.com}) ##' @references Morey, R. D. & Rouder, J. N. (2011). Bayes Factor Approaches for Testing ##' Interval Null Hypotheses. Psychological Methods, 16, 406-419 ##' ##' Rouder, J. N., Speckman, P. L., Sun, D., Morey, R. D., & Iverson, G. ##' (2009). Bayesian t-tests for accepting and rejecting the null hypothesis. ##' Psychonomic Bulletin & Review, 16, 225-237 ##' ##' Rouder, J. N. & Morey, R. D. (2011). A Bayes Factor Meta-Analysis of Bem's ESP Claim. ##' Psychonomic Bulletin & Review, 18, 682-689 ##' @note To obtain the same Bayes factors as Rouder and Morey (2011), ##' change the prior scale to 1. ##' @examples ##' ## Bem's (2010) data (see Rouder & Morey, 2011) ##' t=c(-.15,2.39,2.42,2.43) ##' N=c(100,150,97,99) ##' ##' ## Using rscale=1 and one-sided test to be ##' ## consistent with Rouder & Morey (2011) ##' bf = meta.ttestBF(t, N, rscale=1, nullInterval=c(0, Inf)) ##' bf[1] ##' ##' ## plot posterior distribution of delta, assuming alternative ##' ## turn off progress bar for example ##' samples = posterior(bf[1], iterations = 1000, progress = FALSE) ##' ## Note that posterior() respects the nullInterval ##' plot(samples) ##' summary(samples) ##' @seealso \code{\link{ttestBF}} meta.ttestBF <- function(t, n1, n2 = NULL, nullInterval = NULL, rscale="medium", posterior=FALSE, callback = function(...) as.integer(0), ...) { rscale = rpriorValues(ifelse(is.null(n2),"ttestOne","ttestTwo"),,rscale) hypNames = makeMetaTtestHypothesisNames(rscale, nullInterval) data = data.frame(t=t,n1=n1) if(!is.null(n2)) data$n2 = n2 if(!is.null(nullInterval)){ nullInterval = range(nullInterval) if(identical(nullInterval,c(-Inf,Inf))){ nullInterval = NULL } } mod1 = BFmetat(type = "JZS", identifier = list(formula = "delta =/= 0", nullInterval = nullInterval), prior=list(rscale=rscale, nullInterval = nullInterval), shortName = hypNames$shortName, longName = hypNames$longName ) if(posterior) return(posterior(mod1, data = data, callback = callback, ...)) bf1 = compare(numerator = mod1, data = data) if(!is.null(nullInterval)){ mod2 = mod1 attr(mod2@identifier$nullInterval, "complement") = TRUE attr(mod2@prior$nullInterval, "complement") = TRUE hypNames = makeMetaTtestHypothesisNames(rscale, mod2@identifier$nullInterval) mod2@shortName = hypNames$shortName mod2@longName = hypNames$longName bf2 = compare(numerator = mod2, data = data) return(c(bf1, bf2)) }else{ return(c(bf1)) } }
/scratch/gouwar.j/cran-all/cranData/BayesFactor/R/meta.ttestBF.R
# constructor BFBayesFactor <- function(numerator, denominator, bayesFactor, data){ names(numerator) = rownames(bayesFactor) new("BFBayesFactor", numerator = numerator, denominator = denominator, bayesFactor = bayesFactor, data = data, version = BFInfo(FALSE)) } setValidity("BFBayesFactor", function(object){ if( length(object@numerator) != nrow(object@bayesFactor)) return("Number of numerator models does not equal number of Bayes factors.") numeratorsAreBFs = sapply(object@numerator,function(el) inherits(el,"BFmodel")) if( any(!numeratorsAreBFs)) return("Some numerators are not BFmodel objects.") # check numerators all have same data types as denominator dataTypeDenom = object@denominator@dataTypes dataTypesEqual = unlist(lapply(object@numerator, function(model, compType) model@dataTypes %com% compType, compType=dataTypeDenom)) if( any(!dataTypesEqual)) return("Data types are not equal across models.") typeDenom = object@denominator@type typesEqual = unlist(lapply(object@numerator, function(model, compType) identical(model@type, compType), compType=typeDenom)) if( any(!typesEqual)) return("Model types are not equal across models.") classDenom = class(object@denominator) typesEqual = unlist(lapply(object@numerator, function(model, compType) identical(class(model), compType), compType=classDenom)) if( any(!typesEqual)) return("Model classes are not equal across models.") # Check to see that Bayes factor data frame has required columns if( !all(colnames(object@bayesFactor) %in% c("bf", "error", "time", "code")) ) return("Object does not have required columns (bf, error, time, code).") return(TRUE) }) #' @rdname recompute-methods #' @aliases recompute,BFBayesFactor-method setMethod("recompute", "BFBayesFactor", function(x, progress = getOption('BFprogress', interactive()), multicore = FALSE, callback = function(...) as.integer(0), ...){ modelList = c(x@numerator,x@denominator) if(multicore){ callback = function(...) as.integer(0) message("Note: Progress bars and callbacks are suppressed when running multicore.") if( !suppressMessages( requireNamespace("doMC", quietly = TRUE) ) ){ stop("Required package (doMC) missing for multicore functionality.") } doMC::registerDoMC() if(foreach::getDoParWorkers()==1){ warning("Multicore specified, but only using 1 core. Set options(cores) to something >1.") } bfs = foreach::"%dopar%"( foreach::foreach(gIndex=modelList, .options.multicore=mcoptions), compare(numerator = gIndex, data = x@data, ...) ) }else{ # No multicore checkCallback(callback,as.integer(0)) bfs = NULL myCallback <- function(prgs){ frac <- (i - 1 + prgs/1000)/length(modelList) ret <- callback(frac*1000) return(as.integer(ret)) } if(progress){ pb = txtProgressBar(min = 0, max = length(modelList), style = 3) }else{ pb = NULL } for(i in 1:length(modelList)){ oneModel <- compare(numerator = modelList[[i]], data = x@data, progress=FALSE, callback=myCallback, ...) if(inherits(pb,"txtProgressBar")) setTxtProgressBar(pb, i) bfs = c(bfs,oneModel) } if(inherits(pb,"txtProgressBar")) close(pb) checkCallback(callback,as.integer(1000)) } joined = do.call("c", bfs) numerators = joined[ 1:(length(joined)-1) ] denominator = joined[ length(joined) ] return(numerators / denominator) }) #' @rdname BFBayesFactor-class #' @name /,numeric,BFBayesFactor-method #' @param e1 Numerator of the ratio #' @param e2 Denominator of the ratio setMethod('/', signature("numeric", "BFBayesFactor"), function(e1, e2){ if( (e1 == 1) & (length(e2)==1) ){ numer = e2@numerator[[1]] denom = list(e2@denominator) bf_df = e2@bayesFactor rownames(bf_df) = denom[[1]]@shortName bf_df$bf = -bf_df$bf bfobj = BFBayesFactor(numerator=denom, denominator=numer, bayesFactor=bf_df, data=e2@data) return(bfobj) }else if( e1 != 1 ){ stop("Dividend must be 1 (to take reciprocal).") }else if( length(e2)>1 ){ allNum = as(e2,"list") BFlist = BFBayesFactorList(lapply(allNum, function(num) 1 / num)) } } ) #' @rdname BFBayesFactor-class #' @name /,BFBayesFactor,BFBayesFactor-method setMethod('/', signature("BFBayesFactor", "BFBayesFactor"), function(e1, e2){ if( !(e1@denominator %same% e2@denominator) ) stop("Bayes factors have different denominator models; they cannot be compared.") if( !identical(e1@data, e2@data) ) stop("Bayes factors were computed using different data; they cannot be compared.") if( (length(e2)==1) ){ errorEst = sqrt(e1@bayesFactor$error^2 + e2@bayesFactor$error^2) bfs = data.frame(bf=e1@bayesFactor$bf - e2@bayesFactor$bf, error = errorEst, time = date(), code = randomString(length(e1))) rownames(bfs) = rownames(e1@bayesFactor) # when bayes factors were computed at the same time or for the same model, # they must be exactly equal (no error) sameModel <- sapply(e1@numerator, function(num, den) num %same% den, den = e2@numerator[[1]]) sameCode <- as.character(e1@bayesFactor$code) == as.character(e2@bayesFactor$code) bfs[ sameModel | sameCode, "error" ] = 0 bfs[ sameModel | sameCode, "bf" ] = 0 newbf = BFBayesFactor(numerator=e1@numerator, denominator=e2@numerator[[1]], bayesFactor=bfs, data = e1@data) return(newbf) }else{ allDenom = as(e2,"list") BFlist = BFBayesFactorList(lapply(allDenom, function(denom, num) num / denom, num = e1)) return(BFlist) } } ) setMethod('show', "BFBayesFactor", function(object){ cat("Bayes factor analysis\n--------------\n") bfs = extractBF(object, logbf=TRUE) bfs$bf = sapply(bfs$bf, expString) indices = paste("[",1:nrow(bfs),"]",sep="") # pad model names nms = paste(indices,rownames(bfs),sep=" ") maxwidth = max(nchar(nms)) nms = str_pad(nms,maxwidth,side="right",pad=" ") # pad Bayes factors maxwidth = max(nchar(bfs$bf)) bfString = str_pad(bfs$bf,maxwidth,side="right",pad=" ") for(i in 1:nrow(bfs)){ cat(nms[i]," : ",bfString[i]," \u00B1",round(bfs$error[i]*100,2),"%\n",sep="") } cat("\nAgainst denominator:\n") cat(" ",object@denominator@longName,"\n") cat("---\nBayes factor type: ",class(object@denominator)[1],", ",object@denominator@type,"\n\n",sep="") }) setMethod('summary', "BFBayesFactor", function(object){ show(object) }) #' @rdname BFBayesFactor-class #' @name [,BFBayesFactor,index,missing,missing-method #' @param x BFBayesFactor object #' @param i indices indicating elements to extract #' @param j unused for BFBayesFactor objects #' @param drop unused #' @param ... further arguments passed to related methods setMethod("[", signature(x = "BFBayesFactor", i = "index", j = "missing", drop = "missing"), function (x, i, j, ..., drop) { if((na <- nargs()) == 2){ newbf = x x@numerator = x@numerator[i, drop=FALSE] x@bayesFactor = x@bayesFactor[i, ,drop=FALSE] }else stop("invalid nargs()= ",na) return(x) }) #' @rdname extractBF-methods #' @aliases extractBF,BFBayesFactor-method setMethod("extractBF", "BFBayesFactor", function(x, logbf = FALSE, onlybf = FALSE){ x = x@bayesFactor if(!logbf) x$bf = exp(x$bf) if(onlybf) x = x$bf return(x) }) #' @rdname BFBayesFactor-class #' @name t,BFBayesFactor-method setMethod('t', "BFBayesFactor", function(x){ return(t.BFBayesFactor(x)) }) setAs("BFBayesFactor", "data.frame", function( from, to ){ as.data.frame.BFBayesFactor(from) }) setAs("BFBayesFactor" , "list", function ( from , to ){ vec = vector(mode = "list", length = length(from) ) for(i in 1:length(from)) vec[[i]] = from[i] return(vec) }) setAs("BFBayesFactor", "vector", function( from, to ){ as.vector.BFBayesFactor(from) }) #' @rdname BFBayesFactor-class #' @name which.max,BFBayesFactor-method setMethod("which.max", "BFBayesFactor", function(x) which.max.BFBayesFactor(x) ) #' @rdname BFBayesFactor-class #' @name which.min,BFBayesFactor-method setMethod("which.min", "BFBayesFactor", function(x) which.min.BFBayesFactor(x) ) #' @rdname BFBayesFactor-class #' @name is.na,BFBayesFactor-method setMethod("is.na", "BFBayesFactor", function(x) is.na.BFBayesFactor(x) ) #' @rdname BFBayesFactor-class #' @name *,BFBayesFactor,BFodds-method setMethod('*', signature("BFBayesFactor", "BFodds"), function(e1, e2){ return(e2 * e1) } ) ###### # S3 ###### ##' This function coerces objects to the BFBayesFactor class ##' ##' Function to coerce objects to the BFBayesFactor class ##' ##' Currently, this function will only work with objects of class ##' \code{BFBayesFactorTop}, which are output from the functions \code{anovaBF} ##' and \code{regressionBF} when the \code{whichModels} argument is set to ##' \code{'top'} ##' @title Function to coerce objects to the BFBayesFactor class ##' @param object an object of appropriate class (for now, BFBayesFactorTop) ##' @return An object of class \code{BFBayesFactor} ##' @author Richard D. Morey (\email{richarddmorey@@gmail.com}) ##' @export ##' @keywords misc ##' @seealso \code{\link{regressionBF}}, \code{anovaBF} whose output is ##' appropriate for use with this function when \code{whichModels='top'} as.BFBayesFactor <- function(object) UseMethod("as.BFBayesFactor") is.na.BFBayesFactor <- function(x){ return(is.na(x@bayesFactor$bf)) } names.BFBayesFactor <- function(x) { num <- sapply(x@numerator, function(el) el@shortName) den <- x@denominator@shortName return(list(numerator=num,denominator=den)) } length.BFBayesFactor <- function(x) nrow(x@bayesFactor) # See https://www-stat.stanford.edu/~jmc4/classInheritance.pdf sort.BFBayesFactor <- function(x, decreasing = FALSE, ...){ ord = order(x@bayesFactor$bf, decreasing = decreasing) return(x[ord]) } max.BFBayesFactor <- function(..., na.rm=FALSE){ joinedbf = do.call('c',list(...)) el <- head(joinedbf, n=1) return(el) } min.BFBayesFactor <- function(..., na.rm=FALSE){ joinedbf = do.call('c',list(...)) el <- tail(joinedbf, n=1) return(el) } which.max.BFBayesFactor <- function(x){ index = which.max(x@bayesFactor$bf) names(index) = rownames(x@bayesFactor)[index] return(index) } which.min.BFBayesFactor <- function(x){ index = which.min(x@bayesFactor$bf) names(index) = rownames(x@bayesFactor)[index] return(index) } t.BFBayesFactor <- function(x){ 1/x } head.BFBayesFactor <- function(x, n=6L, ...){ n = ifelse(n>length(x),length(x),n) x = sort(x, decreasing=TRUE) return(x[1:n]) } tail.BFBayesFactor <- function(x, n=6L, ...){ n = ifelse(n>length(x),length(x),n) x = sort(x) return(x[n:1])} as.data.frame.BFBayesFactor <- function(x, row.names = NULL, optional=FALSE,...){ df = x@bayesFactor df$bf = exp(df$bf) return(df) } as.vector.BFBayesFactor <- function(x, mode = "any"){ if( !(mode %in% c("any", "numeric"))) stop("Cannot coerce to mode ", mode) v = exp(x@bayesFactor$bf) names(v) = rownames(x@bayesFactor) return(v) } c.BFBayesFactor <- function(..., recursive = FALSE) { z = list(...) if(length(z)==1) return(z[[1]]) correctClass = unlist(lapply(z, function(object) inherits(object,"BFBayesFactor"))) if(any(!correctClass)) stop("Cannot concatenate Bayes factor with non-Bayes factor.") dataAndDenoms = lapply(z, function(object){list(den = object@denominator, dat = object@data)}) sameInfo = unlist(lapply(dataAndDenoms[-1], function(el, cmp){ sameType = el$dat %com% cmp$dat sameType = ifelse(length(sameType)>0,sameType,TRUE) (el$den %same% cmp$den) & sameType }, cmp=dataAndDenoms[[1]])) if(any(!sameInfo)) stop("Cannot concatenate Bayes factors with different denominator models or data.") numerators = unlist(lapply(z, function(object){object@numerator}),recursive=FALSE, use.names=FALSE) bfs = lapply(z, function(object){object@bayesFactor}) df_rownames = unlist(lapply(z, function(object){rownames(object@bayesFactor)})) df_rownames = make.unique(df_rownames, sep=" #") bfs = do.call("rbind",bfs) rownames(bfs) = df_rownames bf = BFBayesFactor(numerator=numerators, denominator=z[[1]]@denominator, bayesFactor=bfs, data = z[[1]]@data) }
/scratch/gouwar.j/cran-all/cranData/BayesFactor/R/methods-BFBayesFactor.R
BFBayesFactorList<- function(li){ col_nms = sapply(li,function(el) el@denominator@shortName) names(li) = make.unique(col_nms, sep=" #") new("BFBayesFactorList", li, version=BFInfo(FALSE)) } setValidity("BFBayesFactorList", function(object){ firstNumerator = object[[1]]@numerator sameNumerators = unlist(lapply(object, function(el, firstNumerator) { identical(el@numerator,firstNumerator) }, firstNumerator = firstNumerator)) if(any(!sameNumerators)) return("All numerators in elements of BayesFactorList must be identical") return(TRUE) }) setMethod('show', "BFBayesFactorList", function(object){ print(as(object,"matrix")) }) #' @rdname BFBayesFactorList-class #' @name t,BFBayesFactorList-method #' @param x a BFBayesFactorList object setMethod('t', "BFBayesFactorList", function(x){ return(1/x) }) #' @rdname BFBayesFactorList-class #' @name /,numeric,BFBayesFactorList-method #' @param e1 Numerator of the ratio #' @param e2 Denominator of the ratio setMethod('/', signature("numeric", "BFBayesFactorList"), function(e1, e2){ if( (e1 == 1) & (length(e2[[1]])==1) ){ bflist = lapply(e2,function(el) 1/el) return(do.call('c',bflist)) }else if( e1 != 1 ){ stop("Dividend must be 1 (to take reciprocal).") }else if( length(e2[[1]])>1 ){ vec = vector(mode = "list", length = length(e2[[1]])) for(i in 1:length(e2[[1]])){ vec[[i]] = 1/e2[i,] } bflist = BFBayesFactorList(vec) return(bflist) } } ) #' @rdname BFBayesFactorList-class #' @name [,BFBayesFactorList,index,index,missing-method #' @param i indices specifying rows to extract #' @param j indices specifying columns to extract #' @param drop unused #' @param ... further arguments passed to related methods setMethod("[", signature(x = "BFBayesFactorList", i = "index", j = "index", drop = "missing"), function (x, i, j, ..., drop) { if((na <- nargs()) == 3){ x = x[i,][,j] }else stop("invalid nargs()= ",na) return(x) }) #' @rdname BFBayesFactorList-class #' @name [,BFBayesFactorList,index,missing,missing-method setMethod("[", signature(x = "BFBayesFactorList", i = "index", j = "missing", drop = "missing"), function (x, i, j, ..., drop) { if((na <- nargs()) == 3){ bfs = lapply(x,function(el,i) el[i], i = i) x = BFBayesFactorList(bfs) }else stop("invalid nargs()= ",na) return(x) }) #' @rdname BFBayesFactorList-class #' @name [,BFBayesFactorList,missing,index,missing-method setMethod("[", signature(x = "BFBayesFactorList", i = "missing", j = "index", drop = "missing"), function (x, i, j, ..., drop) { if((na <- nargs()) == 3){ if(length(j)==1){ x = x[[j]] }else if(length(j)>1){ x = as(x, "vector") x = BFBayesFactorList(x[j]) } }else stop("invalid nargs()= ",na) return(x) }) setAs("BFBayesFactorList" , "list", function ( from , to ){ as.vector(from) }) setAs("BFBayesFactorList" , "vector", function ( from , to ){ as.vector(from) }) setAs("BFBayesFactorList" , "matrix", function ( from , to ){ as.matrix(from) }) ## S3 Methods ##### as.vector.BFBayesFactorList <- function(x, mode = "any"){ if( !(mode %in% c("any", "list"))) stop("Cannot coerce to mode ", mode) vec = vector(mode = "list", length = length(x) ) for(i in 1:length(x)) vec[[i]] = x[[i]] names(vec) = names(x) return(vec) } as.matrix.BFBayesFactorList <- function(x,...){ matr <- sapply(x, as.vector) dim(matr) <- c(length(x[[1]]),length(x)) numNames <- rownames(extractBF(x[[1]])) denNames <- names(x) dimnames(matr) = list(numerator=numNames, denominator=denNames) return(as.matrix(matr)) }
/scratch/gouwar.j/cran-all/cranData/BayesFactor/R/methods-BFBayesFactorList.R
BFBayesFactorTop <- function(bf){ if( !inherits(bf@denominator, "BFlinearModel") ) stop("BFBayesFactorTopcan only be created from linear model objects.") len = sapply(bf@numerator, function(m){ fmla = formula(m@identifier$formula) length(attr(terms(fmla),"term.labels")) }) len_denom = length(attr(terms(formula(bf@denominator@identifier$formula)),"term.labels")) if( all( len < len_denom ) ){ return(new("BFBayesFactorTop", bf)) }else if( any( len > len_denom ) ){ biggest = which(len == max(len)) if(length(biggest) != 1) stop("Could not determine full model.") if(length(bf)==1) return(new("BFBayesFactorTop", 1/bf[biggest])) return(new("BFBayesFactorTop", bf[-biggest]/bf[biggest])) }else{ stop("Could not determine full model.") } } setValidity("BFBayesFactorTop", function(object){ if(!inherits(object@denominator, "BFlinearModel")) return("BFBayesFactorTop objects can only currently be created from BFlinearModel-type models.") omitted = lapply(object@numerator, whichOmitted, full = object@denominator) lens = sapply(omitted, length) if(any(lens != 1)) return("Not all numerators are formed by removing one term from the denominator.") return(TRUE) }) setMethod('show', "BFBayesFactorTop", function(object){ omitted = unlist(lapply(object@numerator, whichOmitted, full = object@denominator)) cat("Bayes factor top-down analysis\n--------------\n") bfs = extractBF(object, logbf=TRUE) bfs$bf = sapply(bfs$bf, expString) indices = paste("[",1:nrow(bfs),"]",sep="") # pad model names nms = omitted maxwidth = max(nchar(nms)) nms = str_pad(nms,maxwidth,side="right",pad=" ") # pad Bayes factors maxwidth = max(nchar(bfs$bf)) bfString = str_pad(bfs$bf,maxwidth,side="right",pad=" ") cat("When effect is omitted from",object@denominator@shortName,", BF is...\n") for(i in 1:nrow(bfs)){ cat(indices[i]," Omit ",nms[i]," : ",bfString[i]," \u00B1",round(bfs$error[i]*100,2),"%\n",sep="") } cat("\nAgainst denominator:\n") cat(" ",object@denominator@longName,"\n") cat("---\nBayes factor type: ",class(object@denominator)[1],", ",object@denominator@type,"\n\n",sep="") }) #' @rdname BFBayesFactor-class #' @name [,BFBayesFactorTop,index,missing,missing-method setMethod("[", signature(x = "BFBayesFactorTop", i = "index", j = "missing", drop = "missing"), function (x, i, j, ..., drop) { x = as(x,"BFBayesFactor") return(BFBayesFactorTop(x[i])) }) setMethod('summary', "BFBayesFactorTop", function(object){ show(object) }) #' @rdname recompute-methods #' @aliases recompute,BFBayesFactor-method setMethod("recompute", "BFBayesFactorTop", function(x, progress = getOption('BFprogress', interactive()), multicore = FALSE, callback = function(...) as.integer(0), ...){ bf = recompute(as.BFBayesFactor(x), progress, multicore, callback, ...) BFBayesFactorTop(bf) }) setAs("BFBayesFactorTop", "BFBayesFactor", function( from, to ){ as.BFBayesFactor.BFBayesFactorTop(from) }) ######## S3 sort.BFBayesFactorTop <- function(x, decreasing = FALSE, ...){ x = as.BFBayesFactor(x) x = sort(x,decreasing = decreasing, ...) return(BFBayesFactorTop(x)) } as.BFBayesFactor.BFBayesFactorTop <- function(object){ BFBayesFactor(numerator=object@numerator, denominator=object@denominator, bayesFactor = object@bayesFactor, data = object@data) } length.BFBayesFactorTop <- function(x) length(as.BFBayesFactor(x))
/scratch/gouwar.j/cran-all/cranData/BayesFactor/R/methods-BFBayesFactorTop.R
############### Linear models setMethod('compare', signature(numerator = "BFlinearModel", denominator = "missing", data = "data.frame"), function(numerator, data, ...){ if(!.hasSlot(numerator,"analysis")) numerator@analysis = list() old.numerator = numerator rscaleFixed = rpriorValues("allNways","fixed",numerator@prior$rscale[['fixed']]) rscaleRandom = rpriorValues("allNways","random",numerator@prior$rscale[['random']]) rscaleCont = rpriorValues("regression",,numerator@prior$rscale[['continuous']]) rscaleEffects = numerator@prior$rscale[['effects']] formula = formula(numerator@identifier$formula) checkFormula(formula, data, analysis = "lm") factors = fmlaFactors(formula, data)[-1] nFactors = length(factors) dataTypes = numerator@dataTypes relevantDataTypes = dataTypes[names(dataTypes) %in% factors] dv = stringFromFormula(formula[[2]]) dv = composeTerm(dv) if(numerator@type != "JZS") stop("Unknown model type.") denominator = BFlinearModel(type = "JZS", identifier = list(formula = paste(dv,"~ 1")), prior=list(), dataTypes = dataTypes, shortName = paste("Intercept only",sep=""), longName = paste("Intercept only", sep=""), analysis = list(method="trivial") ) bf <- list(bf=NA, properror=NA, method=NA) BFtry({ if( nFactors == 0 ){ numerator = denominator bf = list(bf = 0, properror = 0, method = "trivial") }else if(all(relevantDataTypes == "continuous")){ ## Regression reg = summary(lm(formula,data=data)) R2 = reg[[8]] N = nrow(data) p = length(attr(terms(formula),"term.labels")) if( any( names( rscaleEffects ) %in% attr(terms(formula),"term.labels")) ){ stop("Continuous prior settings set from rscaleEffects; use rscaleCont instead.") } bf = linearReg.R2stat(N,p,R2,rscale=rscaleCont) }else if(all(relevantDataTypes != "continuous")){ # ANOVA or t test freqs <- table(data[[factors[1]]]) if(all(freqs==1)) stop("not enough observations") nLvls <- length(freqs) rscale = ifelse(dataTypes[factors[1]] == "fixed", rscaleFixed, rscaleRandom) if(length(rscaleEffects)>0) if(!is.na(rscaleEffects[factors[1]])) rscale = rscaleEffects[factors[1]] if( (nFactors==1) & (nLvls==2) ){ # test # independent groups t t = t.test(formula = formula,data=data, var.eq=TRUE)$statistic bf = ttest.tstat(t=t, n1=freqs[1], n2=freqs[2],rscale=rscale*sqrt(2)) }else if( (nFactors==1) & (nLvls>2) & all(freqs==freqs[1])){ # Balanced one-way Fstat = summary(aov(formula, data=data))[[1]]["F value"][1,] J = length(freqs) N = freqs[1] bf = oneWayAOV.Fstat(Fstat, N, J, rscale) }else if( (nFactors > 1) | ( (nFactors == 1) & any(freqs!=freqs[1]))){ # Nway ANOVA or unbalanced one-way ANOVA bf = nWayFormula(formula=formula, data = data, dataTypes = dataTypes, rscaleFixed = rscaleFixed, rscaleRandom = rscaleRandom, rscaleEffects = rscaleEffects, posterior = FALSE, ...) }else{ # Nothing stop("Too few levels in independent variable: ",factors[1]) } }else{ # GLM bf = nWayFormula(formula=formula, data = data, dataTypes = dataTypes, rscaleFixed = rscaleFixed, rscaleRandom = rscaleRandom, rscaleCont = rscaleCont, rscaleEffects = rscaleEffects, posterior = FALSE, ...) } }) # End try expression numerator@analysis = as.list(bf) numerator = combineModels(list(numerator,old.numerator)) bf_df = data.frame(bf = numerator@analysis[['bf']], error = numerator@analysis[['properror']], time = date(), code = randomString(1) ) rownames(bf_df) <- numerator@shortName newBF = BFBayesFactor(numerator = list(numerator), denominator = denominator, data = data, bayesFactor = bf_df ) return(newBF) } )
/scratch/gouwar.j/cran-all/cranData/BayesFactor/R/methods-BFlinearModel-compare.R
# constructors BFmodel <- function(type, identifier, prior, dataTypes, shortName, longName, analysis = list()){ new("BFmodel", type = type, identifier = identifier, prior = prior, dataTypes = dataTypes, shortName = shortName, longName = longName, analysis = analysis, version = BFInfo(FALSE)) } BFcorrelation <- function(type, identifier, prior, shortName, longName, analysis = list()){ new("BFcorrelation", type = type, identifier = identifier, prior = prior, shortName = shortName, longName = longName, analysis = analysis, version = BFInfo(FALSE)) } BFproportion <- function(type, identifier, prior, shortName, longName, analysis = list()){ new("BFproportion", type = type, identifier = identifier, prior = prior, shortName = shortName, longName = longName, analysis = analysis, version = BFInfo(FALSE)) } BFcontingencyTable <- function(type, identifier, prior, shortName, longName, analysis = list()){ new("BFcontingencyTable", type = type, identifier = identifier, prior = prior, shortName = shortName, longName = longName, analysis = analysis, version = BFInfo(FALSE)) } BFlinearModel <- function(type, identifier, prior, dataTypes, shortName, longName, analysis = list()){ new("BFlinearModel", type = type, identifier = identifier, prior = prior, dataTypes = dataTypes, shortName = shortName, longName = longName, analysis = analysis, version = BFInfo(FALSE)) } BFoneSample <- function(type, identifier, prior, shortName, longName, analysis = list()){ new("BFoneSample", type = type, identifier = identifier, prior = prior, shortName = shortName, longName = longName, analysis = analysis, version = BFInfo(FALSE)) } BFindepSample <- function(type, identifier, prior, shortName, longName, analysis = list()){ new("BFindepSample", type = type, identifier = identifier, prior = prior, shortName = shortName, longName = longName, analysis = analysis, version = BFInfo(FALSE)) } BFmetat <- function(type, identifier, prior, shortName, longName, analysis = list()){ new("BFmetat", type = type, identifier = identifier, prior = prior, shortName = shortName, longName = longName, analysis = analysis, version = BFInfo(FALSE)) } ####### setMethod('show', signature = c("BFlinearModel"), function(object){ cat("---\n Model:\n") cat("Type: ",class(object)[1],", ",object@type,"\n",sep="") cat(object@longName,"\n") cat("Data types:\n") lapply(names(object@dataTypes),function(el) cat(el,": ",object@dataTypes[el],"\n") ) cat("\n\n") } ) setMethod('show', signature = c("BFmodel"), function(object){ cat("---\n Model:\n") cat("Type: ",class(object)[1],", ",object@type,"\n",sep="") cat(object@longName,"\n") cat("\n\n") } ) setMethod("%same%", signature = c(x="BFmodel",y="BFmodel"), function(x,y){ classesSame = identical(class(x),class(y)) dataTypeSame = x@dataTypes %com% y@dataTypes slotSame = sapply(slotNames(x), function(el,x,y) identical(slot(x,el),slot(y,el)), x=x,y=y) slotSame["dataTypes"] = ifelse(length(dataTypeSame)>0,dataTypeSame, TRUE) # exclude version and analysis slotSame = slotSame[ !( names(slotSame) %in% c("version", "analysis") ) ] return(all(slotSame) & classesSame) }) setMethod('compare', signature(numerator = "BFlinearModel", denominator = "BFlinearModel", data = "data.frame"), function(numerator, denominator, data, ...){ if(!identical(numerator@type, denominator@type)) stop("Models of different types cannot be currently be compared by compare().") if(!identical(numerator@prior$mu, denominator@prior$mu)) stop("Models of different null means cannot currently be compared by compare()") if(!identical(class(numerator), class(denominator))) stop("Models of different classes cannot be currently be compared by compare().") LHSnum = all.vars(update(formula(numerator@identifier$formula), .~0)) LHSden = all.vars(update(formula(denominator@identifier$formula), .~0)) if(!identical(LHSnum, LHSden)) stop("Models have different dependent variables!") BFnum = compare(numerator = numerator, data = data) BFden = compare(numerator = denominator, data = data) return(BFnum / BFden) }) setMethod('compare', signature(numerator = "BFoneSample", denominator = "missing", data = "data.frame"), function(numerator, data, ...){ formula = formula(numerator@identifier$formula) LHSnum = all.vars(update(formula, .~0)) y = data[[LHSnum]] N = length(y) mu = numerator@prior$mu nullInterval=numerator@prior$nullInterval if( (numerator@type=="JZS") ){ if( attr(terms(formula, data = data),"intercept") == 0 ){ numBF = 0 errorEst = 0 bf = list() }else{ t = (mean(y) - mu) / sd(y) * sqrt(N) complement = ifelse(!is.null(attr(nullInterval,"complement")),TRUE,FALSE) bf = ttest.tstat(t=t, n1=N,nullInterval=nullInterval,rscale=numerator@prior$rscale,complement=complement) numBF = bf[['bf']] errorEst = bf[['properror']] } numerator@analysis = bf numList = list(numerator) nms = numerator@shortName modDenominator = BFoneSample(type = "JZS", identifier = list(formula = "y ~ 0"), prior=list(mu=mu), shortName = paste("Null, mu=",mu,sep=""), longName = paste("Null, mu = ",mu, sep=""), analysis = list(method="trivial") ) bf_df = data.frame(bf = numBF, error = errorEst, time = date(), code = randomString(length(numBF))) rownames(bf_df) <- nms newBF = BFBayesFactor(numerator = numList, denominator = modDenominator, data = data, bayesFactor = bf_df ) return(newBF) }else{ stop("Unknown prior type: ", numerator@type) } }) setMethod('compare', signature(numerator = "BFindepSample", denominator = "missing", data = "data.frame"), function(numerator, data, ...){ formula = formula(numerator@identifier$formula) checkFormula(formula, data, analysis = "indept") dv = stringFromFormula(formula[[2]]) dv = composeTerm(dv) factor = fmlaFactors(formula, data)[-1] y = data[[dv]] if(!is.null(factor)){ iv = data[[factor]] ns = table(iv) }else{ iv = NULL ns = NULL } mu = numerator@prior$mu nullInterval=numerator@prior$nullInterval if( mu != 0 ) stop("Indep. groups t test with nonzero null not supported yet.") if( (numerator@type=="JZS") ){ if( length(attr(terms(formula, data = data),"term.labels")) == 0 ){ numBF = 0 errorEst = 0 bf = list() }else{ t = t.test(formula = formula,data=data, var.eq=TRUE)$statistic complement = ifelse(!is.null(attr(nullInterval,"complement")),TRUE,FALSE) bf = ttest.tstat(t=t, n1=ns[1], n2=ns[2], nullInterval=nullInterval,rscale=numerator@prior$rscale, complement = complement) numBF = bf[['bf']] errorEst = bf[['properror']] } numerator@analysis = bf numList = list(numerator) nms = numerator@shortName nullFormula = paste(formula[[2]],"1",sep=" ~ ") modDenominator = BFindepSample(type = "JZS", identifier = list(formula = nullFormula), prior=list(mu=mu), shortName = paste("Null, mu1-mu2=",mu,sep=""), longName = paste("Null, mu1-mu2 = ",mu, sep=""), analysis = list(method="trivial") ) bf_df = data.frame(bf = numBF, error = errorEst, time = date(), code = randomString(length(numBF))) rownames(bf_df) <- nms newBF = BFBayesFactor(numerator = numList, denominator = modDenominator, data = data, bayesFactor = bf_df ) return(newBF) }else{ stop("Unknown prior type: ", numerator@type) } }) setMethod('compare', signature(numerator = "BFmetat", denominator = "missing", data = "data.frame"), function(numerator, data, ...){ nullInterval=numerator@prior$nullInterval if( (numerator@type=="JZS") ){ if( numerator@identifier$formula=="d = 0" ){ numBF = 0 errorEst = 0 bf = list() }else{ complement = ifelse(!is.null(attr(nullInterval,"complement")),TRUE,FALSE) bf = meta.ttest.tstat(t=data$t, n1=data$n1, n2=data$n2, nullInterval=nullInterval, rscale=numerator@prior$rscale,complement=complement) numBF = bf[['bf']] errorEst = bf[['properror']] } numerator@analysis = bf numList = list(numerator) nms = numerator@shortName modDenominator = BFmetat(type = "JZS", identifier = list(formula = "d = 0"), prior=list(), shortName = "Null, d=0", longName = "Null, d = 0", analysis = list(method="trivial")) bf_df = data.frame(bf = numBF, error = errorEst, time = date(), code = randomString(length(numBF))) rownames(bf_df) <- nms newBF = BFBayesFactor(numerator = numList, denominator = modDenominator, data = data, bayesFactor = bf_df) return(newBF) }else{ stop("Unknown prior type: ", numerator@type) } }) setMethod('compare', signature(numerator = "BFcorrelation", denominator = "missing", data = "data.frame"), function(numerator, data, ...){ nullInterval=numerator@prior$nullInterval if( (numerator@type=="Jeffreys-beta*") ){ if( numerator@identifier$formula=="rho = 0" ){ numBF = 0 errorEst = 0 bf = list() }else{ complement = ifelse(!is.null(attr(nullInterval,"complement")),TRUE,FALSE) bf = corr.test.bf(y=data$y, x=data$x, rscale=numerator@prior$rscale, nullInterval, complement = complement) numBF = bf[['bf']] errorEst = bf[['properror']] } numerator@analysis = bf numList = list(numerator) nms = numerator@shortName modDenominator = BFcorrelation(type = "Jeffreys-beta*", identifier = list(formula = "rho = 0"), prior=list(), shortName = "Null, rho = 0", longName = "Null, rho = 0", analysis = list(method="trivial")) bf_df = data.frame(bf = numBF, error = errorEst, time = date(), code = randomString(length(numBF))) rownames(bf_df) <- nms newBF = BFBayesFactor(numerator = numList, denominator = modDenominator, data = data, bayesFactor = bf_df) return(newBF) }else{ stop("Unknown prior type: ", numerator@type) } }) setMethod('compare', signature(numerator = "BFproportion", denominator = "missing", data = "data.frame"), function(numerator, data, ...){ nullInterval=numerator@prior$nullInterval if( (numerator@type=="logistic") ){ if( numerator@identifier$formula=="p = p0" ){ numBF = 0 errorEst = 0 bf = list() }else{ complement = ifelse(!is.null(attr(nullInterval,"complement")),TRUE,FALSE) bf = prop.test.bf(y=data$y, N=data$N, p=numerator@prior$p0, rscale=numerator@prior$rscale, nullInterval, complement = complement) numBF = bf[['bf']] errorEst = bf[['properror']] } numerator@analysis = bf numList = list(numerator) nms = numerator@shortName modDenominator = BFproportion(type = "logistic", identifier = list(formula = "p = p0",p0=numerator@prior$p0), prior=list(p0=numerator@prior$p0), shortName = paste("Null, p=",round(numerator@prior$p0,3),sep=""), longName = paste("Null, p = ", numerator@prior$p0, sep=""), analysis = list(method="trivial")) bf_df = data.frame(bf = numBF, error = errorEst, time = date(), code = randomString(length(numBF))) rownames(bf_df) <- nms newBF = BFBayesFactor(numerator = numList, denominator = modDenominator, data = data, bayesFactor = bf_df) return(newBF) }else{ stop("Unknown prior type: ", numerator@type) } }) setMethod('compare', signature(numerator = "BFcontingencyTable", denominator = "missing", data = "data.frame"), function(numerator, data, ...){ type = numerator@type a = numerator@prior$a marg = numerator@prior$fixedMargin data2 = as.matrix(data) if( !is.null(marg) ) if( ( marg == "cols" ) & ( type == "independent multinomial" ) ) data2 = t(data2) if(any(data%%1 != 0)) stop("All elements of x must be integers.") if(any(dim(data)<2) | (length(dim(data)) != 2)) stop("x must be m by n.") if(numerator@identifier$formula == "independence"){ lbf = 0 error = 0 }else{ lbf = switch(type, "poisson" = contingencyPoisson(as.matrix(data2), a), "joint multinomial" = contingencyJointMultinomial(as.matrix(data2), a), "independent multinomial" = contingencyIndepMultinomial(as.matrix(data2), a), "hypergeometric" = contingencyHypergeometric(as.matrix(data2), a), stop("Unknown value of sampleType (see help for contingencyBF).") ) error = 0 } denominator = BFcontingencyTable(type = type, identifier = list(formula = "independence"), prior=numerator@prior, shortName = paste0("Indep. (a=",a,")"), longName = paste0("Null, independence, a = ", a), analysis = list(method = "trivial")) bf_df = data.frame(bf = lbf, error = error, time = date(), code = randomString(1)) rownames(bf_df) <- numerator@shortName numerator@analysis = list(method="analytic") newBF = BFBayesFactor(numerator = list(numerator), denominator = denominator, data = as.data.frame(data), bayesFactor = bf_df ) return(newBF) }) setMethod('compare', signature(numerator = "BFcontingencyTable", denominator = "BFcontingencyTable", data = "data.frame"), function(numerator, denominator, data, ...){ if(!identical(numerator@type, denominator@type)) stop("Models of different types cannot be currently be compared by compare().") if(!identical(class(numerator), class(denominator))) stop("Models of different classes cannot be currently be compared by compare().") BFnum = compare(numerator = numerator, data = data) BFden = compare(numerator = denominator, data = data) return(BFnum / BFden) })
/scratch/gouwar.j/cran-all/cranData/BayesFactor/R/methods-BFmodel.R
setMethod('show', signature = c("BFmcmc"), function(object){ show(S3Part(object)) show(object@model) } ) setAs("BFmcmc" , "mcmc", function ( from , to ){ as.mcmc(from) }) setAs("BFmcmc" , "matrix", function ( from , to ){ as.matrix(from) }) setAs("BFmcmc" , "data.frame", function ( from , to ){ as.data.frame(from) }) #' @rdname recompute-methods #' @aliases recompute,BFmcmc-method setMethod('recompute', signature(x = "BFmcmc", progress="ANY"), function(x, progress, ...){ posterior(model=x@model, data = x@data, progress = progress, ...) } ) setMethod('compare', signature(numerator = "BFmcmc", denominator = "BFmcmc"), function(numerator, denominator, ...){ compare(numerator = numerator@model, data = numerator@data, ...) / compare(numerator = denominator@model, data = denominator@data, ...) } ) setMethod('compare', signature(numerator = "BFmcmc", denominator = "missing"), function(numerator, denominator, ...){ compare(numerator = numerator@model, data = numerator@data, ...) } ) #' @rdname posterior-methods #' @aliases posterior,BFmodel,missing,data.frame,missing-method setMethod("posterior", signature(model="BFmodel", index="missing", data="data.frame", iterations="missing"), function(model, index, data, iterations, ...) stop("Iterations must be specified for posterior sampling.") ) #' @rdname posterior-methods #' @aliases posterior,BFBayesFactor,missing,missing,missing-method setMethod("posterior", signature(model="BFBayesFactor", index="missing", data="missing", iterations="missing"), function(model, index, data, iterations, ...) stop("Iterations must be specified for posterior sampling.") ) #' @rdname posterior-methods #' @aliases posterior,BFBayesFactor,numeric,missing,numeric-method setMethod('posterior', signature(model = "BFBayesFactor", index = "numeric", data = "missing", iterations = "numeric"), function(model, index, data, iterations, ...){ if(length(model[index])>1) stop("Index must specify single element.") posterior(model = model[index], iterations = iterations, ...) } ) #' @rdname posterior-methods #' @aliases posterior,BFBayesFactor,missing,missing,numeric-method setMethod('posterior', signature(model = "BFBayesFactor", index = "missing", data = "missing", iterations = "numeric"), function(model, index=NULL, data, iterations, ...){ if(length(model)>1) stop("Index argument required for posterior with multiple numerators.") posterior(model = model@numerator[[1]], data = model@data, iterations = iterations, ...) } ) #' @rdname posterior-methods #' @aliases posterior,BFlinearModel,missing,data.frame,numeric-method setMethod('posterior', signature(model = "BFlinearModel", index = "missing", data = "data.frame", iterations = "numeric"), function(model, index = NULL, data, iterations, ...){ rscaleFixed = rpriorValues("allNways","fixed",model@prior$rscale[['fixed']]) rscaleRandom = rpriorValues("allNways","random",model@prior$rscale[['random']]) rscaleCont = rpriorValues("regression",,model@prior$rscale[['continuous']]) rscaleEffects = model@prior$rscale[['effects']] formula = formula(model@identifier$formula) checkFormula(formula, data, analysis = "lm") factors = fmlaFactors(formula, data)[-1] nFactors = length(factors) dataTypes = model@dataTypes relevantDataTypes = dataTypes[names(dataTypes) %in% factors] dv = stringFromFormula(formula[[2]]) dv = composeTerm(dv) if(model@type != "JZS") stop("Unknown model type.") if( nFactors == 0 ){ stop("Sampling from intercept-only model not implemented.") }else if(all(relevantDataTypes == "continuous")){ ## Regression X = fullDesignMatrix(formula, data, dataTypes) chains = linearReg.Gibbs(y = data[[dv]],covariates = X,iterations = iterations, rscale = rscaleCont, ...) }else if(all(relevantDataTypes != "continuous")){ # ANOVA or t test chains = nWayFormula(formula=formula, data = data, dataTypes = dataTypes, rscaleFixed = rscaleFixed, rscaleRandom = rscaleRandom, rscaleEffects = rscaleEffects, iterations = iterations, posterior = TRUE, ...) }else{ # GLM chains = nWayFormula(formula=formula, data = data, dataTypes = dataTypes, rscaleFixed = rscaleFixed, rscaleRandom = rscaleRandom, rscaleCont = rscaleCont, rscaleEffects = rscaleEffects, iterations = iterations, posterior = TRUE, ...) } return(new("BFmcmc",chains, model = model, data = data)) } ) #' @rdname posterior-methods #' @aliases posterior,BFindepSample,missing,data.frame,numeric-method setMethod('posterior', signature(model = "BFindepSample", index = "missing", data = "data.frame", iterations = "numeric"), function(model, index = NULL, data, iterations, ...){ formula = formula(model@identifier$formula) rscale = model@prior$rscale interval = model@prior$nullInterval nullModel = ( formula[[3]] == 1 ) chains = ttestIndepSample.Gibbs(formula, data, nullModel, iterations,rscale, interval,...) new("BFmcmc",chains,model = model, data = data) }) #' @rdname posterior-methods #' @aliases posterior,BFcontingencyTable,missing,data.frame,numeric-method setMethod('posterior', signature(model = "BFcontingencyTable", index = "missing", data = "data.frame", iterations = "numeric"), function(model, index = NULL, data, iterations, ...){ mod = formula(model@identifier) type = model@type prior = model@prior$a marg = model@prior$fixedMargin chains = sampleContingency(mod, type, marg, prior, data = data, iterations = iterations, ...) new("BFmcmc",chains,model = model, data = data) }) #' @rdname posterior-methods #' @aliases posterior,BFoneSample,missing,data.frame,numeric-method setMethod('posterior', signature(model = "BFoneSample", index = "missing", data = "data.frame", iterations = "numeric"), function(model, index = NULL, data, iterations, ...){ mu = model@prior$mu rscale = model@prior$rscale interval = model@prior$nullInterval nullModel = ( model@identifier$formula == "y ~ 0" ) chains = ttestOneSample.Gibbs(y = data$y, nullModel, iterations = iterations, rscale = rscale, nullInterval = interval, ...) new("BFmcmc",chains,model = model, data = data) }) #' @rdname posterior-methods #' @aliases posterior,BFmetat,missing,data.frame,numeric-method setMethod('posterior', signature(model = "BFmetat", index = "missing", data = "data.frame", iterations = "numeric"), function(model, index = NULL, data, iterations, ...){ rscale = model@prior$rscale interval = model@prior$nullInterval nullModel = ( model@identifier$formula == "d = 0" ) chains = meta.t.Metrop(t = data$t, n1 = data$n1, n2 = data$n2, nullModel, iterations = iterations, rscale = rscale, nullInterval = interval, ...) new("BFmcmc",chains, model = model, data = data) }) #' @rdname posterior-methods #' @aliases posterior,BFproportion,missing,data.frame,numeric-method setMethod('posterior', signature(model = "BFproportion", index = "missing", data = "data.frame", iterations = "numeric"), function(model, index = NULL, data, iterations, ...){ rscale = model@prior$rscale p = model@prior$p0 interval = model@prior$nullInterval nullModel = ( model@identifier$formula == "p = p0" ) chains = proportion.Metrop(y = data$y, N = data$N, nullModel, iterations = iterations, nullInterval = interval, p = p, rscale = rscale, ...) new("BFmcmc",chains, model = model, data = data) }) #' @rdname posterior-methods #' @aliases posterior,BFcorrelation,missing,data.frame,numeric-method setMethod('posterior', signature(model = "BFcorrelation", index = "missing", data = "data.frame", iterations = "numeric"), function(model, index = NULL, data, iterations, ...){ rscale = model@prior$rscale interval = model@prior$nullInterval nullModel = ( model@identifier$formula == "rho = 0" ) chains = correlation.Metrop(y = data$y, x = data$x, nullModel, iterations = iterations, nullInterval = interval, rscale = rscale, ...) new("BFmcmc",chains, model = model, data = data) }) ########### ## S3 ########### as.mcmc.BFmcmc <- function(x, ...){ return(S3Part(x)) } as.matrix.BFmcmc <- function(x,...){ return(as.matrix(S3Part(x))) } as.data.frame.BFmcmc <- function(x, row.names=NULL,optional=FALSE,...){ return(as.data.frame(S3Part(x))) }
/scratch/gouwar.j/cran-all/cranData/BayesFactor/R/methods-BFmodelSample.R
# constructor BFodds <- function(BFinit, logodds = NULL, bayesFactor = NULL){ if(is.null(logodds)) logodds = data.frame(odds = BFinit@bayesFactor$bf * 0) rownames(logodds) = rownames(BFinit@bayesFactor) new("BFodds", numerator = BFinit@numerator, denominator = BFinit@denominator, logodds = logodds, bayesFactor = bayesFactor, version = BFInfo(FALSE)) } setValidity("BFodds", function(object){ if( length(object@numerator) != nrow(object@logodds)) return("Number of numerator models does not equal number of Bayes factors.") if( !is.null(object@bayesFactor)){ if( length(object@numerator) != length(object@bayesFactor)) return("Number of numerator models does not equal number of Bayes factors.") for(i in 1:length(object@numerator)){ if( !(object@numerator[[i]] %same% object@bayesFactor@numerator[[i]])){ return("Models in numerator are not the same as the numerators in Bayes factor.") } } if( !(object@denominator %same% object@denominator)) return("Model in denominator is not the same as the denominator in Bayes factor.") } numeratorsAreBFs = sapply(object@numerator,function(el) inherits(el,"BFmodel")) if( any(!numeratorsAreBFs)) return("Some numerators are not BFmodel objects.") # check numerators all have same data types as denominator dataTypeDenom = object@denominator@dataTypes dataTypesEqual = unlist(lapply(object@numerator, function(model, compType) model@dataTypes %com% compType, compType=dataTypeDenom)) if( any(!dataTypesEqual)) return("Data types are not equal across models.") typeDenom = object@denominator@type typesEqual = unlist(lapply(object@numerator, function(model, compType) identical(model@type, compType), compType=typeDenom)) if( any(!typesEqual)) return("Model types are not equal across models.") classDenom = class(object@denominator) typesEqual = unlist(lapply(object@numerator, function(model, compType) identical(class(model), compType), compType=classDenom)) if( any(!typesEqual)) return("Model classes are not equal across models.") return(TRUE) }) #' @rdname extractOdds-methods #' @aliases extractOdds,BFodds-method setMethod("extractOdds", "BFodds", function(x, logodds = FALSE, onlyodds = FALSE){ z = x@logodds if(is.null(x@bayesFactor)){ z$error = 0 }else{ bfs = extractBF(x@bayesFactor, logbf=TRUE) z$odds = z$odds + bfs$bf z$error = x@bayesFactor@bayesFactor$error } if(!logodds) z$odds = exp(z$odds) if(onlyodds) z = z$odds return(z) }) setMethod('show', "BFodds", function(object){ is.prior = is.null(object@bayesFactor) if(is.prior){ cat("Prior odds\n--------------\n") }else{ cat("Posterior odds\n--------------\n") } odds = extractOdds(object, logodds = TRUE) odds$odds = sapply(odds$odds, expString) indices = paste("[",1:nrow(odds),"]",sep="") # pad model names nms = paste(indices,rownames(odds),sep=" ") maxwidth = max(nchar(nms)) nms = str_pad(nms,maxwidth,side="right",pad=" ") # pad Bayes factors maxwidth = max(nchar(odds$odds)) oddsString = str_pad(odds$odds,maxwidth,side="right",pad=" ") for(i in 1:nrow(odds)){ if(is.prior){ cat(nms[i]," : ",oddsString[i],"\n",sep="") }else{ cat(nms[i]," : ",oddsString[i]," \u00B1",round(odds$error[i]*100,2),"%\n",sep="") } } cat("\nAgainst denominator:\n") cat(" ",object@denominator@longName,"\n") cat("---\nModel type: ",class(object@denominator)[1],", ",object@denominator@type,"\n\n",sep="") }) setMethod('summary', "BFodds", function(object){ show(object) }) #' @rdname BFodds-class #' @name /,numeric,BFodds-method #' @param e1 Numerator of the ratio #' @param e2 Denominator of the ratio setMethod('/', signature("numeric", "BFodds"), function(e1, e2){ if( (e1 == 1) & (length(e2)==1) ){ numer = e2@numerator[[1]] denom = list(e2@denominator) odds_df = e2@logodds if(is.null(e2@bayesFactor)){ bf = NULL }else{ bf = 1/e2@bayesFactor } rownames(odds_df) = denom[[1]]@shortName odds_df$odds = -odds_df$odds oddsobj = new("BFodds",numerator=denom, denominator=numer, bayesFactor=bf, logodds = odds_df, version = BFInfo(FALSE)) return(oddsobj) }else if( e1 != 1 ){ stop("Dividend must be 1 (to take reciprocal).") }else if( length(e2)>1 ){ allNum = as(e2,"list") #BFlist = BFBayesFactorList(lapply(allNum, function(num) 1 / num)) stop("Length of odds object must be ==1 to take reciprocal.") } } ) #' @rdname BFodds-class #' @name /,BFodds,BFodds-method setMethod('/', signature("BFodds", "BFodds"), function(e1, e2){ if( length(e2) > 1) stop("Length of divisor must be ==1 to divide.") if( !(e1@denominator %same% e2@denominator) ) stop("Odds have different denominator models; they cannot be compared.") if(!is.null(e1@bayesFactor) & !is.null(e1@bayesFactor)){ bf = e1@bayesFactor / e2@bayesFactor }else if(is.null(e1@bayesFactor) & is.null(e1@bayesFactor)){ bf = NULL }else{ stop("Both odds objects must be prior, or both must be posterior.") } if( (length(e2)==1) ){ logodds = data.frame(odds=e1@logodds$odds - e2@logodds$odds) rownames(logodds) = rownames(e1@logodds) oddsobj = new("BFodds",numerator=e1@numerator, denominator=e2@numerator[[1]], bayesFactor=bf, logodds = logodds, version = BFInfo(FALSE)) return(oddsobj) }else{ stop("Length of divisor must be ==1 to divide.") } } ) #' @rdname BFodds-class #' @name *,BFodds,BFBayesFactor-method setMethod('*', signature("BFodds", "BFBayesFactor"), function(e1, e2){ if(!is.null(e1@bayesFactor)) stop("Cannot multiply posterior odds object with Bayes factor.") new("BFodds", numerator = e1@numerator, denominator = e1@denominator, logodds = e1@logodds, bayesFactor = e2, version = BFInfo(FALSE)) } ) #' @rdname BFodds-class #' @name [,BFodds,index,missing,missing-method #' @param x BFodds object #' @param i indices indicating elements to extract #' @param j unused for BFodds objects #' @param drop unused #' @param ... further arguments passed to related methods setMethod("[", signature(x = "BFodds", i = "index", j = "missing", drop = "missing"), function (x, i, j, ..., drop) { if((na <- nargs()) == 2){ newodds = x x@numerator = x@numerator[i, drop=FALSE] x@logodds = x@logodds[i, ,drop=FALSE] if(is.null(x@bayesFactor)){ x@bayesFactor = NULL }else{ x@bayesFactor = x@bayesFactor[i] } }else stop("invalid nargs()= ",na) return(x) }) #' @rdname recompute-methods #' @aliases recompute,BFodds-method setMethod("recompute", "BFodds", function(x, progress = getOption('BFprogress', interactive()), multicore = FALSE, callback = function(...) as.integer(0), ...){ bf = as.BFBayesFactor(x) bf = recompute(bf, progress = progress, multicore = multicore, callback = callback, ...) x@bayesFactor = bf return(x) }) #' @rdname priorOdds-method #' @name priorOdds<-,BFodds,numeric-method #' @docType methods #' @exportMethod setReplaceMethod("priorOdds", signature(object = "BFodds", value = "numeric"), definition = function (object, value) { priorLogodds(object) <- log(value) object }) #' @rdname priorLogodds-method #' @name priorLogodds<-,BFodds,numeric-method #' @docType methods #' @exportMethod setReplaceMethod("priorLogodds", signature(object = "BFodds", value = "numeric"), definition = function (object, value) { object@logodds$odds <- value object }) setAs("BFodds", "BFBayesFactor", function( from, to ){ as.BFBayesFactor.BFodds(from) }) setAs("BFodds", "BFprobability", function( from, to ){ as.BFprobability.BFodds(from) }) ###### # S3 ###### as.BFBayesFactor.BFodds <- function(object){ if(!is.null(object@bayesFactor)){ return(object@bayesFactor) }else{ stop("Cannot convert prior odds to Bayes factor; no data has been given.") } } as.BFprobability.BFodds <- function(object, normalize = NULL, lognormalize = NULL){ if(is.null(lognormalize) & is.null(normalize)){ lognormalize = 0 }else if(is.null(lognormalize) & !is.null(normalize)){ lognormalize = log(normalize) }else if(!is.null(normalize)){ stop("Cannot specify foth normalize and lognormalize.") } return(BFprobability(object, lognormalize)) } length.BFodds <- function(x) nrow(x@logodds) c.BFodds <- function(..., recursive = FALSE) { z = list(...) if(length(z)==1) return(z[[1]]) correctClass = unlist(lapply(z, function(object) inherits(object,"BFodds"))) if(any(!correctClass)) stop("Cannot concatenate odds with non-odds object.") denoms = lapply(z, function(object){ object@denominator }) samedenom = unlist(lapply(denoms[-1], function(el, cmp){ el %same% cmp }, cmp=denoms[[1]])) if(any(!samedenom)) stop("Cannot concatenate odds objects with different denominator models.") logodds = lapply(z, function(object){object@logodds}) df_rownames = unlist(lapply(z, function(object){rownames(object@logodds)})) df_rownames = make.unique(df_rownames, sep=" #") logodds = do.call("rbind",logodds) rownames(logodds) = df_rownames ### Grab the Bayes factors is.prior = 1:length(z) * NA for(i in 1:length(is.prior)){ is.prior[i] = is.null(z[[i]]@bayesFactor) } if(all(!is.prior)){ bfs = lapply(z, function(object){ object@bayesFactor }) bfs = do.call("c", bfs) bf = BFodds(bfs, logodds = logodds, bayesFactor = bfs) }else if(all(is.prior)){ numerators = unlist(lapply(z, function(object){object@numerator}),recursive=FALSE, use.names=FALSE) bf = new("BFodds", numerator = numerators, denominator = z[[1]]@denominator, logodds = logodds, bayesFactor = NULL, version = BFInfo(FALSE)) }else{ stop("Cannot concatenate prior odds with posterior odds.") } return(bf) } names.BFodds <- function(x) { rownames(extractOdds(x)) } # See https://www-stat.stanford.edu/~jmc4/classInheritance.pdf sort.BFodds <- function(x, decreasing = FALSE, ...){ ord = order(extractOdds(x, logodds=TRUE)$odds, decreasing = decreasing) return(x[ord]) } max.BFodds <- function(..., na.rm=FALSE){ joinedodds = do.call('c',list(...)) el <- head(joinedodds, n=1) return(el) } min.BFodds <- function(..., na.rm=FALSE){ joinedodds = do.call('c',list(...)) el <- tail(joinedodds, n=1) return(el) } which.max.BFodds <- function(x){ index = which.max(extractOdds(x, logodds=TRUE)$odds) names(index) = names(x)[index] return(index) } which.min.BFodds <- function(x){ index = which.min(extractOdds(x, logodds=TRUE)$odds) names(index) = names(x)[index] return(index) } head.BFodds <- function(x, n=6L, ...){ n = ifelse(n>length(x),length(x),n) x = sort(x, decreasing=TRUE) return(x[1:n]) } tail.BFodds <- function(x, n=6L, ...){ n = ifelse(n>length(x),length(x),n) x = sort(x) return(x[n:1])} as.data.frame.BFodds <- function(x, row.names = NULL, optional=FALSE,...){ df = extractOdds(x) return(df) } as.vector.BFodds <- function(x, mode = "any"){ if( !(mode %in% c("any", "numeric"))) stop("Cannot coerce to mode ", mode) v = extractOdds(x)$odds names(v) = names(x) return(v) }
/scratch/gouwar.j/cran-all/cranData/BayesFactor/R/methods-BFodds.R
# constructor BFprobability <- function(odds, normalize = 0){ ## Add denominator if(getOption('BFcheckProbabilityList', TRUE)){ ## eliminate redundant models if( length(odds) > 1 ){ odds = c( odds, (1/odds[1]) / (1/odds[1]) ) duplicates = 1:length(odds) for(i in 2:length(odds)){ for(j in 1:(i-1)){ if( odds@numerator[[i]] %same% odds@numerator[[j]] ){ duplicates[i] = j break } } } which.denom = duplicates[length(odds)] not.duplicate = duplicates == (1:length(odds)) not.duplicate[ which.denom ] = FALSE # get rid of redundant models (this could be done better) odds = odds[not.duplicate] } } new("BFprobability", odds = odds, normalize = normalize, version = BFInfo(FALSE)) } setValidity("BFprobability", function(object){ if( !is.numeric(object@normalize) ) return("Normalization constant must be numeric.") if( object@normalize > 0 ) return("Normalization constant must be a valid probability.") odds = object@odds ## Add denominator if(getOption('BFcheckProbabilityList', TRUE)){ if( length(odds) > 1 ){ odds = c( odds, (1/odds[1]) / (1/odds[1]) ) duplicates = 1:length(odds) for(i in 2:length(odds)){ for(j in 1:(i-1)){ if( odds@numerator[[i]] %same% odds@numerator[[j]] ){ return("Duplicate models not allowed in probability objects.") } } } } } return(TRUE) }) setMethod('show', "BFprobability", function(object){ odds = object@odds is.prior = is.null(object@odds@bayesFactor) if(is.prior){ cat("Prior probabilities\n--------------\n") }else{ cat("Posterior probabilities\n--------------\n") } logprobs = extractProbabilities(object, logprobs = TRUE) logprobs$probs = sapply(logprobs$probs, expString) indices = paste("[",1:length(object),"]",sep="") # pad model names nms = paste(indices,rownames(logprobs),sep=" ") maxwidth = max(nchar(nms)) nms = str_pad(nms,maxwidth,side="right",pad=" ") # pad Bayes factors maxwidth = max(nchar(logprobs$probs)) probString = str_pad(logprobs$probs,maxwidth,side="right",pad=" ") for(i in 1:nrow(logprobs)){ if(is.prior){ cat(nms[i]," : ",probString[i],"\n",sep="") }else{ cat(nms[i]," : ",probString[i]," \u00B1",round(logprobs$error[i]*100,2),"%\n",sep="") } } cat("\nNormalized probability: ", expString(object@normalize), " \n") cat("---\nModel type: ",class(object@odds@denominator)[1],", ",object@odds@denominator@type,"\n\n",sep="") }) setMethod('summary', "BFprobability", function(object){ show(object) }) #' @rdname extractProbabilities-methods #' @aliases extractProbabilities,BFprobability-method setMethod("extractProbabilities", "BFprobability", function(x, logprobs = FALSE, onlyprobs = FALSE){ norm = x@normalize odds = x@odds if( (length(odds) > 1 ) | !( odds@numerator[[1]] %same% odds@denominator ) ){ odds = c(odds, (1/odds[1])/(1/odds[1])) x = extractOdds(odds, logodds = TRUE) logsumodds = logMeanExpLogs(x$odds) + log(length(x$odds)) logp = x$odds - logsumodds + norm z = data.frame(probs = logp, error = NA) }else{ # numerator and denominator are the same x = extractOdds(odds, logodds = TRUE) z = data.frame(probs = norm, error = NA) } rownames(z) = rownames(x) if(!logprobs) z$probs = exp(z$probs) if(onlyprobs) z = z$probs return(z) }) #' @rdname BFprobability-class #' @name /,BFprobability,numeric-method #' @param e1 BFprobability object #' @param e2 new normalization constant setMethod('/', signature("BFprobability", "numeric"), function(e1, e2){ if(e2 > 1 | e2 <= 0) stop("Normalization constant must be >0 and not >1") return(e1 - log(e2)) } ) #' @rdname BFprobability-class #' @name -,BFprobability,numeric-method setMethod('-', signature("BFprobability", "numeric"), function(e1, e2){ if(length(e2)>1) stop("Normalization constant must be a scalar.") if(e2 > 0 | e2 == -Inf) stop("Normalization constant must be >0 and not >1") e1@normalize = e2 return(e1) } ) #' @rdname BFprobability-class #' @name [,BFprobability,index,missing,missing-method #' @param x BFprobability object #' @param i indices indicating elements to extract #' @param j unused for BFprobability objects #' @param drop unused #' @param ... further arguments passed to related methods setMethod("[", signature(x = "BFprobability", i = "index", j = "missing", drop = "missing"), function (x, i, j, ..., drop) { if((na <- nargs()) == 2){ if(is.logical(i)){ if(any(i)){ i = (1:length(i))[i] }else{ return(NULL) } } i = unique(i) norm = x@normalize logprobs = extractProbabilities(x, logprobs = TRUE)[i, ,drop=FALSE] sumlogprobs = logMeanExpLogs(logprobs$probs) + log(nrow(logprobs)) if(length(x) == length(i) ){ newnorm = norm }else if( length(i) == 1){ newnorm = sumlogprobs }else{ newnorm = norm + sumlogprobs } whichnum = i[1:max(1, length(i)-1)] whichdenom = i[length(i)] newodds = c(x@odds, (1/x@odds[1])/(1/x@odds[1])) newodds = newodds[whichnum] / newodds[whichdenom] x = BFprobability( newodds, newnorm ) }else stop("invalid nargs()= ",na) return(x) }) #' @rdname BFprobability-class #' @name filterBF,BFprobability,character-method #' @param name regular expression to search name #' @param perl logical. Should perl-compatible regexps be used? See ?grepl for details. #' @param fixed logical. If TRUE, pattern is a string to be matched as is. See ?grepl for details. setMethod("filterBF", signature(x = "BFprobability", name = "character"), function (x, name, perl, fixed, ...) { my.names = names(x) matches = sapply(name, function(el){ grepl(el, my.names, fixed = fixed, perl = perl) }) any.matches = apply(matches, 1, any) x[any.matches] } ) ###### # S3 ###### ##' This function coerces objects to the BFprobability class ##' ##' Function to coerce objects to the BFprobability class ##' ##' Currently, this function will only work with objects of class ##' \code{BFOdds}. ##' @title Function to coerce objects to the BFprobability class ##' @param object an object of appropriate class (BFodds) ##' @param normalize the sum of the probabilities for all models in the object (1 by default) ##' @param lognormalize alternative to \code{normalize}; the ##' logarithm of the normalization constant (0 by default) ##' @return An object of class \code{BFprobability} ##' @author Richard D. Morey (\email{richarddmorey@@gmail.com}) ##' @export ##' @keywords misc as.BFprobability <- function(object, normalize = NULL, lognormalize = NULL) UseMethod("as.BFprobability") length.BFprobability <- function(x) nrow(extractProbabilities(x)) names.BFprobability <- function(x) { rownames(extractProbabilities(x)) } # See https://www-stat.stanford.edu/~jmc4/classInheritance.pdf sort.BFprobability <- function(x, decreasing = FALSE, ...){ ord = order(extractProbabilities(x, logprobs=TRUE)$probs, decreasing = decreasing) return(x[ord]) } max.BFprobability <- function(..., na.rm=FALSE){ if(nargs()>2) stop("Cannot concatenate probability objects.") el <- head(list(...)[[1]], n=1) return(el) } min.BFprobability <- function(..., na.rm=FALSE){ if(nargs()>2) stop("Cannot concatenate probability objects.") el <- tail(list(...)[[1]], n=1) return(el) } which.max.BFprobability <- function(x){ index = which.max(extractProbabilities(x, logprobs=TRUE)$probs) names(index) = names(x)[index] return(index) } which.min.BFprobability <- function(x){ index = which.min(extractProbabilities(x, logprobs=TRUE)$probs) names(index) = names(x)[index] return(index) } head.BFprobability <- function(x, n=6L, ...){ n = ifelse(n>length(x),length(x),n) x = sort(x, decreasing=TRUE) return(x[1:n]) } tail.BFprobability <- function(x, n=6L, ...){ n = ifelse(n>length(x),length(x),n) x = sort(x) return(x[n:1])} as.data.frame.BFprobability <- function(x, row.names = NULL, optional=FALSE,...){ df = extractProbabilities(x) return(df) } as.vector.BFprobability <- function(x, mode = "any"){ if( !(mode %in% c("any", "numeric"))) stop("Cannot coerce to mode ", mode) v = extractProbabilities(x)$probs names(v) = names(x) return(v) } sum.BFprobability <- function(..., na.rm = FALSE) { if(na.rm) warning("na.rm argument not used for BFprobability objects.") sapply(list(...), function(el){ if(is(el, "BFprobability")){ return(exp(el@normalize)) }else{ return(NA) } }, USE.NAMES = FALSE) }
/scratch/gouwar.j/cran-all/cranData/BayesFactor/R/methods-BFprobability.R
designMatrix = function(bf, ...){ model = bf@numerator[[1]] if( !inherits(model, "BFlinearModel") ) stop("Model matrix not defined for this model type.") designMatrixJZS_LM(bf, ...) } designMatrixJZS_LM = function(bf, ...){ model = bf@numerator[[1]] data = bf@data dataTypes = model@dataTypes formula = formula(model@identifier$formula) checkFormula(formula, data, analysis = "lm") factors = fmlaFactors(formula, data)[-1] nFactors = length(factors) if( nFactors == 0 ){ X = matrix(1,nrow(data),1) gMap = c(intercept=NA) }else{ # Remove "as.matrix" when sparse matrix support is added X = as.matrix(fullDesignMatrix(formula, data, dataTypes)) gMap = createGMap(formula, data, dataTypes) X = cbind(1,X) gMap = c(intercept=NA, gMap) } attr(X,"gMap") = gMap return(X) } #' Design matrices for Bayes factor linear models analyses. #' #' This function returns the design matrix used for computation of the Bayes factor #' for the numerator of a \code{BFBayesFactor} object. There must not be more #' than one numerator in the \code{BFBayesFactor} object. #' @param object a BayesFactor object with a single numerator #' @param ... arguments passed to and from related methods #' @return Returns the design matrix for the corresponding model. The 'gMap' attribute of the returned #' matrix contains the mapping from columns of the design matrix to g parameters #' @export #' @docType methods #' @rdname model.matrix-methods #' @aliases model.matrix,BFBayesFactor #' @references Rouder, J. N., Morey, R. D., Speckman, P. L., Province, J. M., (2012) #' Default Bayes Factors for ANOVA Designs. Journal of Mathematical #' Psychology. 56. p. 356-374. #' @examples #' ## Gets the design matrix for a simple analysis #' data(sleep) #' #' bf = anovaBF(extra ~ group + ID, data = sleep, whichRandom="ID", progress=FALSE) #' X = model.matrix(bf) #' #' ## Show dimensions of X (should be 20 by 12) #' dim(X) setMethod('model.matrix', signature(object = "BFBayesFactor"), function(object, ...){ if(length(object)>1) stop("Must specify single model.") designMatrix(object, ...) } ) #' @rdname model.matrix-methods #' @aliases model.matrix,BFBayesFactor setMethod('model.matrix', signature(object = "BFBayesFactorTop"), function(object, ...){ if(length(object)>1) stop("Must specify single model.") designMatrix(as.BFBayesFactor(object), ...) } )
/scratch/gouwar.j/cran-all/cranData/BayesFactor/R/model.matrix.R
singleGBayesFactor <- function(y,X,rscale,gMap,incCont){ if(ncol(X)==1){ dat = data.frame(y=y,x=as.factor(X[,1])) freqs = table(dat$x) t = t.test(y~x,data=dat, var.eq=TRUE)$statistic bf = ttest.tstat(t=t, n1=freqs[1], n2=freqs[2],rscale=rscale*sqrt(2)) return(bf) }else{ N = length(y) if(!incCont){ priorX = matrix(1,0,0) }else if(incCont == 1){ priorX = matrix(sum(X[,1]^2),1,1) / N }else{ priorX = crossprod(X[,1:incCont]) / N } Cny = matrix(y - mean(y), N) CnX = t(t(X) - colMeans(X)) XtCnX = crossprod(CnX) CnytCnX = crossprod(Cny, CnX) sumSq = var(y) * (N-1) gMapCounts = table(gMap) f1 = Vectorize( function(g, const, ...){ exp(Qg(log(g), ..., limit=FALSE) - log(g) - const) },"g") integral = BFtry({ op = optim(0, Qg, control=list(fnscale=-1),gr=dQg, method="BFGS", sumSq=sumSq,N=N,XtCnX=XtCnX,CnytCnX=CnytCnX, rscale=rscale, gMap=gMap, gMapCounts=gMapCounts,priorX=priorX,incCont=incCont) const = op$value - op$par integrate(f1,0,Inf,sumSq=sumSq,N=N,XtCnX=XtCnX,CnytCnX=CnytCnX,rscale=rscale,gMap=gMap,gMapCounts=gMapCounts,const=const,priorX=priorX,incCont=incCont) }) if(inherits(integral,"try-error")){ return(list(bf = NA, properror = NA, method = "quadrature")) } lbf = log(integral$value) prop.error = exp(log(integral$abs.error) - lbf) return(list(bf = lbf + const, properror = prop.error, method = "quadrature")) } } doNwaySampling<-function(method, y, X, rscale, iterations, gMap, incCont, progress, callback = function(...) as.integer(0)) { goodSamples = NULL simpSamples = NULL impSamples = NULL apx = NULL testNsamples = getOption('BFpretestIterations', 100) testCallback = function(...) callback(0) if(ncol(X)==1) method="simple" if(method=="auto"){ simpSamples = BFtry(jzs_sampler(testNsamples, y, X, rscale, gMap, incCont, NA, NA, FALSE, testCallback, 1, 0)) simpleErr = propErrorEst(simpSamples) logAbsSimpErr = logMeanExpLogs(simpSamples) + log(simpleErr) apx = suppressWarnings(BFtry(gaussianApproxAOV(y,X,rscale,gMap,incCont))) if(inherits(apx,"try-error")){ method="simple" }else{ impSamples = BFtry(jzs_sampler(testNsamples, y, X, rscale, gMap, incCont, apx$mu, apx$sig, FALSE, testCallback, 1, 1)) if(inherits(impSamples, "try-error")){ method="simple" }else{ impErr = propErrorEst(impSamples) logAbsImpErr = logMeanExpLogs(impSamples) + log(impErr) if(is.na(impErr)){ method="simple" }else if(is.na(simpleErr)){ method="importance" }else{ method = ifelse(impErr>simpleErr,"simple","importance") } } } } if(method=="importance"){ if(is.null(apx) | inherits(apx,"try-error")) apx = BFtry(gaussianApproxAOV(y,X,rscale,gMap,incCont)) if(inherits(apx, "try-error")){ method="simple" }else{ goodSamples= BFtry(jzs_sampler(iterations, y, X, rscale, gMap, incCont, apx$mu, apx$sig, progress, callback, 1, 1)) if(inherits(goodSamples,"try-error")){ method="simple" goodSamples = NULL } } } if(method=="simple" | is.null(goodSamples)){ method = "simple" goodSamples = jzs_sampler(iterations, y, X, rscale, gMap, incCont, NA, NA, progress, callback, 1, 0) } if(is.null(goodSamples)){ warning("Unknown sampling method requested (or sampling failed) for nWayAOV") return(list(bf=NA,properror=NA,method=NA)) } if( any(is.na(goodSamples)) ) warning("Some NAs were removed from sampling results: ",sum(is.na(goodSamples))," in total.") bfSamp = goodSamples[!is.na(goodSamples)] n2 = length(bfSamp) bf = logMeanExpLogs(bfSamp) # estimate error properror = propErrorEst(bfSamp) return(list(bf = bf, properror=properror, N = n2, method = method, sampled = TRUE, code = randomString(1))) } createRscales <- function(formula, data, dataTypes, rscaleFixed = NULL, rscaleRandom = NULL, rscaleCont = NULL, rscaleEffects = NULL){ rscaleFixed = rpriorValues("allNways","fixed",rscaleFixed) rscaleRandom = rpriorValues("allNways","random",rscaleRandom) rscaleCont = rpriorValues("regression",,rscaleCont) types = termTypes(formula, data, dataTypes) nFac = sum( (types=="random") | (types=="fixed") ) nCont = any(types=="continuous") * 1 nGs = nFac + nCont rscale = 1:nGs * NA rscaleTypes = rscale if(nCont > 0){ rscaleTypes[nGs] = "continuous" names(rscaleTypes)[nGs] = "continuous" } if(nFac > 0){ facTypes = types[types != "continuous"] rscaleTypes[1:nFac] = facTypes names(rscaleTypes)[1:nFac] = names(facTypes) } names(rscale) = names(rscaleTypes) rscale[rscaleTypes=="continuous"] = rscaleCont rscale[rscaleTypes=="fixed"] = rscaleFixed rscale[rscaleTypes=="random"] = rscaleRandom if( any( names(rscaleEffects) %in% names(types)[types == "continuous"] ) ){ stop("Continuous prior settings set from rscaleEffects; use rscaleCont instead.") #rscaleEffects = rscaleEffects[ !( names(rscaleEffects) %in% names(types)[types == "continuous"] ) ] } if(length(rscaleEffects)>0) rscale[names(rscale) %in% names(rscaleEffects)] = rscaleEffects[names(rscale)[names(rscale) %in% names(rscaleEffects)]] rscale = mapply(rpriorValues,effectType=rscaleTypes, priorType=rscale,MoreArgs = list(modelType="allNways")) return(rscale) } createGMap <- function(formula, data, dataTypes){ factors = fmlaFactors(formula, data)[-1] if(length(factors)<1) return(c()) # Compute number of parameters for each specified column nXcols = numColsForFactor(formula, data, dataTypes) lvls = termLevels(formula, data, nXcols) types = termTypes(formula, data, dataTypes) # each random or fixed group gets a parameter, and all continuous together get 1 nFac = sum( (types=="random") | (types=="fixed") ) nCont = any(types=="continuous") * 1 nGs = nFac + nCont P = sum(lvls) gGroups = inverse.rle(list(lengths=lvls,values=names(lvls))) gMap = 1:P * NA names(gMap) = gGroups gGroupsFac = lvls[types != "continuous"] * 0 + (1:nFac - 1) gMap[types[gGroups] == "continuous"] = nGs - 1 gMap[types[gGroups] != "continuous"] = gGroupsFac[names(gMap[types[gGroups] != "continuous"])] return(gMap) } numColsForFactor <- function(formula, data, dataTypes){ factors = fmlaFactors(formula, data)[-1] sapply(factors, function(el, data, dataTypes){ switch(dataTypes[el], fixed = nlevels(data[,el]) - 1, random = nlevels(data[,el]), continuous = 1 ) }, data = data, dataTypes = dataTypes) } termLevels <- function(formula, data, nXcols){ trms = attr(terms(formula, data = data),"term.labels") sapply(trms, function(term, nXcols){ constit = decomposeTerm(term) prod(nXcols[constit]) }, nXcols = nXcols) } termTypes <- function(formula, data, dataTypes){ trms = attr(terms(formula, data = data),"term.labels") sapply(trms, function(term, dataTypes){ constit = decomposeTerm(term) types = dataTypes[constit] if(any(types=="continuous")) return("continuous") if(any(types=="random")) return("random") return("fixed") }, dataTypes = dataTypes) } fullDesignMatrix <- function(fmla, data, dataTypes){ trms <- attr(terms(fmla, data = data), "term.labels") sparse = any(dataTypes=="random") Xs = lapply(trms,function(trm, data, dataTypes){ oneDesignMatrix(trm, data = data, dataTypes = dataTypes, sparse = sparse) }, data = data, dataTypes = dataTypes) do.call("cbind" ,Xs) } oneDesignMatrix <- function(trm, data, dataTypes, sparse = FALSE) { effects <- unlist(decomposeTerm(trm)) #check to ensure all terms are in data checkEffects(effects, data, dataTypes) if(length(effects) == 1){ fmla = paste("~",composeTerm(effects),"-1") X = model.Matrix(formula(fmla), data = data, sparse = sparse) if(dataTypes[effects] == "fixed"){ X = X %*% fixedFromRandomProjection(ncol(X), sparse = sparse) colnames(X) = paste(effects,"_redu_",1:ncol(X),sep="") }else if(dataTypes[effects] == "random"){ # We need to add in a hyphen to be consistent with the # column names elsewhere colnames(X) = stringr::str_replace(string = colnames(X), pattern = paste0("^",effects), replacement = paste0(effects,"-")) } return(X) }else{ Xs = lapply(effects, function(trm, data, dataTypes, sparse){ trm <- composeTerm(trm) oneDesignMatrix(trm, data = data, dataTypes = dataTypes, sparse = sparse) }, data = data, dataTypes = dataTypes, sparse = sparse) X = Reduce(rowMultiply, x = Xs) return(X) } } design.names.intList <- function(effects, data, dataTypes){ type = dataTypes[ effects[1] ] firstCol = data[ ,effects[1] ] nLevs = nlevels( firstCol ) if(length(effects)==1){ if(type=="random") return(levels(firstCol)) if(type=="fixed") return(0:(nLevs-2)) if(type=="continuous") return(effects) }else{ if(type=="random") return(rowPaste(levels(firstCol), design.names.intList(effects[-1], data, dataTypes) )) if(type=="fixed") return(rowPaste(0:(nLevs-2), design.names.intList(effects[-1], data, dataTypes) )) if(type=="continuous") return( design.names.intList(effects[-1], data, dataTypes) ) #return(rowPaste(0:(nLevs-2), design.names.intList(effects[-1], data, dataTypes) )) } } design.projection.intList <- function(effects, data, dataTypes){ type = dataTypes[ effects[1] ] firstCol = data[ ,effects[1] ] nLevs = nlevels( firstCol ) if(length(effects)==1){ if(type=="random") return(bdiag(diag(nLevs))) if(type=="fixed") return(fixedFromRandomProjection(nLevs)) if(type=="continuous") return(Matrix(1,1,1)) }else{ if(type=="random") return(kronecker(diag(nLevs), design.projection.intList(effects[-1],data, dataTypes) )) if(type=="fixed") return(kronecker(fixedFromRandomProjection(nLevs), design.projection.intList(effects[-1], data, dataTypes) )) if(type=="continuous") return( design.projection.intList(effects[-1], data, dataTypes) ) } } rowPaste = function(v1,v2) { as.vector(t(outer(v1,v2,paste,sep=".&."))) } rowMultiply = function(x, y) { sparse = is(x, "sparseMatrix") | is(y, "sparseMatrix") if(nrow(x) != nrow(y)) stop("Unequal row numbers in row.multiply:", nrow(x),", ",nrow(y)) K = sapply(1:nrow(x), function(n, x, y){ kronecker(x[n,], y[n,]) }, x = x, y = y ) # add names K <- t(Matrix(as.vector(K), ncol = nrow(x), sparse = sparse)) colnames(K) = as.vector(t( outer(colnames(x), colnames(y), function(x,y){ paste(x, y,sep=".&.") }))) return(K) } # Create projection matrix fixedFromRandomProjection <- function(nlevRandom, sparse = FALSE){ centering=diag(nlevRandom)-(1/nlevRandom) S=as.vector((eigen(centering)$vectors)[,1:(nlevRandom-1)]) return(Matrix(S,nrow=nlevRandom, sparse = sparse)) } centerContinuousColumns <- function(data){ mycols = lapply(data,function(colmn){ if(is.factor(colmn)){ return(colmn) }else{ return(colmn - mean(colmn)) } }) df <- data.frame(mycols) colnames(df) <- colnames(data) return(df) } nWayFormula <- function(formula, data, dataTypes, rscaleFixed=NULL, rscaleRandom=NULL, rscaleCont=NULL, rscaleEffects = NULL, posterior=FALSE, columnFilter = NULL, unreduce=TRUE, ...){ checkFormula(formula, data, analysis = "lm") y = data[,stringFromFormula(formula[[2]])] data <- centerContinuousColumns(data) X = fullDesignMatrix(formula, data, dataTypes) # To be removed when sparse matrix support is complete X = as.matrix(X) rscale = createRscales(formula, data, dataTypes, rscaleFixed, rscaleRandom, rscaleCont, rscaleEffects) gMap = createGMap(formula, data, dataTypes) if(any(dataTypes=="continuous")){ continuous = termTypes(formula, data, dataTypes)=="continuous" continuous = continuous[names(gMap)] }else{ continuous = FALSE } ## Determine which columns we will ignore if(is.null(columnFilter)){ ignoreCols = NULL }else{ ignoreCols = filterVectorLogical(columnFilter, names(gMap)) } if(all(ignoreCols) & !is.null(ignoreCols)) stop("Filtering out all chain columns of interest is not allowed.") retVal = nWayAOV(y, X, gMap = gMap, rscale = rscale, posterior = posterior, continuous = continuous, ignoreCols=ignoreCols,...) if(posterior){ retVal <- mcmc(makeChainNeater(retVal, colnames(X), formula, data, dataTypes, gMap, unreduce, continuous, columnFilter)) } return(retVal) } makeLabelList <- function(formula, data, dataTypes, unreduce, columnFilter){ terms = attr(terms(formula, data = data), "term.labels") if(!is.null(columnFilter)) terms = terms[!filterVectorLogical(columnFilter,terms)] if(unreduce) dataTypes[dataTypes == "fixed"] = "random" labelList = lapply(terms, function(term, data, dataTypes){ effects = strsplit(term,":",fixed=TRUE)[[1]] my.names = design.names.intList(effects, data, dataTypes) return(paste(term,"-",my.names,sep="")) }, data = data, dataTypes=dataTypes) # join them all together in one cector unlist(labelList) } unreduceChainPart = function(term, chains, data, dataTypes, gMap, ignoreCols){ effects = strsplit(term,":", fixed = TRUE)[[1]] myCols = names(gMap)==term if(ignoreCols[myCols][1]) return(NULL) # Figure out which columns we need to look at, given that some are missing cumulativeIgnored = sum(ignoreCols[1:which(myCols)[1]]) # How many are ignored up to the one of interest? remappedCols = which(myCols) - cumulativeIgnored chains = chains[, remappedCols, drop = FALSE ] if(any(dataTypes[effects]=="fixed")){ S = design.projection.intList(effects, data, dataTypes) return(chains%*%as.matrix(t(S))) }else{ return(chains) } } ureduceChains = function(chains, formula, data, dataTypes, gMap, ignoreCols){ terms = attr(terms(formula, data = data), "term.labels") unreducedChains = lapply(terms, unreduceChainPart, chains=chains, data = data, dataTypes = dataTypes, gMap = gMap, ignoreCols=ignoreCols) do.call(cbind, unreducedChains) } makeChainNeater <- function(chains, Xnames, formula, data, dataTypes, gMap, unreduce, continuous, columnFilter){ P = length(gMap) nGs = max(gMap) + 1 factors = fmlaFactors(formula, data)[-1] dataTypes = dataTypes[ names(dataTypes) %in% factors ] types = termTypes(formula, data, dataTypes) lastPars = ncol(chains) + (-nGs):0 if(any(continuous)){ gNames = paste("g",c(names(types[types!="continuous"]),"continuous"),sep="_") }else{ gNames = paste("g",names(types), sep="_") } if(is.null(columnFilter)){ ignoreCols = ignoreCols = rep(0,P) }else{ ignoreCols=filterVectorLogical(columnFilter, names(gMap)) } if(!unreduce | !any(dataTypes == "fixed")) { labels = c("mu", Xnames[!ignoreCols], "sig2", gNames) colnames(chains) = labels return(chains) } # Make column names parLabels = makeLabelList(formula, data, dataTypes, unreduce, columnFilter) labels = c("mu", parLabels) betaChains = chains[,1:(ncol(chains)-2-nGs) + 1, drop = FALSE] betaChains = ureduceChains(betaChains, formula, data, dataTypes, gMap, ignoreCols) newChains = cbind(chains[,1],betaChains,chains[,lastPars]) labels = c(labels, "sig2", gNames) colnames(newChains) = labels return(newChains) }
/scratch/gouwar.j/cran-all/cranData/BayesFactor/R/nWayAOV-utility.R
##' Computes a single Bayes factor, or samples from the posterior, for an ANOVA ##' model defined by a design matrix ##' ##' This function is not meant to be called by end-users, although ##' technically-minded users can call this function for flexibility beyond what ##' the other functions in this package provide. See \code{\link{lmBF}} for a ##' user-friendly front-end to this function. Details about the priors can be ##' found in the help for \code{\link{anovaBF}} and the references therein. ##' ##' Argument \code{gMap} provides a way of grouping columns of ##' the design matrix as a factor; the effects in each group will share a common ##' \eqn{g} parameter. \code{gMap} should be a vector of the same length as the number of ##' nonconstant rows in \code{X}. It will contain all integers from 0 to ##' \eqn{N_g-1}{Ng-1}, where \eqn{N_g}{Ng} is the total number of \eqn{g} ##' parameters. Each element of \code{gMap} specifies the group to which that ##' column belongs. ##' ##' If all columns belonging to a group are adjacent, \code{struc} can instead ##' be used to compactly represent the groupings. \code{struc} is a vector of ##' length \eqn{N_g}{Ng}. Each element specifies the number columns in the ##' group. ##' ##' The vector \code{rscale} should be of length \eqn{N_g}{Ng}, and contain the ##' prior scales of the standardized effects. See Rouder et al. (2012) for more ##' details and the help for \code{\link{anovaBF}} for some typical values. ##' ##' The method used to estimate the Bayes factor depends on the \code{method} ##' argument. "simple" is most accurate for small to moderate sample sizes, and ##' uses the Monte Carlo sampling method described in Rouder et al. (2012). ##' "importance" uses an importance sampling algorithm with an importance ##' distribution that is multivariate normal on log(g). "laplace" does not ##' sample, but uses a Laplace approximation to the integral. It is expected to ##' be more accurate for large sample sizes, where MC sampling is slow. If ##' \code{method="auto"}, then an initial run with both samplers is done, and ##' the sampling method that yields the least-variable samples is chosen. The ##' number of initial test iterations is determined by ##' \code{options(BFpretestIterations)}. ##' ##' If posterior samples are requested, the posterior is sampled with a Gibbs ##' sampler. ##' @title Use ANOVA design matrix to compute Bayes factors or sample posterior ##' @param y vector of observations ##' @param X design matrix whose number of rows match \code{length(y)}. ##' @param gMap vector grouping the columns of \code{X} (see Details). ##' @param rscale a vector of prior scale(s) of appropriate length (see ##' Details). ##' @param iterations Number of Monte Carlo samples used to estimate Bayes ##' factor or posterior ##' @param progress if \code{TRUE}, show progress with a text progress bar ##' @param callback callback function for third-party interfaces ##' @param gibbs will be deprecated. See \code{posterior} ##' @param posterior if \code{TRUE}, return samples from the posterior using ##' Gibbs sampling, instead of the Bayes factor ##' @param ignoreCols if \code{NULL} and \code{posterior=TRUE}, all parameter ##' estimates are returned in the MCMC object. If not \code{NULL}, a vector of ##' length P-1 (where P is number of columns in the design matrix) giving which ##' effect estimates to ignore in output ##' @param thin MCMC chain to every \code{thin} iterations. Default of 1 means ##' no thinning. Only used if \code{posterior=TRUE} ##' @param method the integration method (only valid if \code{posterior=FALSE}); one ##' of "simple", "importance", "laplace", or "auto" ##' @param continuous either FALSE if no continuous covariates are included, or ##' a logical vector of length equal to number of columns of X indicating ##' which columns of the design matrix represent continuous covariates ##' @param noSample if \code{TRUE}, do not sample, instead returning NA. This is ##' intended to be used with functions generating and testing many models at one time, ##' such as \code{\link{anovaBF}} ##' @return If \code{posterior} is \code{FALSE}, a vector of length 2 containing ##' the computed log(e) Bayes factor (against the intercept-only null), along ##' with a proportional error estimate on the Bayes factor. Otherwise, an ##' object of class \code{mcmc}, containing MCMC samples from the posterior is ##' returned. ##' @note Argument \code{struc} has been deprecated. Use \code{gMap}, which is the \code{\link{inverse.rle}} of \code{struc}, ##' minus 1. ##' @export ##' @keywords htest ##' @author Richard D. Morey (\email{richarddmorey@@gmail.com}), Jeffery N. ##' Rouder (\email{rouderj@@missouri.edu}) ##' @seealso See \code{\link{lmBF}} for the user-friendly front end to this ##' function; see \code{\link{regressionBF}} and \code{anovaBF} for testing ##' many regression or ANOVA models simultaneously. ##' @references Rouder, J. N., Morey, R. D., Speckman, P. L., Province, J. M., ##' (2012) Default Bayes Factors for ANOVA Designs. Journal of Mathematical ##' Psychology. 56. p. 356-374. ##' @examples ##' ## Classical example, taken from t.test() example ##' ## Student's sleep data ##' data(sleep) ##' plot(extra ~ group, data = sleep) ##' ##' ## traditional ANOVA gives a p value of 0.00283 ##' summary(aov(extra ~ group + Error(ID/group), data = sleep)) ##' ##' ## Build design matrix ##' group.column <- rep(1/c(-sqrt(2),sqrt(2)),each=10) ##' subject.matrix <- model.matrix(~sleep$ID - 1,data=sleep$ID) ##' ## Note that we include no constant column ##' X <- cbind(group.column, subject.matrix) ##' ##' ## (log) Bayes factor of full model against grand-mean only model ##' bf.full <- nWayAOV(y = sleep$extra, X = X, gMap = c(0,rep(1,10)), rscale=c(.5,1)) ##' exp(bf.full[['bf']]) ##' ##' ## Compare with lmBF result (should be about the same, give or take 1%) ##' bf.full2 <- lmBF(extra ~ group + ID, data = sleep, whichRandom = "ID") ##' bf.full2 nWayAOV<- function(y, X, gMap, rscale, iterations = 10000, progress = getOption('BFprogress', interactive()), callback = function(...) as.integer(0), gibbs = NULL, posterior = FALSE, ignoreCols=NULL, thin=1, method="auto", continuous=FALSE, noSample = FALSE) { if(!is.numeric(y)) stop("y must be numeric.") if(!is.numeric(X)) stop("X must be numeric.") if(!is.function(callback)) stop("Invalid callback.") if(!is.null(gibbs)){ warning("Argument 'gibbs' to nWayAOV will soon be deprecated. Use 'posterior' instead.") posterior = gibbs } N = length(y) X = matrix( X, nrow=N ) constantCols = apply(X,2,function(v) length(unique(v)))==1 & !apply(X,2,function(v) all(v==0)) if( sum(constantCols) > 0 ) { X = X[,-which(constantCols)] warning( sum(constantCols)," constant columns removed from X." ) } P = ncol(X) if(!is.null(gMap)){ if(length(gMap) != P) stop("Invalid gMap argument. length(gMap) must be the the same as the number of parameters (excluding intercept): ",sum(gMap)," != ",P) if( !all(0:max(gMap) %in% unique(gMap)) ) stop("Invalid gMap argument: no index can be skipped.") nGs = as.integer(max(gMap) + 1) }else{ stop("gMap must be defined.") } if(is.null(ignoreCols)) ignoreCols = rep(0,P) if(length(rscale)!=nGs){ stop("Length of rscale vector wrong. Was ", length(rscale), " and should be ", nGs,".") } # Rearrange design matrix if continuous columns are included # We will undo this later if chains have to be returned if(!identical(continuous,FALSE)){ if(all(continuous) & !posterior){ #### If all covariates are continuous, we want to use Gaussian quadrature. Cy = matrix(y - mean(y), ncol=1) CX = t(t(X) - colMeans(X)) R2 = t(Cy)%*%CX%*%solve(t(CX)%*%CX)%*%t(CX)%*%Cy / (t(Cy)%*%Cy) bf = linearReg.R2stat(N=N,p=ncol(CX),R2=R2,rscale=rscale) return(bf) } if(length(continuous) != P) stop("argument continuous must have same length as number of predictors") if(length(unique(gMap[continuous]))!=1) stop("gMap for continuous predictors don't all point to same g value") # Sort chains so that continuous covariates are together, and first sortX = order(!continuous) revSortX = order(sortX) X = X[,sortX,drop=FALSE] gMap = gMap[sortX] ignoreCols = ignoreCols[sortX] continuous = continuous[sortX] incCont = sum(continuous) }else{ revSortX = sortX = 1:ncol(X) incCont = as.integer(0) } # What if we can use quadrature? if(nGs==1 & !posterior & all(!continuous)) return(singleGBayesFactor(y,X,rscale,gMap, incCont)) if(posterior) return(nWayAOV.Gibbs(y, X, gMap, rscale, iterations, incCont, sortX, revSortX, progress, ignoreCols, thin, continuous, noSample, callback)) if(!noSample){ if(method %in% c("simple","importance","auto")){ return(doNwaySampling(method, y, X, rscale, iterations, gMap, incCont, progress, callback)) }else if(method=="laplace"){ bf = laplaceAOV(y,X,rscale,gMap,incCont) return(list(bf = bf, properror=NA, method="laplace")) }else{ stop("Unknown method specified.") } } return(list(bf = NA, properror=NA, method=NA)) } nWayAOV.Gibbs = function(y, X, gMap, rscale, iterations, incCont, sortX, revSortX, progress, ignoreCols, thin, continuous, noSample, callback) { P = ncol(X) nGs = as.integer( max(gMap) + 1 ) # Check thinning to make sure number is reasonable if( (thin<1) | (thin>(iterations/3)) ) stop("MCMC thin parameter cannot be less than 1 or greater than iterations/3. Was:", thin) if(!identical(continuous,FALSE)){ if(length(continuous) != P) stop("argument continuous must have same length as number of predictors") if(length(unique(gMap[continuous]))!=1) stop("gMap for continuous predictors don't all point to same g value") } nOutputPars = sum(1-ignoreCols) if(noSample){ # Return structure of chains chains = matrix(NA,2,nOutputPars + 2 + nGs) }else{ chains = jzs_Gibbs(iterations, y, cbind(1,X), rscale, 1, gMap, table(gMap), incCont, FALSE, as.integer(ignoreCols), as.integer(thin), as.logical(progress), callback, 1) } chains = mcmc(chains) # Unsort the chains if we had continuous covariates if(incCont){ # Account for ignored columns when resorting revSort = 1+order(sortX[!ignoreCols]) chains[,1 + 1:nOutputPars] = chains[,revSort] labels = c("mu",paste("beta",1:P,sep="_")[!ignoreCols[revSortX]],"sig2",paste("g",1:nGs,sep="_")) }else{ labels = c("mu",paste("beta",1:P,sep="_")[!ignoreCols],"sig2",paste("g",1:nGs,sep="_")) } colnames(chains) = labels return(chains) }
/scratch/gouwar.j/cran-all/cranData/BayesFactor/R/nWayAOV.R
#'Create prior odds from a Bayes factor object #' #'Create a prior odds object from a Bayes factor object #' #'This function takes a Bayes factor object and, using its structure and #'specified type of prior odds, will create a prior odds object. #' #'For now, the only type is "equal", which assigns equal prior odds to all #'models. #' #'@param bf A BFBayesFactor object, eg, from an analysis #'@param type The type of prior odds to create (by default "equal"; see details) #'@return A (prior) BFodds object, which can then be multiplied by the #'BFBayesFactor object to obtain posterior odds. #'@author Richard D. Morey (\email{richarddmorey@@gmail.com}) #'@keywords misc #'@export newPriorOdds = function(bf, type = "equal"){ BFodds(bf) }
/scratch/gouwar.j/cran-all/cranData/BayesFactor/R/newPriorOdds.R
.onAttach<- function(libname, pkgname){ packageStartupMessage("************\nWelcome to ",pkgname," ",BFInfo(FALSE),". If you have", " questions, please contact Richard Morey ([email protected]).\n\n", "Type BFManual() to open the manual.\n************", appendLF = TRUE) } #'options() for package BayesFactor #' #'Options that can be set for the BayesFactor package #' #'The BayesFactor package has numerous options that can be set to globally #'change the behavior of the functions in the package. These options can be #'changed using \code{\link[base]{options}}(). #' #'\describe{ #'\item{\code{BFMaxModels}}{Integer; maximum number of models to analyze in \code{\link{anovaBF}} or \code{\link{regressionBF}}} #'\item{\code{BFprogress}}{If \code{TRUE}, progress bars are on by default; if \code{FALSE}, they are disabled by default.} #'\item{\code{BFpretestIterations}}{Integer; if sampling is needed to compute the Bayes factor, the package attempts to #'choose the most efficient sampler. This option controls the number of initial test iterations.} #'\item{\code{BFapproxOptimizer}}{\code{"nlm"} or \code{"optim"}; changes the optimization function used for the importance sampler. If one fails, try the other.} #'\item{\code{BFapproxLimits}}{Vector of length two containing the lower and upper limits on #'on \code{log(g)} before the the posterior returns \code{-Inf}. This only affects the initial optimization step for the importance sampler.} #'\item{\code{BFfactorsMax}}{Maximum number of factors to try to do enumeration with in generalTestBF.} #'\item{\code{BFcheckProbabilityList}}{Check for duplicate models when creating BFprobability objects?} #'} #' #'@name options-BayesFactor #'@seealso \code{\link[base]{options}} NULL
/scratch/gouwar.j/cran-all/cranData/BayesFactor/R/onAttach.R
marginal.g.oneWay = Vectorize(function(g,F,N,J,rscale,log=FALSE, log.const=0) { dfs = (J-1)/(N*J-J) omega = (1+(N*g/(dfs*F+1)))/(N*g+1) m = log(rscale) - 0.5*log(2*pi) - 1.5*log(g) - rscale^2/(2*g) - (J-1)/2*log(N*g+1) - (N*J-1)/2*log(omega) - log.const ifelse(log,m,exp(m)) },"g")
/scratch/gouwar.j/cran-all/cranData/BayesFactor/R/oneWayAOV-utility.R
##' Using the classical F test statistic for a balanced one-way design, this function computes the corresponding Bayes factor test. ##' ##' For F statistics computed from balanced one-way designs, this function can ##' be used to compute the Bayes factor testing the model that all group means ##' are not equal to the grand mean, versus the null model that all group means ##' are equal. It can be used when you don't have access to the full data set ##' for analysis by \code{\link{lmBF}}, but you do have the test statistic. ##' ##' For details about the model, see the help for \code{\link{anovaBF}}, and the references therein. ##' ##' The Bayes factor is computed via Gaussian quadrature. ##' @title Use F statistic to compute Bayes factor for balanced one-way designs ##' @param F F statistic from classical ANOVA ##' @param N number of observations per cell or group ##' @param J number of cells or groups ##' @param rscale numeric prior scale ##' @param simple if \code{TRUE}, return only the Bayes factor ##' @return If \code{simple} is \code{TRUE}, returns the Bayes factor (against the ##' intercept-only null). If \code{FALSE}, the function returns a ##' vector of length 3 containing the computed log(e) Bayes factor, ##' along with a proportional error estimate on the Bayes factor and the method used to compute it. ##' @export ##' @keywords htest ##' @author Richard D. Morey (\email{richarddmorey@@gmail.com}) ##' @references Morey, R. D., Rouder, J. N., Pratte, M. S., and Speckman, P. L. ##' (2011). Using MCMC chain outputs to efficiently estimate Bayes factors. ##' Journal of Mathematical Psychology, 55, 368-378 ##' ##' @note \code{oneWayAOV.Fstat} should only be used with F values obtained from ##' balanced designs. ##' @examples ##' ## Example data "InsectSprays" - see ?InsectSprays ##' require(stats); require(graphics) ##' boxplot(count ~ spray, data = InsectSprays, xlab = "Type of spray", ##' ylab = "Insect count", main = "InsectSprays data", varwidth = TRUE, ##' col = "lightgray") ##' ##' ## Classical analysis (with transformation) ##' classical <- aov(sqrt(count) ~ spray, data = InsectSprays) ##' plot(classical) ##' summary(classical) ##' ##' ## Bayes factor (a very large number) ##' Fvalue <- anova(classical)$"F value"[1] ##' result <- oneWayAOV.Fstat(Fvalue, N=12, J=6) ##' exp(result[['bf']]) ##' @seealso \code{\link{integrate}}, \code{\link{aov}}; see \code{\link{lmBF}} for the intended interface to this function, using the full data set. oneWayAOV.Fstat = function(F, N, J, rscale="medium", simple = FALSE) { rscale = rpriorValues("allNways","fixed",rscale) res = list(bf=NA, properror=NA,method="quadrature") BFtry({ log.const = marginal.g.oneWay(1,F=F,N=N,J=J,rscale=rscale,log=TRUE) integral = integrate(marginal.g.oneWay,lower=0,upper=Inf,F=F,N=N,J=J,rscale=rscale,log.const=log.const) properror = exp(log(integral[[2]]) - log(integral[[1]])) bf = log(integral[[1]]) + log.const res = list(bf=bf, properror=properror, method="quadrature") }) if(simple){ return(c(B10=exp(res[['bf']]))) }else{ return(res) } }
/scratch/gouwar.j/cran-all/cranData/BayesFactor/R/oneWayAOV_Fstat.R
## S4 method ##### # setMethod("plot", "BFBayesFactor", function(x, include1 = TRUE, addDenom = FALSE, sortbf=TRUE, logbase = c("log10", "log2","ln"), marginExpand=.4,pars=NULL, ...){ # plot.BFBayesFactor(x, include1 = include1, # addDenom = addDenom, # sortbf = sortbf, # logbase = logbase, # marginExpand = marginExpand, # pars = pars, ...) # invisible(NULL) # }) ## S3 method ##### #' Plot a Bayes factor object #' #' This function creates a barplot of the (log) Bayes factors in a Bayes factor #' object. Error bars are added (though in many cases they may be too small to #' see) in red to show the error in estimation of the Bayes factor. If a red question mark #' appears next to a bar, then that Bayes factor has no error estimate available. #' @title Plot a Bayes factor object #' @param x a BFBayesFactor object #' @param include1 if \code{TRUE}, ensure that Bayes factor = 1 is on the plot #' @param addDenom if \code{TRUE}, add the denominator model into the group #' @param sortbf sort the Bayes factors before plotting them? Defaults to #' \code{TRUE} #' @param logbase the base of the log Bayes factors in the plot #' @param marginExpand an expansion factor for the left margin, in case more #' space is needed for model names #' @param cols a vector of length two of valid color names or numbers #' @param main a character vector for the plot title #' @param pars a list of par() settings #' @param ... additional arguments to pass to barplot() #' @method plot BFBayesFactor #' @author Richard D. Morey (\email{richarddmorey@@gmail.com}) #' @examples #' data(puzzles) #' #' bfs = anovaBF(RT ~ shape*color + ID, data = puzzles, whichRandom="ID", progress=FALSE) #' plot(bfs) plot.BFBayesFactor <- function(x, include1=TRUE, addDenom = FALSE, sortbf=TRUE, logbase = c("log10", "log2","ln"), marginExpand = .4, cols = c("wheat","lightslateblue"), main = paste("vs.",x@denominator@longName), pars=NULL, ...){ # eliminate NAs x = x[!is.na(x)] oldPar <- par() on.exit(par(oldPar[c("mfrow","las",names(pars))])) textLogBase = logbase[1] logBase <- switch(textLogBase, log10=10, ln=exp(1), log2=2, stop('Invalid logarithm base.')) # Add denominator if(addDenom) x = c(x, (1/x[1]) / (1/x[1])) if(sortbf) x = sort(x) bfs <- extractBF(x, logbf = TRUE) # Estimate left margin maxChar = max(nchar(rownames(bfs))) leftMargin = marginExpand * maxChar + 4 # Errors whichNA = is.na(bfs$error) bfs$error[whichNA] = 0 errs <- exp(bfs$bf + log(bfs$error)) errs <- log(outer(errs,c(-1,1),'*') + exp(bfs$bf))/log(logBase) if(include1){ rng <- range(c(0,errs)) }else{ rng <- range(errs) } yaxes <- seq(floor(rng[1]), ceiling(rng[2]), 1) ygrids <- seq(yaxes[1], yaxes[length(yaxes)], .1) if(textLogBase=="ln"){ tickLab <- paste("exp(",yaxes,")",sep="") tickLab[yaxes==0] = "1" }else{ tickLab <- logBase^yaxes tickLab[yaxes<0] = paste("1/",logBase^abs(yaxes[yaxes<0]),sep="") } cols = cols[(bfs$bf>0) + 1] pars = c(pars, list(oma=c(5,leftMargin,0,1),las=1,mar=c(0,0,2,0))) par(pars) yloc <- barplot( bfs$bf/log(logBase), names.arg=rownames(bfs), horiz=TRUE, axes=FALSE, xlim=range(yaxes), main = main, col=cols, ...) # add error bars segments(errs[,1],yloc,errs[,2],yloc,col="red") # add unknown errors if(any(whichNA)) mapply(function(x,y,adj) text(x,y,"?",col="red",adj=adj) , x=errs[whichNA,1],y=yloc[whichNA],adj=1-(errs[whichNA,1]>0)) axis(1, at = yaxes, labels=tickLab, las=2) if(length(ygrids) < 50) abline(v=ygrids,col="gray",lty=2) abline(v=yaxes, col="gray") abline(v=0) invisible(NULL) }
/scratch/gouwar.j/cran-all/cranData/BayesFactor/R/plot-BFBayesFactor.R
## S4 method ##### # setMethod("plot", "BFBayesFactor", function(x, include1 = TRUE, addDenom = FALSE, sortbf=TRUE, logbase = c("log10", "log2","ln"), marginExpand=.4,pars=NULL, ...){ # plot.BFBayesFactor(x, include1 = include1, # addDenom = addDenom, # sortbf = sortbf, # logbase = logbase, # marginExpand = marginExpand, # pars = pars, ...) # invisible(NULL) # }) ## S3 method ##### #' Plot a Bayes factor top-down object #' #' This function creates a barplot of the (log) Bayes factors in a Bayes factor #' object. Error bars are added (though in many cases they may be too small to #' see) in red to show the error in estimation of the Bayes factor. If a red question mark #' appears next to a bar, then that Bayes factor has no error estimate available. #' @title Plot a Bayes factor top-down object #' @param x a BFBayesFactorTop object #' @param include1 if \code{TRUE}, ensure that Bayes factor = 1 is on the plot #' @param addDenom if \code{TRUE}, add the denominator model into the group #' @param sortbf sort the Bayes factors before plotting them? Defaults to #' \code{TRUE} #' @param logbase the base of the log Bayes factors in the plot #' @param marginExpand an expansion factor for the left margin, in case more #' space is needed for model names #' @param pars a list of par() settings #' @param ... additional arguments to pass to barplot() #' @method plot BFBayesFactorTop #' @author Richard D. Morey (\email{richarddmorey@@gmail.com}) #' @examples #' data(puzzles) #' #' bfs = anovaBF(RT ~ shape*color + ID, data = puzzles, whichRandom="ID", #' whichModels='top', progress=FALSE) #' plot(bfs) plot.BFBayesFactorTop <- function(x, include1=TRUE, addDenom = FALSE, sortbf=FALSE, logbase = c("log10", "log2","ln"), marginExpand = .4, pars=NULL, ...){ # eliminate NAs x = x[!is.na(x)] oldPar <- par() on.exit(par(oldPar[c("mfrow","las",names(pars))])) textLogBase = logbase[1] logBase <- switch(textLogBase, log10=10, ln=exp(1), log2=2, stop('Invalid logarithm base.')) # Add denominator if(addDenom) x = c(x, (1/x[1]) / (1/x[1])) if(sortbf) x = sort(x) bfs <- extractBF(x, logbf = TRUE) omitted = unlist(lapply(x@numerator, whichOmitted, full = x@denominator)) # Estimate left margin maxChar = max(nchar(omitted)) leftMargin = marginExpand * maxChar + 4 # Errors whichNA = is.na(bfs$error) bfs$error[whichNA] = 0 errs <- exp(bfs$bf + log(bfs$error)) errs <- log(outer(errs,c(-1,1),'*') + exp(bfs$bf))/log(logBase) if(include1){ rng <- range(c(0,errs)) }else{ rng <- range(errs) } yaxes <- seq(floor(rng[1]), ceiling(rng[2]), 1) ygrids <- seq(yaxes[1], yaxes[length(yaxes)], .1) if(textLogBase=="ln"){ tickLab <- paste("exp(",yaxes,")",sep="") tickLab[yaxes==0] = "1" }else{ tickLab <- logBase^yaxes tickLab[yaxes<0] = paste("1/",logBase^abs(yaxes[yaxes<0]),sep="") } cols = c("wheat","lightslateblue")[(bfs$bf>0) + 1] pars = c(pars, list(oma=c(5,leftMargin,0,1),las=1,mar=c(0,0,2,0))) par(pars) yloc <- barplot( bfs$bf/log(logBase), names.arg=omitted, horiz=TRUE, axes=FALSE, xlim=range(yaxes), main = paste("BF change when omitted from\n",x@denominator@longName), col=cols,...) # add error bars segments(errs[,1],yloc,errs[,2],yloc,col="red") # add unknown errors if(any(whichNA)) mapply(function(x,y,adj) text(x,y,"?",col="red",adj=adj) , x=errs[whichNA,1],y=yloc[whichNA],adj=1-(errs[whichNA,1]>0)) axis(1, at = yaxes, labels=tickLab, las=2) if(length(ygrids) < 50) abline(v=ygrids,col="gray",lty=2) abline(v=yaxes, col="gray") abline(v=0) invisible(NULL) }
/scratch/gouwar.j/cran-all/cranData/BayesFactor/R/plot-BFBayesFactorTop.R
makePropHypothesisNames = function(rscale, nullInterval=NULL, p){ if(is.null(nullInterval)){ shortName = paste("Alt., p0=",p,", r=",round(rscale,3),sep="") longName = paste("Alternative, p0 = ",p,", r = ",rscale,", p =/= p0", sep="") }else{ if(!is.null(attr(nullInterval,"complement"))){ shortName = paste("Alt., p0=",p,", r=",round(rscale,3)," !(",nullInterval[1],"<p<",nullInterval[2],")",sep="") longName = paste("Alternative, p0 = ", p ,", r = ",rscale,", p =/= p0 !(",nullInterval[1],"<p<",nullInterval[2],")",sep="") }else{ shortName = paste("Alt., p0=",p,", r=",round(rscale,3)," ",nullInterval[1],"<p<",nullInterval[2],sep="") longName = paste("Alternative, p0 = ",p,", r = ",rscale,", p =/= p0 ",nullInterval[1],"<p<",nullInterval[2],sep="") } } return(list(shortName=shortName,longName=longName)) } like.prop.test = Vectorize(function(lo, y, N, p, rscale, log = FALSE, log.const = 0, shift = 0, scale = 1){ ans = sum(dbinom(y, N, plogis(lo*scale + shift), log=TRUE)) + dlogis(lo*scale + shift, qlogis(p), rscale, log=TRUE) - log.const ifelse(log, ans, exp(ans)) } ,"lo") prop.test.bf.interval <- function(y, N, p, rscale, nullInterval){ intervalProb = plogis(nullInterval, qlogis(p), rscale, log.p = TRUE) prior.interval = logExpXminusExpY(intervalProb[2], intervalProb[1]) beta.a = sum(y) + 1 beta.b = sum(N) - sum(y) + 1 lo.est = qlogis(beta.a/(beta.a + beta.b)) p.var = beta.a * beta.b / ( ( beta.a + beta.b )^2 * ( beta.a + beta.b + 1 ) ) lo.sd = sqrt( p.var / dlogis( lo.est )^2 ) log.const = like.prop.test(lo.est, y = y, N = N, p = p, rscale = rscale, log = TRUE) intgl = integrate(like.prop.test, (nullInterval[1] - lo.est)/lo.sd, (nullInterval[2] - lo.est)/lo.sd, y = y, N = N, p = p, rscale = rscale, log.const = log.const, shift = lo.est, scale = lo.sd) nullLike = sum(dbinom(y, N, p, log = TRUE)) val = log(intgl[[1]]*lo.sd) + log.const - prior.interval - nullLike err = exp(log(intgl[[2]]) + log(lo.sd) - val) return( list( bf = val, properror = err, method = "quadrature" ) ) } prop.test.bf <- function(y, N, p, rscale, interval, complement){ if(length(interval)!=2 & !is.null(interval)) stop("argument interval must have two elements.") if(is.null(interval)){ return(prop.test.bf.interval(y, N, p, rscale, c(-Inf,Inf))) } interval = range(interval) interval = qlogis(interval) if(interval[1]==-Inf & interval[2]==Inf){ if(complement){ return(list(bf=NA,properror=NA)) }else{ return(prop.test.bf.interval(y, N, p, rscale, interval)) } } if(any(is.infinite(interval))){ bf = prop.test.bf.interval(y, N, p, rscale, interval) if(interval[1]==-Inf){ bf.compl = prop.test.bf.interval(y, N, p, rscale, c(interval[2], Inf)) }else{ bf.compl = prop.test.bf.interval(y, N, p, rscale, c(-Inf,interval[1])) } }else{ logPriorProbs = plogis(c(-Inf,interval,Inf), qlogis(p), scale=rscale,log.p=TRUE) prior.interval1 = logExpXminusExpY(logPriorProbs[2], logPriorProbs[1]) prior.interval3 = logExpXminusExpY(logPriorProbs[4], logPriorProbs[3]) prior.interval.1.3 = logMeanExpLogs(c(prior.interval1,prior.interval3)) + log(2) bf1 = prop.test.bf.interval(y, N, p, rscale, c(-Inf,interval[1])) bf = prop.test.bf.interval(y, N, p, rscale, interval) bf3 = prop.test.bf.interval(y, N, p, rscale, c(interval[2],Inf)) bf.compl = sumWithPropErr(bf1[['bf']] + prior.interval1, bf3[['bf']] + prior.interval3, bf1[['properror']], bf3[['properror']]) bf.compl[1] = bf.compl[1] - prior.interval.1.3 } if(complement){ return( list( bf = bf.compl[[1]], properror = bf.compl[[2]], method = "quadrature" )) }else{ return( list( bf = bf[['bf']], properror = bf[['properror']], method = bf[['method']] )) } } proportion.Metrop <- function(y, N, nullModel, iterations=10000, nullInterval=NULL, p, rscale, progress=getOption('BFprogress', interactive()), noSample=FALSE, callback = NULL, callbackInterval = 1){ if(length(y)!=length(N)) stop("lengths of t and n1 must be equal.") iterations = as.integer(iterations) progress = as.logical(progress) if(is.null(callback) | !is.function(callback)) callback=function(...) as.integer(0) if(is.null(nullInterval) | nullModel){ doInterval = FALSE nullInterval = c(0, 1) intervalCompl = FALSE }else{ doInterval = TRUE intervalCompl = ifelse(!is.null(attr(nullInterval,"complement")),TRUE,FALSE) nullInterval = range(nullInterval) } if(noSample){ chains = matrix(as.numeric(NA),1,1) }else{ if(nullModel) rscale = 0 chains = metropProportionRcpp(y, N, p, rscale, iterations, doInterval, qlogis(nullInterval), intervalCompl, nullModel, progress, callback, callbackInterval) if(!nullModel & !noSample){ acc.rate = mean(diff(chains) != 0) message("Independent-candidate M-H acceptance rate: ",round(100*acc.rate),"%") } } chains = mcmc(data.frame(logodds = chains, p = plogis(chains))) return(chains) }
/scratch/gouwar.j/cran-all/cranData/BayesFactor/R/proportion-utility.R
##' Bayes factors or posterior samples for binomial, geometric, or neg. binomial data. ##' ##' Given count data modeled as a binomial, geometric, or negative binomial random variable, ##' the Bayes factor provided by \code{proportionBF} tests the null hypothesis that ##' the probability of a success is \eqn{p_0}{p_0} (argument \code{p}). Specifically, ##' the Bayes factor compares two hypotheses: that the probability is \eqn{p_0}{p_0}, or ##' probability is not \eqn{p_0}{p_0}. Currently, the default alternative is that ##' \deqn{\lambda~logistic(\lambda_0,r)} where ##' \eqn{\lambda_0=logit(p_0)}{lambda_0=logit(p_0)} and ##' \eqn{\lambda=logit(p)}{lambda=logit(p)}. \eqn{r}{r} serves as a prior scale parameter. ##' ##' For the \code{rscale} argument, several named values are recognized: ##' "medium", "wide", and "ultrawide". These correspond ##' to \eqn{r} scale values of \eqn{1/2}{1/2}, \eqn{\sqrt{2}/2}{sqrt(2)/2}, and 1, ##' respectively. ##' ##' The Bayes factor is computed via Gaussian quadrature, and posterior ##' samples are drawn via independence Metropolis-Hastings. ##' @title Function for Bayesian analysis of proportions ##' @param y a vector of successes ##' @param N a vector of total number of observations ##' @param p the null value for the probability of a success to be tested against ##' @param rscale prior scale. A number of preset values can be given as ##' strings; see Details. ##' @param nullInterval optional vector of length 2 containing ##' lower and upper bounds of an interval hypothesis to test, in probability units ##' @param posterior if \code{TRUE}, return samples from the posterior instead ##' of Bayes factor ##' @param callback callback function for third-party interfaces ##' @param ... further arguments to be passed to or from methods. ##' @return If \code{posterior} is \code{FALSE}, an object of class ##' \code{BFBayesFactor} containing the computed model comparisons is ##' returned. If \code{nullInterval} is defined, then two Bayes factors will ##' be computed: The Bayes factor for the interval against the null hypothesis ##' that the probability is \eqn{p_0}{p0}, and the corresponding Bayes factor for ##' the compliment of the interval. ##' ##' If \code{posterior} is \code{TRUE}, an object of class \code{BFmcmc}, ##' containing MCMC samples from the posterior is returned. ##' @export ##' @keywords htest ##' @author Richard D. Morey (\email{richarddmorey@@gmail.com}) ##' @examples ##' bf = proportionBF(y = 15, N = 25, p = .5) ##' bf ##' ## Sample from the corresponding posterior distribution ##' samples =proportionBF(y = 15, N = 25, p = .5, posterior = TRUE, iterations = 10000) ##' plot(samples[,"p"]) ##' @seealso \code{\link{prop.test}} proportionBF <- function(y, N, p, rscale = "medium", nullInterval = NULL, posterior=FALSE, callback = function(...) as.integer(0), ...) { if (p >= 1 || p <= 0) stop('p must be between 0 and 1', call.=FALSE) if(!is.null(nullInterval)){ if(any(nullInterval<0) | any(nullInterval>1)) stop("nullInterval endpoints must be in [0,1].") nullInterval = range(nullInterval) } rscale = rpriorValues("proptest",,rscale) if( length(p) > 1 ) stop("Only a single null allowed (length(p) > 1).") if( length(y) != length(N) ) stop("Length of y and N must be the same.") if( any(y>N) | any(y < 0) ) stop("Invalid data (y>N or y<0).") if( any( c(y,N)%%1 != 0 ) ) stop("y and N must be integers.") hypNames = makePropHypothesisNames(rscale, nullInterval, p) mod1 = BFproportion(type = "logistic", identifier = list(formula = "p =/= p0", nullInterval = nullInterval, p0 = p), prior=list(rscale=rscale, nullInterval = nullInterval, p0 = p), shortName = hypNames$shortName, longName = hypNames$longName ) data = data.frame(y = y, N = N) checkCallback(callback,as.integer(0)) if(posterior) return(posterior(mod1, data = data, callback = callback, ...)) bf1 = compare(numerator = mod1, data = data) if(!is.null(nullInterval)){ mod2 = mod1 attr(mod2@identifier$nullInterval, "complement") = TRUE attr(mod2@prior$nullInterval, "complement") = TRUE hypNames = makePropHypothesisNames(rscale, mod2@identifier$nullInterval,p) mod2@shortName = hypNames$shortName mod2@longName = hypNames$longName bf2 = compare(numerator = mod2, data = data) checkCallback(callback,as.integer(1000)) return(c(bf1, bf2)) }else{ checkCallback(callback,as.integer(1000)) return(c(bf1)) } }
/scratch/gouwar.j/cran-all/cranData/BayesFactor/R/proportionBF.R
enumerateRegressionModels = function(fmla, whichModels, data){ trms <- attr(terms(fmla, data = data), "term.labels") ntrms <- length(trms) dv = stringFromFormula(fmla[[2]]) dv = composeTerm(dv) if(ntrms == 1 ) whichModels = "all" if(whichModels=="top"){ lst = combn2( trms, ntrms - 1 ) }else if(whichModels=="all"){ lst = combn2( trms, 1 ) }else if(whichModels=='bottom'){ lst = as.list(combn( trms, 1 )) }else{ stop("Unknown whichModels value: ",whichModels) } strng <- lapply(lst,function(el){ paste(el,collapse=" + ") }) fmla <- lapply(strng, function(el){ formula(paste(dv,"~", el)) }) return(fmla) } createFullRegressionModel <- function(formula, data){ factors = fmlaFactors(formula, data)[-1] factors = composeTerms(factors) dv = stringFromFormula(formula[[2]]) dv = composeTerm(dv) RHS = paste(factors,collapse=" + ") strng = paste(dv, " ~ ", RHS, collapse = "") return(formula(strng)) } integrand.regression=Vectorize(function(g, N, p, R2, rscaleSqr=1, log=FALSE, log.const=0){ a = .5 * ((N - p - 1 ) * log(1 + g) - (N - 1) * log(1 + g * (1 - R2))) shape=.5 scale=rscaleSqr*N/2 log.density.igam <- dinvgamma(g, shape, scale, log=TRUE) ans = a + log.density.igam - log.const ifelse(log,ans,exp(ans)) },"g") # This is a more numerically stable version of the integrand, as a function of log(g) integrand.regression.u=Vectorize(function(u, N, p, R2, rscaleSqr=1, log=FALSE, log.const=0, shift = 0){ u = u + shift a = .5 * ((N - p - 1 ) * log1pExp(u) - (N - 1) * log1pExp(u + log(1 - R2))) shape=.5 scale=rscaleSqr*N/2 log.density.igam <- dinvgamma(u, shape, scale, log=TRUE, logx=TRUE) ans = a + log.density.igam - log.const + u ifelse(log,ans,exp(ans)) },"u") linearReg.Gibbs <- function(y, covariates, iterations = 10000, rscale = "medium", progress = getOption('BFprogress', interactive()), callback=function(...) as.integer(0), noSample=FALSE, callbackInterval = 1, ignoreCols = NULL, thin = 1, ...){ rscale = rpriorValues("allNways","continuous",rscale) X = apply(covariates,2,function(v) v - mean(v)) y = matrix(y,ncol=1) N = length(y) P = ncol(X) nGs = 1 if(is.null(ignoreCols)) ignoreCols = rep(0,P) # Check thinning to make sure number is reasonable if( (thin<1) | (thin>(iterations/3)) ) stop("MCMC thin parameter cannot be less than 1 or greater than iterations/3. Was:", thin) gMap = rep(0, P) sig2start = sum( (X%*%solve(t(X)%*%X)%*%t(X)%*%y - y)^2 ) / N progress = as.logical(progress) if(is.null(callback) | !is.function(callback)) callback=function(...) as.integer(0) if(noSample){ # Return structure of chains chains = matrix(NA, 2, P + 2 + nGs) }else{ chains = jzs_Gibbs(iterations, y, cbind(1,X), rscale, sig2start, gMap, table(gMap), P, FALSE, as.integer(ignoreCols), as.integer(thin), as.logical(progress), callback, 1) } colnames(chains) = c("mu", colnames(covariates), "sig2", "g") chains = mcmc(chains) return(chains) }
/scratch/gouwar.j/cran-all/cranData/BayesFactor/R/regressionBF-utility.R
##' This function simultaneously computes Bayes factors for groups of models in ##' regression designs ##' ##' \code{regressionBF} computes Bayes factors to test the hypothesis that ##' slopes are 0 against the alternative that all slopes are nonzero. ##' ##' The vector of observations \eqn{y} is assumed to be distributed as \deqn{y ~ ##' Normal(\alpha 1 + X\beta, \sigma^2 I).} The joint prior on ##' \eqn{\alpha,\sigma^2} is proportional to \eqn{1/\sigma^2}, the prior on ##' \eqn{\beta} is \deqn{\beta ~ Normal(0, N g \sigma^2(X'X)^{-1}).} where ##' \eqn{g ~ InverseGamma(1/2,r/2)}. See Liang et al. (2008) section 3 for ##' details. ##' ##' Possible values for \code{whichModels} are 'all', 'top', and 'bottom', where ##' 'all' computes Bayes factors for all models, 'top' computes the Bayes ##' factors for models that have one covariate missing from the full model, and ##' 'bottom' computes the Bayes factors for all models containing a single ##' covariate. Caution should be used when interpreting the results; when the ##' results of 'top' testing is interpreted as a test of each covariate, the ##' test is conditional on all other covariates being in the model (and likewise ##' 'bottom' testing is conditional on no other covariates being in the model). ##' ##' An option is included to prevent analyzing too many models at once: ##' \code{options('BFMaxModels')}, which defaults to 50,000, is the maximum ##' number of models that `regressionBF` will analyze at once. This can be ##' increased by increasing the option value. ##' ##' For the \code{rscaleCont} argument, several named values are recongized: ##' "medium", "wide", and "ultrawide", which correspond \eqn{r} scales of ##' \eqn{\sqrt{2}/4}{sqrt(2)/4}, 1/2, and \eqn{\sqrt{2}/2}{sqrt(2)/2}, ##' respectively. These values were chosen to yield consistent Bayes factors ##' with \code{\link{anovaBF}}. ##' @title Function to compute Bayes factors for regression designs ##' @param formula a formula containing all covariates to include in the ##' analysis (see Examples) ##' @param data a data frame containing data for all factors in the formula ##' @param whichModels which set of models to compare; see Details ##' @param progress if \code{TRUE}, show progress with a text progress bar ##' @param rscaleCont prior scale on all standardized slopes ##' @param noSample if \code{TRUE}, do not sample, instead returning NA. ##' @param callback callback function for third-party interfaces ##' @return An object of class \code{BFBayesFactor}, containing the computed ##' model comparisons ##' @author Richard D. Morey (\email{richarddmorey@@gmail.com}) ##' @references Liang, F. and Paulo, R. and Molina, G. and Clyde, M. A. and ##' Berger, J. O. (2008). Mixtures of g-priors for Bayesian Variable ##' Selection. Journal of the American Statistical Association, 103, pp. ##' 410-423 ##' ##' Rouder, J. N. and Morey, R. D. (in press). Bayesian testing in ##' regression. Multivariate Behavioral Research. ##' ##' Zellner, A. and Siow, A., (1980) Posterior Odds Ratios for Selected ##' Regression Hypotheses. In Bayesian Statistics: Proceedings of the First ##' Interanational Meeting held in Valencia (Spain). Bernardo, J. M., ##' Lindley, D. V., and Smith A. F. M. (eds), pp. 585-603. University of ##' Valencia. ##' @export ##' @keywords htest ##' @examples ##' ## See help(attitude) for details about the data set ##' data(attitude) ##' ##' ## Classical regression ##' summary(fm1 <- lm(rating ~ ., data = attitude)) ##' ##' ## Compute Bayes factors for all regression models ##' output = regressionBF(rating ~ ., data = attitude, progress=FALSE) ##' head(output) ##' ## Best model is 'complaints' only ##' ##' ## Compute all Bayes factors against the full model, and ##' ## look again at best models ##' head(output / output[63]) ##' ##' @seealso \code{\link{lmBF}}, for testing specific models, and ##' \code{\link{anovaBF}} for the function similar to \code{regressionBF} for ##' ANOVA models. regressionBF <- function(formula, data, whichModels = "all", progress=getOption('BFprogress', interactive()), rscaleCont = "medium", callback = function(...) as.integer(0), noSample=FALSE) { data <- marshallTibble(data) checkFormula(formula, data, analysis = "regression") dataTypes <- createDataTypes(formula, whichRandom=c(), data, analysis = "regression") fmla <- createFullRegressionModel(formula, data) models <- enumerateRegressionModels(fmla, whichModels, data) if(length(models)>getOption('BFMaxModels', 50000)) stop("Maximum number of models exceeded (", length(models), " > ",getOption('BFMaxModels', 50000) ,"). ", "The maximum can be increased by changing ", "options('BFMaxModels').") bfs = NULL if(progress){ pb = txtProgressBar(min = 0, max = length(models), style = 3) }else{ pb = NULL } checkCallback(callback,as.integer(0)) for(i in 1:length(models)){ oneModel <- lmBF(models[[i]],data = data, dataTypes = dataTypes, rscaleCont = rscaleCont,noSample=noSample) if(inherits(pb,"txtProgressBar")) setTxtProgressBar(pb, i) checkCallback(callback,as.integer((i - 1)/length(models) * 1000)) bfs = c(bfs,oneModel) } if(inherits(pb,"txtProgressBar")) close(pb) checkCallback(callback,as.integer(1000)) bfObj = do.call("c", bfs) if(whichModels=="top") bfObj = BFBayesFactorTop(bfObj) return(bfObj) }
/scratch/gouwar.j/cran-all/cranData/BayesFactor/R/regressionBF.R
library(hypergeo) A <- function(t, n, nu, mu.delta, g) { Re(hypergeo::genhypergeo(U = (nu + 1)/2, L = 1/2, z = mu.delta^2*t^2/ (2*(1/n + g)*((1 + n*g)*nu + t^2)))) } B <- function(t, n, nu, mu.delta, g) { out <- mu.delta*t/sqrt(1/2*(1/n + g)*((1 + n*g)*nu + t^2)) * exp(lgamma((nu + 2)/2) - lgamma((nu + 1)/2)) * Re(hypergeo::genhypergeo(U = (nu + 2)/2, L = 3/2, z = mu.delta^2*t^2/ (2*(1/n + g)*((1 + n*g)*nu + t^2)))) return(out) } C <- function(delta, t, n, nu) { Re(hypergeo::genhypergeo(U = (nu + 1)/2, L = 1/2, z = n*t^2*delta^2/(2*(nu + t^2)))) } D <- function(delta, t, n, nu) { out <- t*delta*sqrt(2*n/(nu + t^2))* exp(lgamma((nu + 2)/2) - lgamma((nu + 1)/2))* Re(hypergeo::genhypergeo(U = (nu + 2)/2, L = 3/2, z = n*t^2*delta^2/(2*(nu + t^2)))) return(out) } term_normalprior <- function(t, n, nu, mu.delta, g) { (1 + n*g)^(-1/2) * exp(-mu.delta^2/(2*(1/n + g))) * (1 + t^2/(nu*(1 + n*g)))^(-(nu + 1)/2) * (A(t, n, nu, mu.delta, g) + B(t, n, nu, mu.delta, g)) } integrand <- function(g, t, n, nu, mu.delta, r, kappa) { tmp <- term_normalprior(t = t, n = n, nu = nu, mu.delta = mu.delta, g = g) pg_log <- kappa/2*(2*log(r) + log(kappa/2)) - lgamma(kappa/2) - (kappa/2 + 1)*log(g) - r^2*kappa/(2*g) pg <- exp(pg_log) out <- tmp*pg return(out) } dtss <- function(delta, mu.delta, r, kappa, log = FALSE) { out <- - log(r) + lgamma((kappa + 1)/2) - .5*(log(pi) + log(kappa)) - lgamma(kappa/2) - (kappa + 1)/2 * log(1 + ((delta - mu.delta)/r)^2/kappa) if ( ! log) out <- exp(out) return(out) } posterior_t_tmp <- function(delta, t, ny, nx = NULL, independentSamples = FALSE, prior.location, prior.scale, prior.df, rel.tol = .Machine$double.eps^0.25) { neff <- ifelse(independentSamples, ny*nx/(ny + nx), ny) nu <- ifelse(independentSamples, ny + nx - 2, ny - 1) mu.delta <- prior.location r <- prior.scale kappa <- prior.df numerator <- exp(-neff/2*delta^2)*(1 + t^2/nu)^(-(nu + 1)/2)* (C(delta, t, neff, nu) + D(delta, t, neff, nu))* dtss(delta, mu.delta, r, kappa) denominator <- integrate(integrand, lower = 0, upper = Inf, t = t, n = neff, nu = nu, mu.delta = mu.delta, r = r, kappa = kappa, rel.tol = rel.tol)$value out <- numerator/denominator if ( is.na(out)) out <- 0 return(out) } posterior_t <- Vectorize(posterior_t_tmp, "delta") cdf_t <- function(x, t, ny, nx = NULL, independentSamples = FALSE, prior.location, prior.scale, prior.df) { integrate(posterior_t, lower = -Inf, upper = x, t = t, ny = ny, nx = nx, independentSamples = independentSamples, prior.location = prior.location, prior.scale = prior.scale, prior.df = prior.df)$value } quantile_t <- function(q, t, ny, nx = NULL, independentSamples = FALSE, prior.location, prior.scale, prior.df, tol = 0.0001, max.iter = 100) { # compute quantiles via Newton-Raphson method x.cur <- Inf # get reasonable starting value delta <- seq(-2, 2, length.out = 400) dens <- posterior_t(delta, t = t, ny = ny, nx = nx, independentSamples = independentSamples, prior.location = prior.location, prior.scale = prior.scale, prior.df = prior.df) x.new <- delta[which.max(dens)] i <- 1 while (abs(x.cur - x.new) > tol && i < max.iter) { x.cur <- x.new x.new <- x.cur - (cdf_t(x.cur, t = t, ny = ny, nx = nx, independentSamples = independentSamples, prior.location = prior.location, prior.scale = prior.scale, prior.df = prior.df) - q)/ posterior_t(x.cur, t = t, ny = ny, nx = nx, independentSamples = independentSamples, prior.location = prior.location, prior.scale = prior.scale, prior.df = prior.df) i <- i + 1 } return(x.new) } ciPlusMedian_t <- function(t, ny, nx = NULL, independentSamples = FALSE, prior.location, prior.scale, prior.df, ci = .95, type = "two-sided", tol = 0.0001, max.iter = 100) { lower <- (1 - ci)/2 upper <- ci + (1 - ci)/2 med <- .5 postAreaSmaller0 <- cdf_t(x = 0, t = t, ny = ny, nx = nx, independentSamples = independentSamples, prior.location = prior.location, prior.scale = prior.scale, prior.df = prior.df) if (type == "plus-sided") { lower <- postAreaSmaller0 + (1 - postAreaSmaller0)*lower upper <- postAreaSmaller0 + (1 - postAreaSmaller0)*upper med <- postAreaSmaller0 + (1 - postAreaSmaller0)*med } else if (type == "min-sided") { lower <- postAreaSmaller0*lower upper <- postAreaSmaller0*upper med <- postAreaSmaller0*med } ciLower <- quantile_t(lower, t = t, ny = ny, nx = nx, independentSamples = independentSamples, prior.location = prior.location, prior.scale = prior.scale, prior.df = prior.df) ciUpper <- quantile_t(upper, t = t, ny = ny, nx = nx, independentSamples = independentSamples, prior.location = prior.location, prior.scale = prior.scale, prior.df = prior.df) median <- quantile_t(med, t = t, ny = ny, nx = nx, independentSamples = independentSamples, prior.location = prior.location, prior.scale = prior.scale, prior.df = prior.df) return(list(ciLower = ciLower, median = median, ciUpper = ciUpper)) } posterior_normal_tmp <- function(delta, t, ny, nx = NULL, independentSamples = FALSE, prior.mean, prior.variance, rel.tol = .Machine$double.eps^0.25) { neff <- ifelse(independentSamples, ny*nx/(ny + nx), ny) nu <- ifelse(independentSamples, ny + nx - 2, ny - 1) mu.delta <- prior.mean g <- prior.variance numerator <- exp(-neff/2*delta^2)*(1 + t^2/nu)^(-(nu + 1)/2)* (C(delta, t, neff, nu) + D(delta, t, neff, nu))* dnorm(delta, mu.delta, sqrt(g)) denominator <- term_normalprior(t = t, n = neff, nu = nu, mu.delta = mu.delta, g = g) out <- numerator/denominator if ( is.na(out)) out <- 0 return(out) } posterior_normal <- Vectorize(posterior_normal_tmp, "delta") cdf_normal <- function(x, t, ny, nx = NULL, independentSamples = FALSE, prior.mean, prior.variance) { integrate(posterior_normal, lower = -Inf, upper = x, t = t, ny = ny, nx = nx, independentSamples = independentSamples, prior.mean = prior.mean, prior.variance = prior.variance)$value } quantile_normal <- function(q, t, ny, nx = NULL, independentSamples = FALSE, prior.mean, prior.variance, tol = 0.0001, max.iter = 100) { # compute quantiles via Newton-Raphson method x.cur <- Inf # get reasonable start value delta <- seq(-2, 2, length.out = 400) dens <- posterior_normal(delta, t = t, ny = ny, nx = nx, independentSamples = independentSamples, prior.mean = prior.mean, prior.variance = prior.variance) x.new <- delta[which.max(dens)] i <- 1 while (abs(x.cur - x.new) > tol && i < max.iter) { x.cur <- x.new x.new <- x.cur - (cdf_normal(x.cur, t = t, ny = ny, nx = nx, independentSamples = independentSamples, prior.mean = prior.mean, prior.variance = prior.variance) - q)/ posterior_normal(x.cur, t = t, ny = ny, nx = nx, independentSamples = independentSamples, prior.mean = prior.mean, prior.variance = prior.variance) i <- i + 1 } return(x.new) } ciPlusMedian_normal <- function(t, ny, nx = NULL, independentSamples = FALSE, prior.mean, prior.variance, ci = .95, type = "two-sided", tol = 0.0001, max.iter = 100) { lower <- (1 - ci)/2 upper <- ci + (1 - ci)/2 med <- .5 postAreaSmaller0 <- cdf_normal(x = 0, t = t, ny = ny, nx = nx, independentSamples = independentSamples, prior.mean = prior.mean, prior.variance = prior.variance) if (type == "plus-sided") { lower <- postAreaSmaller0 + (1 - postAreaSmaller0)*lower upper <- postAreaSmaller0 + (1 - postAreaSmaller0)*upper med <- postAreaSmaller0 + (1 - postAreaSmaller0)*med } else if (type == "min-sided") { lower <- postAreaSmaller0*lower upper <- postAreaSmaller0*upper med <- postAreaSmaller0*med } ciLower <- quantile_normal(lower, t = t, ny = ny, nx = nx, independentSamples = independentSamples, prior.mean = prior.mean, prior.variance = prior.variance) ciUpper <- quantile_normal(upper, t = t, ny = ny, nx = nx, independentSamples = independentSamples, prior.mean = prior.mean, prior.variance = prior.variance) median <- quantile_normal(med, t = t, ny = ny, nx = nx, independentSamples = independentSamples, prior.mean = prior.mean, prior.variance = prior.variance) return(list(ciLower = ciLower, median = median, ciUpper = ciUpper)) } bf10_t <- function(t, ny, nx = NULL, independentSamples = FALSE, prior.location, prior.scale, prior.df, rel.tol = .Machine$double.eps^0.25) { neff <- ifelse(independentSamples, ny*nx/(ny + nx), ny) nu <- ifelse(independentSamples, ny + nx - 2, ny - 1) mu.delta <- prior.location r <- prior.scale kappa <- prior.df numerator <- integrate(integrand, lower = 0, upper = Inf, t = t, n = neff, nu = nu, mu.delta = mu.delta, r = r, kappa = kappa, rel.tol = rel.tol)$value denominator <- (1 + t^2/nu)^(-(nu + 1)/2) BF10 <- numerator/denominator priorAreaSmaller0 <- integrate(dtss, lower = -Inf, upper = 0, mu.delta = prior.location, r = prior.scale, kappa = prior.df)$value postAreaSmaller0 <- cdf_t(x = 0, t = t, ny = ny, nx = nx, independentSamples = independentSamples, prior.location = prior.location, prior.scale = prior.scale, prior.df = prior.df) BFmin1 <- postAreaSmaller0/priorAreaSmaller0 BFplus1 <- (1 - postAreaSmaller0)/(1 - priorAreaSmaller0) BFmin0 <- BFmin1 * BF10 BFplus0 <- BFplus1 * BF10 return(list(BF10 = BF10, BFplus0 = BFplus0, BFmin0 = BFmin0)) } bf10_normal <- function(t, ny, nx = NULL, independentSamples = FALSE, prior.mean, prior.variance) { neff <- ifelse(independentSamples, ny*nx/(ny + nx), ny) nu <- ifelse(independentSamples, ny + nx - 2, ny - 1) mu.delta <- prior.mean g <- prior.variance numerator <- term_normalprior(t = t, n = neff, nu = nu, mu.delta = mu.delta, g = g) denominator <- (1 + t^2/nu)^(-(nu + 1)/2) BF10 <- numerator/denominator priorAreaSmaller0 <- pnorm(0, mean = prior.mean, sd = sqrt(prior.variance)) postAreaSmaller0 <- cdf_normal(x = 0, t = t, ny = ny, nx = nx, independentSamples = independentSamples, prior.mean = prior.mean, prior.variance = prior.variance) BFmin1 <- postAreaSmaller0/priorAreaSmaller0 BFplus1 <- (1 - postAreaSmaller0)/(1 - priorAreaSmaller0) BFmin0 <- BFmin1 * BF10 BFplus0 <- BFplus1 * BF10 return(list(BF10 = BF10, BFplus0 = BFplus0, BFmin0 = BFmin0)) }
/scratch/gouwar.j/cran-all/cranData/BayesFactor/R/ttest-informed-JASP.R
makeTtestHypothesisNames = function(rscale, nullInterval=NULL, mu = 0){ if(is.null(nullInterval)){ shortName = paste("Alt., r=",round(rscale,3),sep="") longName = paste("Alternative, r = ",rscale,", mu =/= ",mu, sep="") }else{ if(!is.null(attr(nullInterval,"complement"))){ shortName = paste("Alt., r=",round(rscale,3)," !(",nullInterval[1],"<d<",nullInterval[2], ")",sep="") longName = paste("Alternative, r = ",rscale,", mu =/= ",mu, " !(",nullInterval[1],"<d<",nullInterval[2],")",sep="") }else{ shortName = paste("Alt., r=",round(rscale,3)," ",nullInterval[1],"<d<",nullInterval[2],sep="") longName = paste("Alternative, r = ",rscale,", mu =/= ",mu, " ",nullInterval[1],"<d<",nullInterval[2],sep="") } } return(list(shortName=shortName,longName=longName)) } ttestBF_oneSample = function(x, mu, nullInterval, rscale, posterior, callback, ... ){ rscale = rpriorValues("ttestOne",,rscale) hypNames = makeTtestHypothesisNames(rscale, nullInterval, mu = mu) mod1 = BFoneSample(type = "JZS", identifier = list(formula = "y ~ 1", nullInterval = nullInterval), prior=list(rscale=rscale, mu=mu, nullInterval = nullInterval), shortName = hypNames$shortName, longName = hypNames$longName) if(posterior) return(posterior(mod1, data = data.frame(y=x), callback = callback, ...)) bf1 = compare(numerator = mod1, data = data.frame(y=x)) if(!is.null(nullInterval)){ mod2 = mod1 attr(mod2@identifier$nullInterval, "complement") = TRUE attr(mod2@prior$nullInterval, "complement") = TRUE hypNames = makeTtestHypothesisNames(rscale, mod2@identifier$nullInterval, mu = mu) mod2@shortName = hypNames$shortName mod2@longName = hypNames$longName bf2 = compare(numerator = mod2, data = data.frame(y=x)) checkCallback(callback,as.integer(1000)) return(c(bf1,bf2)) }else{ checkCallback(callback,as.integer(1000)) return(bf1) } } ttestBF_indepSample = function(formula, data, mu, nullInterval, rscale, posterior, callback, ... ){ checkFormula(formula, data, analysis = "indept") rscale = rpriorValues("ttestTwo",,rscale) hypNames = makeTtestHypothesisNames(rscale, nullInterval, mu = mu) mod1 = BFindepSample(type = "JZS", identifier = list(formula = stringFromFormula(formula), nullInterval = nullInterval), prior=list(rscale=rscale, mu=mu, nullInterval = nullInterval), shortName = hypNames$shortName, longName = hypNames$longName ) if(posterior) return(posterior(mod1, data = data, callback = callback, ...)) bf1 = compare(numerator = mod1, data = data) if(!is.null(nullInterval)){ mod2 = mod1 attr(mod2@identifier$nullInterval, "complement") = TRUE attr(mod2@prior$nullInterval, "complement") = TRUE hypNames = makeTtestHypothesisNames(rscale, mod2@identifier$nullInterval, mu = mu) mod2@shortName = hypNames$shortName mod2@longName = hypNames$longName bf2 = compare(numerator = mod2, data = data) checkCallback(callback,as.integer(1000)) return(c(bf1, bf2)) }else{ checkCallback(callback,as.integer(1000)) return(bf1) } } ttestOneSample.Gibbs = function(y, nullModel, iterations, rscale, nullInterval, progress=getOption('BFprogress', interactive()), noSample=FALSE, callback=NULL, callbackInterval = 1){ n = as.integer(length(y)) rscale = ifelse(nullModel,1,rpriorValues("ttestOne",,rscale)) iterations = as.integer(iterations) progress = as.logical(progress) if(is.null(nullInterval)){ do.interval = FALSE nullInterval = c(-Inf,Inf) complement = FALSE }else{ if(length(nullInterval)!=2){ stop("nullInterval must be a vector of length 2.") } do.interval=TRUE complement = ifelse(!is.null(attr(nullInterval,"complement")),TRUE,FALSE) } if(is.null(callback) | !is.function(callback)) callback=function(...) as.integer(0) if(noSample){ chains = matrix(as.numeric(NA),4,2) }else{ chains = gibbsOneSampleRcpp(mean(y), var(y), n, rscale, iterations, do.interval, nullInterval, complement, nullModel, progress, callback, callbackInterval) } colnames(chains) = c("mu","sig2","delta","g") if(nullModel){ return(mcmc(chains[,-4])) }else{ return(mcmc(chains)) } } ttestIndepSample.Gibbs = function(formula, data, nullModel, iterations, rscale, nullInterval, progress=getOption('BFprogress', interactive()), noSample=FALSE, callback=NULL, callbackInterval = 1){ depVar = as.character(formula[[2]]) if(nullModel){ # If sampling from the null model, it doesn't matter how we divide the data fakeIndepVar = c(1,1,rep(2, nrow(data) - 2)) ybar = tapply(data[,depVar], fakeIndepVar, mean) s2 = tapply(data[,depVar], fakeIndepVar, var) N = tapply(data[,depVar], fakeIndepVar, length) rscale = 1 }else{ indepVar = as.character(formula[[3]]) spltData = rev(split(data[,depVar], factor(data[,indepVar]))) ybar = sapply(spltData, mean) if(length(ybar)!=2) stop("Incorrect number of levels in independent variable.") s2 = sapply(spltData, var) N = sapply(spltData, length) grp.names = names(spltData) effect.direction = paste(rev(grp.names), collapse = " - ") rscale = rpriorValues("ttestTwo",,rscale) } iterations = as.integer(iterations) progress = as.logical(progress) if(is.null(nullInterval)){ do.interval = FALSE nullInterval = c(-Inf,Inf) complement = FALSE }else{ if(length(nullInterval)!=2){ stop("nullInterval must be a vector of length 2.") } do.interval=TRUE complement = ifelse(!is.null(attr(nullInterval,"complement")),TRUE,FALSE) } if(is.null(callback) | !is.function(callback)) callback=function(...) as.integer(0) if(noSample){ chains = matrix(as.numeric(NA),5,2) }else{ chains = gibbsTwoSampleRcpp(ybar, s2, N, rscale, iterations, do.interval, nullInterval, complement, nullModel, progress, callback, callbackInterval) } if(nullModel){ colnames(chains) = c("mu","beta","sig2","delta","g") return(mcmc(chains[,-5])) }else{ colnames(chains) = c("mu",paste("beta (",effect.direction,")",sep=""),"sig2","delta","g") return(mcmc(chains)) } }
/scratch/gouwar.j/cran-all/cranData/BayesFactor/R/ttest-utility.R
##' This function computes Bayes factors, or samples from the posterior, for ##' one- and two-sample designs. ##' ##' The Bayes factor provided by \code{ttestBF} tests the null hypothesis that ##' the mean (or mean difference) of a normal population is \eqn{\mu_0}{mu0} ##' (argument \code{mu}). Specifically, the Bayes factor compares two ##' hypotheses: that the standardized effect size is 0, or that the standardized ##' effect size is not 0. For one-sample tests, the standardized effect size is ##' \eqn{(\mu-\mu_0)/\sigma}{(mu-mu0)/sigma}; for two sample tests, the ##' standardized effect size is \eqn{(\mu_2-\mu_1)/\sigma}{(mu2-mu1)/sigma}. ##' ##' A noninformative Jeffreys prior is placed on the variance of the normal ##' population, while a Cauchy prior is placed on the standardized effect size. ##' The \code{rscale} argument controls the scale of the prior distribution, ##' with \code{rscale=1} yielding a standard Cauchy prior. See the references ##' below for more details. ##' ##' For the \code{rscale} argument, several named values are recognized: ##' "medium", "wide", and "ultrawide". These correspond ##' to \eqn{r} scale values of \eqn{\sqrt{2}/2}{sqrt(2)/2}, 1, and \eqn{\sqrt{2}}{sqrt(2)} ##' respectively. ##' ##' The Bayes factor is computed via Gaussian quadrature. ##' @title Function for Bayesian analysis of one- and two-sample designs ##' @param x a vector of observations for the first (or only) group ##' @param y a vector of observations for the second group (or condition, for ##' paired) ##' @param formula for independent-group designs, a (optional) formula ##' describing the model ##' @param mu for one-sample and paired designs, the null value of the mean (or ##' mean difference) ##' @param nullInterval optional vector of length 2 containing lower and upper bounds of an interval hypothesis to test, in standardized units ##' @param paired if \code{TRUE}, observations are paired ##' @param data for use with \code{formula}, a data frame containing all the ##' data ##' @param rscale prior scale. A number of preset values can be given as ##' strings; see Details. ##' @param posterior if \code{TRUE}, return samples from the posterior instead ##' of Bayes factor ##' @param callback callback function for third-party interfaces ##' @param ... further arguments to be passed to or from methods. ##' @return If \code{posterior} is \code{FALSE}, an object of class ##' \code{BFBayesFactor} containing the computed model comparisons is ##' returned. If \code{nullInterval} is defined, then two Bayes factors will ##' be computed: The Bayes factor for the interval against the null hypothesis ##' that the standardized effect is 0, and the corresponding Bayes factor for ##' the compliment of the interval. ##' ##' If \code{posterior} is \code{TRUE}, an object of class \code{BFmcmc}, ##' containing MCMC samples from the posterior is returned. ##' @export ##' @keywords htest ##' @author Richard D. Morey (\email{richarddmorey@@gmail.com}) ##' @references Morey, R. D., Rouder, J. N., Pratte, M. S., & Speckman, P. L. ##' (2011). Using MCMC chain outputs to efficiently estimate Bayes factors. ##' Journal of Mathematical Psychology, 55, 368-378 ##' ##' Morey, R. D. & Rouder, J. N. (2011). Bayes Factor Approaches for Testing ##' Interval Null Hypotheses. Psychological Methods, 16, 406-419 ##' ##' Rouder, J. N., Speckman, P. L., Sun, D., Morey, R. D., & Iverson, G. ##' (2009). Bayesian t-tests for accepting and rejecting the null hypothesis. ##' Psychonomic Bulletin & Review, 16, 225-237 ##' ##' @note The default priors have changed from 1 to \eqn{\sqrt{2}/2}. The ##' factor of \eqn{\sqrt{2}} is to be consistent ##' with Morey et al. (2011) and ##' Rouder et al. (2012), and the factor of \eqn{1/2} in both is to better scale the ##' expected effect sizes; the previous scaling put more weight on larger ##' effect sizes. To obtain the same Bayes factors as Rouder et al. (2009), ##' change the prior scale to 1. ##' @examples ##' ## Sleep data from t test example ##' data(sleep) ##' plot(extra ~ group, data = sleep) ##' ##' ## paired t test ##' ttestBF(x = sleep$extra[sleep$group==1], y = sleep$extra[sleep$group==2], paired=TRUE) ##' ##' ## Sample from the corresponding posterior distribution ##' samples = ttestBF(x = sleep$extra[sleep$group==1], ##' y = sleep$extra[sleep$group==2], paired=TRUE, ##' posterior = TRUE, iterations = 1000) ##' plot(samples[,"mu"]) ##' @seealso \code{\link{integrate}}, \code{\link{t.test}} ttestBF <- function(x = NULL, y = NULL, formula = NULL, mu = 0, nullInterval = NULL, paired = FALSE, data = NULL, rscale="medium", posterior=FALSE, callback = function(...) as.integer(0), ...){ data <- marshallTibble(data) if(!is.null(x) & !is.null(formula)) stop("Only one of x or formula should be defined.") if(!is.null(x) | !is.null(y)) if(any(is.na(c(x,y))) | any(is.infinite(c(x,y)))) stop("x or y must not contain missing or infinite values.") if(!is.null(nullInterval)){ nullInterval = range(nullInterval) if(identical(nullInterval,c(-Inf,Inf))){ nullInterval = NULL } } checkCallback(callback,as.integer(0)) if( (is.null(formula) & is.null(y)) | (!is.null(y) & paired) ){ # one sample if(paired){ # check that the two vectors have same length if(length(x)!=length(y)) stop("Length of x and y must be the same if paired=TRUE.") x = x - y } return( ttestBF_oneSample(x = x, mu = mu, nullInterval = nullInterval, rscale = rscale, posterior = posterior, callback = callback, ... ) ) } if(!is.null(y) & !paired){ # Two-sample; create formula if(!is.null(data) | !is.null(formula)) stop("Do not specify formula or data if x and y are specified.") data = data.frame(y = c(x,y), group = factor(c(rep("x",length(x)),rep("y",length(y)))) ) formula = y ~ group } if(!is.null(formula)){ # Two-sample if(paired) stop("Cannot use 'paired' with formula.") if(is.null(data)) stop("'data' needed for formula.") if(mu != 0) stop("Use of nonzero null hypothesis not implemented for independent samples test.") return(ttestBF_indepSample(formula = formula, data = data, mu = mu, nullInterval = nullInterval, rscale = rscale, posterior = posterior, callback = callback, ... )) }else{ stop("Insufficient arguments to perform t test.") } }
/scratch/gouwar.j/cran-all/cranData/BayesFactor/R/ttestBF.R
##' Using the classical t test statistic for a one- or two-sample design, this ##' function computes the corresponding Bayes factor test. ##' ##' This function can be used to compute the Bayes factor corresponding to a ##' one-sample, a paired-sample, or an independent-groups t test, using the ##' classical t statistic. It can be used when you don't have access to the ##' full data set for analysis by \code{\link{ttestBF}}, but you do have the ##' test statistic. ##' ##' For details about the model, see the help for \code{\link{ttestBF}}, and the ##' references therein. ##' ##' The Bayes factor is computed via Gaussian quadrature. ##' @title Use t statistic to compute Bayes factor for one- and two- sample designs ##' @param t classical t statistic ##' @param n1 size of first group (or only group, for one-sample tests) ##' @param n2 size of second group, for independent-groups tests ##' @param nullInterval optional vector of length 2 containing lower and upper bounds of an interval hypothesis to test, in standardized units ##' @param rscale numeric prior scale ##' @param complement if \code{TRUE}, compute the Bayes factor against the complement of the interval ##' @param simple if \code{TRUE}, return only the Bayes factor ##' @return If \code{simple} is \code{TRUE}, returns the Bayes factor (against the ##' null). If \code{FALSE}, the function returns a ##' vector of length 3 containing the computed log(e) Bayes factor, ##' along with a proportional error estimate on the Bayes factor and the method used to compute it. ##' @author Richard D. Morey (\email{richarddmorey@@gmail.com}) and Jeffrey N. ##' Rouder (\email{rouderj@@missouri.edu}) ##' @keywords htest ##' @export ##' @references Morey, R. D. & Rouder, J. N. (2011). Bayes Factor Approaches for ##' Testing Interval Null Hypotheses. Psychological Methods, 16, 406-419 ##' ##' Rouder, J. N., Speckman, P. L., Sun, D., Morey, R. D., & Iverson, G. ##' (2009). Bayesian t-tests for accepting and rejecting the null hypothesis. ##' Psychonomic Bulletin & Review, 16, 225-237 ##' @note In version 0.9.9, the behaviour of this function has changed in order to produce more uniform results. In ##' version 0.9.8 and before, this function returned two Bayes factors when \code{nullInterval} was ##' non-\code{NULL}: the Bayes factor for the interval versus the null, and the Bayes factor for the complement of ##' the interval versus the null. Starting in version 0.9.9, in order to get the Bayes factor for the complement, it is required to ##' set the \code{complement} argument to \code{TRUE}, and the function only returns one Bayes factor. ##' @seealso \code{\link{integrate}}, \code{\link{t.test}}; see ##' \code{\link{ttestBF}} for the intended interface to this function, using ##' the full data set. ##' @examples ##' ## Classical example: Student's sleep data ##' data(sleep) ##' plot(extra ~ group, data = sleep) ##' ##' ## t.test() gives a t value of -4.0621 ##' t.test(sleep$extra[1:10], sleep$extra[11:20], paired=TRUE) ##' ## Gives a Bayes factor of about 15 ##' ## in favor of the alternative hypothesis ##' result <- ttest.tstat(t = -4.0621, n1 = 10) ##' exp(result[['bf']]) ttest.tstat=function(t,n1,n2=0,nullInterval=NULL,rscale="medium", complement=FALSE, simple = FALSE) { if(n2){ rscale = rpriorValues("ttestTwo",,rscale) }else{ rscale = rpriorValues("ttestOne",,rscale) } stopifnot(length(t)==1 & length(n1)==1) nu=ifelse(n2==0 | is.null(n2),n1-1,n1+n2-2) n=ifelse(n2==0 | is.null(n2), n1, exp(log(n1)+log(n2)-log(n1+n2)) ) if( (n < 1) | (nu < 1)) stop("not enough observations") if(is.infinite(t)) stop("data are essentially constant") r2=rscale^2 log.marg.like.0= -(nu+1)/2 * log(1+t^2/(nu)) res = list(bf=NA, properror=NA,method=NA) if(is.null(nullInterval)){ BFtry({res = meta.t.bf(t,n,nu,rscale=rscale)}) }else{ BFtry({res = meta.t.bf(t,n,nu,interval=nullInterval,rscale=rscale,complement = complement)}) } if(simple){ return(c(B10=exp(res$bf))) }else{ return(res) } }
/scratch/gouwar.j/cran-all/cranData/BayesFactor/R/ttest_tstat.R
#'Prints the version information for the BayesFactor package #' #'Prints the version, revision, and date information for the BayesFactor package #' #'This function prints the version and revision information for the BayesFactor #'package. #' #'@param print if \code{TRUE}, print version information to the console #'@return \code{BFInfo} returns a character string containing the version and #' revision number of the package.. #'@author Richard D. Morey (\email{richarddmorey@@gmail.com}) #'@keywords misc #'@export BFInfo <- function(print=TRUE) { if(print){ cat("Package BayesFactor\n") cat(packageDescription("BayesFactor")$Version,"\n") } retStr = paste(packageDescription("BayesFactor")$Version) invisible(retStr) }
/scratch/gouwar.j/cran-all/cranData/BayesFactor/R/version.R
## ----echo=FALSE,message=FALSE,results='hide'---------------------------------- library(BayesFactor) options(BFprogress = FALSE) bfversion = BFInfo() session = sessionInfo()[[1]] rversion = paste(session$version.string," on ",session$platform,sep="") options(markdown.HTML.stylesheet = 'extra/manual.css') library(knitr) opts_chunk$set(dpi = 200, out.width = "67%") options(digits=3) require(graphics) set.seed(2) ## ----message=FALSE,warning=FALSE---------------------------------------------- library(arm) library(lme4) ## ----------------------------------------------------------------------------- # Number of participants N <- 20 sig2 <- 1 sig2ID <- 1 # 3x3x3 design, with participant as random factor effects <- expand.grid(A = c("A1","A2","A3"), B = c("B1","B2","B3"), C = c("C1","C2","C3"), ID = paste("Sub",1:N,sep="") ) Xdata <- model.matrix(~ A*B*C + ID, data=effects) beta <- matrix(c(50, -.2,.2, 0,0, .1,-.1, rnorm(N-1,0,sqrt(sig2ID)), 0,0,0,0, -.1,.1,.1,-.1, 0,0,0,0, 0,0,0,0,0,0,0,0), ncol=1) effects$y = rnorm(Xdata%*%beta,Xdata%*%beta,sqrt(sig2)) ## ----------------------------------------------------------------------------- # Typical repeated measures ANOVA summary(fullaov <- aov(y ~ A*B*C + Error(ID/(A*B*C)),data=effects)) ## ----fig.width=10,fig.height=4------------------------------------------------ mns <- tapply(effects$y,list(effects$A,effects$B,effects$C),mean) stderr = sqrt((sum(resid(fullaov[[3]])^2)/fullaov[[3]]$df.resid)/N) par(mfrow=c(1,3),cex=1.1) for(i in 1:3){ matplot(mns[,,i],xaxt='n',typ='b',xlab="A",main=paste("C",i), ylim=range(mns)+c(-1,1)*stderr,ylab="y") axis(1,at=1:3,lab=1:3) segments(1:3 + mns[,,i]*0,mns[,,i] + stderr,1:3 + mns[,,i]*0,mns[,,i] - stderr,col=rgb(0,0,0,.3)) } ## ----------------------------------------------------------------------------- t.is = system.time(bfs.is <- anovaBF(y ~ A*B*C + ID, data = effects, whichRandom="ID") ) t.la = system.time(bfs.la <- anovaBF(y ~ A*B*C + ID, data = effects, whichRandom="ID", method = "laplace") ) ## ----fig.width=6,fig.height=6------------------------------------------------- t.is t.la plot(log(extractBF(sort(bfs.is))$bf),log(extractBF(sort(bfs.la))$bf), xlab="Default Sampler",ylab="Laplace approximation", pch=21,bg=rgb(0,0,1,.2),col="black",asp=TRUE,cex=1.2) abline(0,1) bfs.is ## ----message=FALSE------------------------------------------------------------ chains <- lmBF(y ~ A + B + C + ID, data=effects, whichRandom = "ID", posterior=TRUE, iterations=10000) lmerObj <- lmer(y ~ A + B + C + (1|ID), data=effects) # Use arm function sim() to sample from posterior chainsLmer = sim(lmerObj,n.sims=10000) ## ----------------------------------------------------------------------------- BF.sig2 <- chains[,colnames(chains)=="sig2"] AG.sig2 <- (chainsLmer@sigma)^2 qqplot(log(BF.sig2),log(AG.sig2),pch=21,bg=rgb(0,0,1,.2), col=NULL,asp=TRUE,cex=1,xlab="BayesFactor samples", ylab="arm samples",main="Posterior samples of\nerror variance") abline(0,1) ## ----------------------------------------------------------------------------- AG.raneff <- chainsLmer@ranef$ID[,,1] BF.raneff <- chains[,grep('ID-',colnames(chains),fixed='TRUE')] plot(colMeans(BF.raneff),colMeans(AG.raneff),pch=21,bg=rgb(0,0,1,.2),col="black",asp=TRUE,cex=1.2,xlab="BayesFactor estimate",ylab="arm estimate",main="Random effect posterior means") abline(0,1) ## ----tidy=FALSE--------------------------------------------------------------- AG.fixeff <- chainsLmer@fixef BF.fixeff <- chains[,1:10] # Adjust AG results from reference cell to sum to 0 Z = c(1, 1/3, 1/3, 1/3, 1/3, 1/3, 1/3, 0, -1/3, -1/3, 0, 0, 0, 0, 0, 2/3, -1/3, 0, 0, 0, 0, 0, -1/3, 2/3, 0, 0, 0, 0, 0, 0, 0, -1/3, -1/3, 0, 0, 0, 0, 0, 2/3, -1/3, 0, 0, 0, 0, 0, -1/3, 2/3, 0, 0, 0, 0, 0, 0, 0, -1/3, -1/3, 0, 0, 0, 0, 0, 2/3, -1/3, 0, 0, 0, 0, 0, -1/3, 2/3) dim(Z) = c(7,10) Z = t(Z) AG.fixeff2 = t(Z%*%t(AG.fixeff)) ## Our grand mean has heavier tails qqplot(BF.fixeff[,1],AG.fixeff2[,1],pch=21,bg=rgb(0,0,1,.2),col=NULL,asp=TRUE,cex=1,xlab="BayesFactor estimate",ylab="arm estimate",main="Grand mean posterior samples") abline(0,1) plot(colMeans(BF.fixeff[,-1]),colMeans(AG.fixeff2[,-1]),pch=21,bg=rgb(0,0,1,.2),col="black",asp=TRUE,cex=1.2,xlab="BayesFactor estimate",ylab="arm estimate",main="Fixed effect posterior means") abline(0,1) ## Compare posterior standard deviations BFsd = apply(BF.fixeff[,-1],2,sd) AGsd = apply(AG.fixeff2[,-1],2,sd) plot(sort(AGsd/BFsd),pch=21,bg=rgb(0,0,1,.2),col="black",cex=1.2,ylab="Ratio of posterior standard deviations (arm/BF)",xlab="Fixed effect index") ## AG estimates are slightly larger, consistent with sig2 estimates ## probably due to prior ## ----message=FALSE,warning=FALSE---------------------------------------------- library(languageR) library(xtable) ## ----------------------------------------------------------------------------- data(primingHeidPrevRT) primingHeidPrevRT$lRTmin1 <- log(primingHeidPrevRT$RTmin1) ###Frequentist lr4 <- lmer(RT ~ Condition + (1|Word)+ (1|Subject) + lRTmin1 + RTtoPrime + ResponseToPrime + ResponseToPrime*RTtoPrime +BaseFrequency ,primingHeidPrevRT) # Get rid rid of some outlying response times INDOL <- which(scale(resid(lr4)) < 2.5) primHeidOL <- primingHeidPrevRT[INDOL,] ## ----------------------------------------------------------------------------- # Center continuous variables primHeidOL$BaseFrequency <- primHeidOL$BaseFrequency - mean(primHeidOL$BaseFrequency) primHeidOL$lRTmin1 <- primHeidOL$lRTmin1 - mean(primHeidOL$lRTmin1) primHeidOL$RTtoPrime <- primHeidOL$RTtoPrime - mean(primHeidOL$RTtoPrime) ## ----------------------------------------------------------------------------- # LMER lr4b <- lmer( RT ~ Condition + ResponseToPrime + (1|Word)+ (1|Subject) + lRTmin1 + RTtoPrime + ResponseToPrime*RTtoPrime + BaseFrequency , primHeidOL) # BayesFactor B5out <- lmBF( RT ~ Condition + ResponseToPrime + Word + Subject + lRTmin1 + RTtoPrime + ResponseToPrime*RTtoPrime + BaseFrequency , primHeidOL , whichRandom = c("Word", "Subject"), posterior = TRUE, iteration = 50000,columnFilter=c("Word","Subject")) lmerEff <- fixef(lr4b) bfEff <- colMeans(B5out[,1:10]) ## ----results='asis'----------------------------------------------------------- print(xtable(cbind("lmer fixed effects"=names(lmerEff))), type='html') ## ----tidy=FALSE--------------------------------------------------------------- # Adjust lmer results from reference cell to sum to 0 Z = c(1, 1/2, 1/2, 0, 0, 0, 0, 0, -1/2, 0, 0, 0, 0, 0, 0, 1/2, 0, 0, 0, 0, 0, 0, 0,-1/2, 0, 0, 0, 0, 0, 0, 1/2, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1/2, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, -1/2, 0, 0, 0, 0, 0, 0, 1/2) dim(Z) = c(7,10) Z = t(Z) # Do reparameterization by pre-multimplying the parameter vector by Z reparLmer <- Z %*% matrix(lmerEff,ncol=1) # put results in data.frame for comparison sideBySide <- data.frame(BayesFactor=bfEff,lmer=reparLmer) ## ----results='asis'----------------------------------------------------------- print(xtable(sideBySide,digits=4), type='html') ## ----------------------------------------------------------------------------- # Notice Bayesian shrinkage par(cex=1.5) plot(sideBySide[-1,],pch=21,bg=rgb(0,0,1,.2),col="black",asp=TRUE,cex=1.2, main="fixed effects\n (excluding grand mean)") abline(0,1, lty=2)
/scratch/gouwar.j/cran-all/cranData/BayesFactor/inst/doc/compare_lme4.R
<!-- %\VignetteEngine{knitr::knitr} %\VignetteIndexEntry{Demos and comparisons} \usepackage[utf8]{inputenc} --> ![alt text](extra/logo.png) ------ ```{r echo=FALSE,message=FALSE,results='hide'} library(BayesFactor) options(BFprogress = FALSE) bfversion = BFInfo() session = sessionInfo()[[1]] rversion = paste(session$version.string," on ",session$platform,sep="") options(markdown.HTML.stylesheet = 'extra/manual.css') library(knitr) opts_chunk$set(dpi = 200, out.width = "67%") options(digits=3) require(graphics) set.seed(2) ``` Comparison of BayesFactor against other packages ======================================================== This R markdown file runs a series of tests to ensure that the BayesFactor package is giving correct answers, and can gracefully handle probable input. ```{r message=FALSE,warning=FALSE} library(arm) library(lme4) ``` ANOVA ---------- First we generate some data. ```{r} # Number of participants N <- 20 sig2 <- 1 sig2ID <- 1 # 3x3x3 design, with participant as random factor effects <- expand.grid(A = c("A1","A2","A3"), B = c("B1","B2","B3"), C = c("C1","C2","C3"), ID = paste("Sub",1:N,sep="") ) Xdata <- model.matrix(~ A*B*C + ID, data=effects) beta <- matrix(c(50, -.2,.2, 0,0, .1,-.1, rnorm(N-1,0,sqrt(sig2ID)), 0,0,0,0, -.1,.1,.1,-.1, 0,0,0,0, 0,0,0,0,0,0,0,0), ncol=1) effects$y = rnorm(Xdata%*%beta,Xdata%*%beta,sqrt(sig2)) ``` ```{r} # Typical repeated measures ANOVA summary(fullaov <- aov(y ~ A*B*C + Error(ID/(A*B*C)),data=effects)) ``` We can plot the data with standard errors: ```{r fig.width=10,fig.height=4} mns <- tapply(effects$y,list(effects$A,effects$B,effects$C),mean) stderr = sqrt((sum(resid(fullaov[[3]])^2)/fullaov[[3]]$df.resid)/N) par(mfrow=c(1,3),cex=1.1) for(i in 1:3){ matplot(mns[,,i],xaxt='n',typ='b',xlab="A",main=paste("C",i), ylim=range(mns)+c(-1,1)*stderr,ylab="y") axis(1,at=1:3,lab=1:3) segments(1:3 + mns[,,i]*0,mns[,,i] + stderr,1:3 + mns[,,i]*0,mns[,,i] - stderr,col=rgb(0,0,0,.3)) } ``` ### Bayes factor Compute the Bayes factors, while testing the Laplace approximation ```{r} t.is = system.time(bfs.is <- anovaBF(y ~ A*B*C + ID, data = effects, whichRandom="ID") ) t.la = system.time(bfs.la <- anovaBF(y ~ A*B*C + ID, data = effects, whichRandom="ID", method = "laplace") ) ``` ```{r fig.width=6,fig.height=6} t.is t.la plot(log(extractBF(sort(bfs.is))$bf),log(extractBF(sort(bfs.la))$bf), xlab="Default Sampler",ylab="Laplace approximation", pch=21,bg=rgb(0,0,1,.2),col="black",asp=TRUE,cex=1.2) abline(0,1) bfs.is ``` Comparison to lmer and arm ------ We can use samples from the posterior distribution to compare `BayesFactor` with `lmer` and `arm`. ```{r message=FALSE} chains <- lmBF(y ~ A + B + C + ID, data=effects, whichRandom = "ID", posterior=TRUE, iterations=10000) lmerObj <- lmer(y ~ A + B + C + (1|ID), data=effects) # Use arm function sim() to sample from posterior chainsLmer = sim(lmerObj,n.sims=10000) ``` Compare estimates of variance ```{r} BF.sig2 <- chains[,colnames(chains)=="sig2"] AG.sig2 <- (chainsLmer@sigma)^2 qqplot(log(BF.sig2),log(AG.sig2),pch=21,bg=rgb(0,0,1,.2), col=NULL,asp=TRUE,cex=1,xlab="BayesFactor samples", ylab="arm samples",main="Posterior samples of\nerror variance") abline(0,1) ``` Compare estimates of participant effects: ```{r} AG.raneff <- chainsLmer@ranef$ID[,,1] BF.raneff <- chains[,grep('ID-',colnames(chains),fixed='TRUE')] plot(colMeans(BF.raneff),colMeans(AG.raneff),pch=21,bg=rgb(0,0,1,.2),col="black",asp=TRUE,cex=1.2,xlab="BayesFactor estimate",ylab="arm estimate",main="Random effect posterior means") abline(0,1) ``` Compare estimates of fixed effects: ```{r tidy=FALSE} AG.fixeff <- chainsLmer@fixef BF.fixeff <- chains[,1:10] # Adjust AG results from reference cell to sum to 0 Z = c(1, 1/3, 1/3, 1/3, 1/3, 1/3, 1/3, 0, -1/3, -1/3, 0, 0, 0, 0, 0, 2/3, -1/3, 0, 0, 0, 0, 0, -1/3, 2/3, 0, 0, 0, 0, 0, 0, 0, -1/3, -1/3, 0, 0, 0, 0, 0, 2/3, -1/3, 0, 0, 0, 0, 0, -1/3, 2/3, 0, 0, 0, 0, 0, 0, 0, -1/3, -1/3, 0, 0, 0, 0, 0, 2/3, -1/3, 0, 0, 0, 0, 0, -1/3, 2/3) dim(Z) = c(7,10) Z = t(Z) AG.fixeff2 = t(Z%*%t(AG.fixeff)) ## Our grand mean has heavier tails qqplot(BF.fixeff[,1],AG.fixeff2[,1],pch=21,bg=rgb(0,0,1,.2),col=NULL,asp=TRUE,cex=1,xlab="BayesFactor estimate",ylab="arm estimate",main="Grand mean posterior samples") abline(0,1) plot(colMeans(BF.fixeff[,-1]),colMeans(AG.fixeff2[,-1]),pch=21,bg=rgb(0,0,1,.2),col="black",asp=TRUE,cex=1.2,xlab="BayesFactor estimate",ylab="arm estimate",main="Fixed effect posterior means") abline(0,1) ## Compare posterior standard deviations BFsd = apply(BF.fixeff[,-1],2,sd) AGsd = apply(AG.fixeff2[,-1],2,sd) plot(sort(AGsd/BFsd),pch=21,bg=rgb(0,0,1,.2),col="black",cex=1.2,ylab="Ratio of posterior standard deviations (arm/BF)",xlab="Fixed effect index") ## AG estimates are slightly larger, consistent with sig2 estimates ## probably due to prior ``` Another comparison with lmer ----------- We begin by loading required packages... ```{r message=FALSE,warning=FALSE} library(languageR) library(xtable) ``` ...and creating the data set to analyze. ```{r} data(primingHeidPrevRT) primingHeidPrevRT$lRTmin1 <- log(primingHeidPrevRT$RTmin1) ###Frequentist lr4 <- lmer(RT ~ Condition + (1|Word)+ (1|Subject) + lRTmin1 + RTtoPrime + ResponseToPrime + ResponseToPrime*RTtoPrime +BaseFrequency ,primingHeidPrevRT) # Get rid rid of some outlying response times INDOL <- which(scale(resid(lr4)) < 2.5) primHeidOL <- primingHeidPrevRT[INDOL,] ``` The first thing we have to do is center the continuous variables. This is done automatically by lmBF(), as required by Liang et al. (2008). This, of course, changes the definition of the intercept. ```{r} # Center continuous variables primHeidOL$BaseFrequency <- primHeidOL$BaseFrequency - mean(primHeidOL$BaseFrequency) primHeidOL$lRTmin1 <- primHeidOL$lRTmin1 - mean(primHeidOL$lRTmin1) primHeidOL$RTtoPrime <- primHeidOL$RTtoPrime - mean(primHeidOL$RTtoPrime) ``` Now we perform both analyses on the same data, and place the fixed effect estimates for both packages into their own vectors. ```{r} # LMER lr4b <- lmer( RT ~ Condition + ResponseToPrime + (1|Word)+ (1|Subject) + lRTmin1 + RTtoPrime + ResponseToPrime*RTtoPrime + BaseFrequency , primHeidOL) # BayesFactor B5out <- lmBF( RT ~ Condition + ResponseToPrime + Word + Subject + lRTmin1 + RTtoPrime + ResponseToPrime*RTtoPrime + BaseFrequency , primHeidOL , whichRandom = c("Word", "Subject"), posterior = TRUE, iteration = 50000,columnFilter=c("Word","Subject")) lmerEff <- fixef(lr4b) bfEff <- colMeans(B5out[,1:10]) ``` `lmer` uses a "reference cell" parameterization, rather than imposing sum-to-0 constraints. We can tell what the reference cell is by looking at the parameter names. ```{r results='asis'} print(xtable(cbind("lmer fixed effects"=names(lmerEff))), type='html') ``` Notice what's missing: for the categorical parameters, we are missing `Conditionbaseheid` and `ResponseToPrimecorrect`. For the slope parameters, we are missing `ResponseToPrimecorrect:RTtoPrime`. The missing effects tell us what the reference cells are. Since the reference cell parameterization is just a linear transformation of the sum-to-0 parameterization, we can create a matrix that allows us to move from one to the other. We call this $10 \times 7$ matrix `Z`. It takes the 7 "reference-cell" parameters from `lmer` and maps them into the 10 linearly constrained parameters from `lmBF`. The first row of `Z` transforms the intercept (reference cell) to the grand mean (sum-to-0). We have to add half of the two fixed effects back into the intercept. The second and third row divide the totl effect of `Condition` into two equal parts, one for `baseheid` and one for `heid`. Rows four and five do the same for `ResponseToPrime`. The slopes that do not enter into interactions are fine as they are; however, `ResponseToPrimecorrect:RTtoPrime` serves as our reference cell for the `ResponseToPrime:RTtoPrime` interaction. We treat these slopes analogously to the grand mean; we take `RTtoPrime` and add half the `ResponseToPrimeincorrect:RTtoPrime` effect to it, to make it a grand mean slope. The last two rows divide up the `ResponseToPrimeincorrect:RTtoPrime` effect between `ResponseToPrimeincorrect:RTtoPrime` and `ResponseToPrimecorrect:RTtoPrime`. ```{r tidy=FALSE} # Adjust lmer results from reference cell to sum to 0 Z = c(1, 1/2, 1/2, 0, 0, 0, 0, 0, -1/2, 0, 0, 0, 0, 0, 0, 1/2, 0, 0, 0, 0, 0, 0, 0,-1/2, 0, 0, 0, 0, 0, 0, 1/2, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1/2, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, -1/2, 0, 0, 0, 0, 0, 0, 1/2) dim(Z) = c(7,10) Z = t(Z) # Do reparameterization by pre-multimplying the parameter vector by Z reparLmer <- Z %*% matrix(lmerEff,ncol=1) # put results in data.frame for comparison sideBySide <- data.frame(BayesFactor=bfEff,lmer=reparLmer) ``` We can look at them side by side for comparison: ```{r results='asis'} print(xtable(sideBySide,digits=4), type='html') ``` ...and plot them: ```{r} # Notice Bayesian shrinkage par(cex=1.5) plot(sideBySide[-1,],pch=21,bg=rgb(0,0,1,.2),col="black",asp=TRUE,cex=1.2, main="fixed effects\n (excluding grand mean)") abline(0,1, lty=2) ``` The results are quite close to one another, with a bit of Bayesian shrinkage. ------- *This document was compiled with version `r bfversion` of BayesFactor (`r rversion`).*
/scratch/gouwar.j/cran-all/cranData/BayesFactor/inst/doc/compare_lme4.Rmd
## ----echo=FALSE,message=FALSE,results='hide'---------------------------------- options(markdown.HTML.stylesheet = 'extra/manual.css') library(knitr)
/scratch/gouwar.j/cran-all/cranData/BayesFactor/inst/doc/index.R
<!-- %\VignetteEngine{knitr::knitr} %\VignetteIndexEntry{Vignette menu} \usepackage[utf8]{inputenc} --> ![alt text](extra/logo.png) ------ BayesFactor manual files ------ ```{r echo=FALSE,message=FALSE,results='hide'} options(markdown.HTML.stylesheet = 'extra/manual.css') library(knitr) ``` * [Main manual](manual.html) * [Posterior odds and probabilities](odds_probs.html) * [Prior checks](priors.html) * [Comparison to arm/lmer](compare_lme4.html)
/scratch/gouwar.j/cran-all/cranData/BayesFactor/inst/doc/index.Rmd
## ----echo=FALSE,message=FALSE,results='hide'---------------------------------- options(markdown.HTML.stylesheet = 'extra/manual.css') library(knitr) opts_chunk$set(dpi = 200, out.width = "67%") options(digits=3) require(graphics) set.seed(2) ## ----message=FALSE------------------------------------------------------------ library(BayesFactor) ## ----echo=FALSE,message=FALSE,results='hide'---------------------------------- options(BFprogress = FALSE) bfversion = BFInfo() session = sessionInfo()[[1]] rversion = paste(session$version.string," on ",session$platform,sep="") ## ----onesampdata-------------------------------------------------------------- data(sleep) ## Compute difference scores diffScores = sleep$extra[1:10] - sleep$extra[11:20] ## Traditional two-tailed t test t.test(diffScores) ## ----onesampt----------------------------------------------------------------- bf = ttestBF(x = diffScores) ## Equivalently: ## bf = ttestBF(x = sleep$extra[1:10],y=sleep$extra[11:20], paired=TRUE) bf ## ----recip-------------------------------------------------------------------- 1 / bf ## ----tsamp-------------------------------------------------------------------- chains = posterior(bf, iterations = 1000) summary(chains) ## ----tsamplplot,fig.width=10,fig.cap=''--------------------------------------- chains2 = recompute(chains, iterations = 10000) plot(chains2[,1:2]) ## ----onesamptinterval--------------------------------------------------------- bfInterval = ttestBF(x = diffScores, nullInterval=c(-Inf,0)) bfInterval ## ----onesampledivide---------------------------------------------------------- bfInterval[1] / bfInterval[2] ## ----onesampcat--------------------------------------------------------------- allbf = c(bf, bfInterval) allbf ## ----plotonesamp,fig.width=10,fig.height=5,fig.cap=''------------------------- plot(allbf) ## ----onesamplist-------------------------------------------------------------- bfmat = allbf / allbf bfmat ## ----onesamplist2------------------------------------------------------------- bfmat[,2] bfmat[1,] ## ----onesamplist3------------------------------------------------------------- bfmat[,1:2] t(bfmat[,1:2]) ## ----twosampledata------------------------------------------------------------ data(chickwts) ## Restrict to two groups chickwts = chickwts[chickwts$feed %in% c("horsebean","linseed"),] ## Drop unused factor levels chickwts$feed = factor(chickwts$feed) ## Plot data plot(weight ~ feed, data = chickwts, main = "Chick weights") ## ----------------------------------------------------------------------------- ## traditional t test t.test(weight ~ feed, data = chickwts, var.eq=TRUE) ## ----twosamplet--------------------------------------------------------------- ## Compute Bayes factor bf = ttestBF(formula = weight ~ feed, data = chickwts) bf ## ----twosampletsamp,fig.width=10,fig.cap=''----------------------------------- chains = posterior(bf, iterations = 10000) plot(chains[,2]) ## ----bemdata------------------------------------------------------------------ ## Bem's t statistics from four selected experiments t = c(-.15, 2.39, 2.42, 2.43) N = c(100, 150, 97, 99) ## ----bemanalysis1------------------------------------------------------------- bf = meta.ttestBF(t=t, n1=N, nullInterval=c(0,Inf), rscale=1) bf ## ----bemposterior,fig.width=10,fig.cap=''------------------------------------- ## Do analysis again, without nullInterval restriction bf = meta.ttestBF(t=t, n1=N, rscale=1) ## Obtain posterior samples chains = posterior(bf, iterations = 10000) plot(chains) ## ----fixeddata,fig.width=10,fig.height=5,fig.cap=''--------------------------- data(ToothGrowth) ## Example plot from ?ToothGrowth coplot(len ~ dose | supp, data = ToothGrowth, panel = panel.smooth, xlab = "ToothGrowth data: length vs dose, given type of supplement") ## Treat dose as a factor ToothGrowth$dose = factor(ToothGrowth$dose) levels(ToothGrowth$dose) = c("Low", "Medium", "High") summary(aov(len ~ supp*dose, data=ToothGrowth)) ## ----------------------------------------------------------------------------- bf = anovaBF(len ~ supp*dose, data=ToothGrowth) bf ## ----fixedbf,fig.width=10,fig.height=5,fig.cap=''----------------------------- plot(bf[3:4] / bf[2]) ## ----------------------------------------------------------------------------- bf = anovaBF(len ~ supp*dose, data=ToothGrowth, whichModels="top") bf ## ----------------------------------------------------------------------------- bfMainEffects = lmBF(len ~ supp + dose, data = ToothGrowth) bfInteraction = lmBF(len ~ supp + dose + supp:dose, data = ToothGrowth) ## Compare the two models bf = bfInteraction / bfMainEffects bf ## ----------------------------------------------------------------------------- newbf = recompute(bf, iterations = 500000) newbf ## ----------------------------------------------------------------------------- ## Sample from the posterior of the full model chains = posterior(bfInteraction, iterations = 10000) ## 1:13 are the only "interesting" parameters summary(chains[,1:13]) ## ----------------------------------------------------------------------------- plot(chains[,4:6]) ## ----------------------------------------------------------------------------- data(puzzles) ## ----puzzlesplot,fig.width=7,fig.height=5,echo=FALSE,fig.cap=''--------------- ## plot the data aovObj = aov(RT ~ shape*color + Error(ID/(shape*color)), data=puzzles) matplot(t(matrix(puzzles$RT,12,4)),ty='b',pch=19,lwd=1,lty=1,col=rgb(0,0,0,.2), ylab="Completion time", xlab="Condition",xaxt='n') axis(1,at=1:4,lab=c("round&mono","square&mono","round&color","square&color")) mns = tapply(puzzles$RT,list(puzzles$color,puzzles$shape),mean)[c(2,4,1,3)] points(1:4,mns,pch=22,col="red",bg=rgb(1,0,0,.6),cex=2) # within-subject standard error, uses MSE from ANOVA stderr = sqrt(sum(aovObj[[5]]$residuals^2)/11)/sqrt(12) segments(1:4,mns + stderr,1:4,mns - stderr,col="red") ## ----------------------------------------------------------------------------- summary(aov(RT ~ shape*color + Error(ID/(shape*color)), data=puzzles)) ## ----tidy=FALSE--------------------------------------------------------------- bf = anovaBF(RT ~ shape*color + ID, data = puzzles, whichRandom="ID") ## ----------------------------------------------------------------------------- bf ## ----testplot,fig.width=10,fig.height=5,fig.cap=''---------------------------- plot(bf) ## ----------------------------------------------------------------------------- bfWithoutID = lmBF(RT ~ shape*color, data = puzzles) bfWithoutID ## ----------------------------------------------------------------------------- bfOnlyID = lmBF(RT ~ ID, whichRandom="ID",data = puzzles) bf2 = bfWithoutID / bfOnlyID bf2 ## ----------------------------------------------------------------------------- bfall = c(bf,bf2) ## ----------------------------------------------------------------------------- bf[4] / bf2 ## ----regressData-------------------------------------------------------------- data(attitude) ## Traditional multiple regression analysis lmObj = lm(rating ~ ., data = attitude) summary(lmObj) ## ----regressAll--------------------------------------------------------------- bf = regressionBF(rating ~ ., data = attitude) length(bf) ## ----regressSelect------------------------------------------------------------ ## Choose a specific model bf["privileges + learning + raises + critical + advance"] ## Best 6 models head(bf, n=6) ## Worst 4 models tail(bf, n=4) ## ----regressSelectwhichmax,eval=FALSE----------------------------------------- # ## which model index is the best? # which.max(bf) ## ----regressSelectwhichmaxFake,echo=FALSE------------------------------------- ## which model index is the best? BayesFactor::which.max(bf) ## ----regressSelect2----------------------------------------------------------- ## Compare the 5 best models to the best bf2 = head(bf) / max(bf) bf2 plot(bf2) ## ----regresstop, fig.width=10, fig.height=5,fig.cap=''------------------------ bf = regressionBF(rating ~ ., data = attitude, whichModels = "top") ## The seventh model is the most complex bf plot(bf) ## ----regressbottom, fig.width=10, fig.height=5,fig.cap=''--------------------- bf = regressionBF(rating ~ ., data = attitude, whichModels = "bottom") plot(bf) ## ----lmregress1--------------------------------------------------------------- complaintsOnlyBf = lmBF(rating ~ complaints, data = attitude) complaintsLearningBf = lmBF(rating ~ complaints + learning, data = attitude) ## Compare the two models complaintsOnlyBf / complaintsLearningBf ## ----lmposterior-------------------------------------------------------------- chains = posterior(complaintsLearningBf, iterations = 10000) summary(chains) ## ----lmregressclassical------------------------------------------------------- summary(lm(rating ~ complaints + learning, data = attitude)) ## ----echo=FALSE,results='hide'------------------------------------------------ rm(ToothGrowth) ## ----GLMdata------------------------------------------------------------------ data(ToothGrowth) # model log2 of dose instead of dose directly ToothGrowth$dose = log2(ToothGrowth$dose) # Classical analysis for comparison lmToothGrowth <- lm(len ~ supp + dose + supp:dose, data=ToothGrowth) summary(lmToothGrowth) ## ----GLMs--------------------------------------------------------------------- full <- lmBF(len ~ supp + dose + supp:dose, data=ToothGrowth) noInteraction <- lmBF(len ~ supp + dose, data=ToothGrowth) onlyDose <- lmBF(len ~ dose, data=ToothGrowth) onlySupp <- lmBF(len ~ supp, data=ToothGrowth) allBFs <- c(full, noInteraction, onlyDose, onlySupp) allBFs ## ----GLMs2-------------------------------------------------------------------- full / noInteraction ## ----GLMposterior1------------------------------------------------------------ chainsFull <- posterior(full, iterations = 10000) # summary of the "interesting" parameters summary(chainsFull[,1:7]) ## ----GLMposterior2,results='hide',echo=FALSE---------------------------------- chainsNoInt <- posterior(noInteraction, iterations = 10000) ## ----GLMplot,echo=FALSE,fig.width=10, fig.height=5,fig.cap=''----------------- ToothGrowth$dose <- ToothGrowth$dose - mean(ToothGrowth$dose) cmeans <- colMeans(chainsFull)[1:6] ints <- cmeans[1] + c(-1, 1) * cmeans[2] slps <- cmeans[4] + c(-1, 1) * cmeans[5] par(cex=1.8, mfrow=c(1,2)) plot(len ~ dose, data=ToothGrowth, pch=as.integer(ToothGrowth$supp)+20, bg = rgb(as.integer(ToothGrowth$supp)-1,2-as.integer(ToothGrowth$supp),0,.5),col=NULL,xaxt="n",ylab="Tooth length",xlab="Vitamin C dose (mg)") abline(a=ints[1],b=slps[1],col=2) abline(a=ints[2],b=slps[2],col=3) axis(1,at=-1:1,lab=2^(-1:1)) dataVC <- ToothGrowth[ToothGrowth$supp=="VC",] dataOJ <- ToothGrowth[ToothGrowth$supp=="OJ",] lmVC <- lm(len ~ dose, data=dataVC) lmOJ <- lm(len ~ dose, data=dataOJ) abline(lmVC,col=2,lty=2) abline(lmOJ,col=3,lty=2) mtext("Interaction",3,.1,adj=1,cex=1.3) # Do single slope cmeans <- colMeans(chainsNoInt)[1:4] ints <- cmeans[1] + c(-1, 1) * cmeans[2] slps <- cmeans[4] plot(len ~ dose, data=ToothGrowth, pch=as.integer(ToothGrowth$supp)+20, bg = rgb(as.integer(ToothGrowth$supp)-1,2-as.integer(ToothGrowth$supp),0,.5),col=NULL,xaxt="n",ylab="Tooth length",xlab="Vitamin C dose (mg)") abline(a=ints[1],b=slps,col=2) abline(a=ints[2],b=slps,col=3) axis(1,at=-1:1,lab=2^(-1:1)) mtext("No interaction",3,.1,adj=1,cex=1.3) ## ----eval=FALSE--------------------------------------------------------------- # chainsNoInt <- posterior(noInteraction, iterations = 10000) # # # summary of the "interesting" parameters # summary(chainsNoInt[,1:5]) ## ----echo=FALSE--------------------------------------------------------------- summary(chainsNoInt[,1:5]) ## ----------------------------------------------------------------------------- ToothGrowth$doseAsFactor <- factor(ToothGrowth$dose) levels(ToothGrowth$doseAsFactor) <- c(.5,1,2) aovBFs <- anovaBF(len ~ doseAsFactor + supp + doseAsFactor:supp, data = ToothGrowth) ## ----------------------------------------------------------------------------- allBFs <- c(aovBFs, full, noInteraction, onlyDose) ## eliminate the supp-only model, since it performs so badly allBFs <- allBFs[-1] ## Compare to best model allBFs / max(allBFs) ## ----GLMplot2,echo=FALSE,fig.width=10, fig.height=5,fig.cap=''---------------- plot(allBFs / max(allBFs)) ## ----------------------------------------------------------------------------- plot(Sepal.Width ~ Sepal.Length, data = iris) abline(lm(Sepal.Width ~ Sepal.Length, data = iris), col = "red") ## ----------------------------------------------------------------------------- cor.test(y = iris$Sepal.Length, x = iris$Sepal.Width) ## ----------------------------------------------------------------------------- bf = correlationBF(y = iris$Sepal.Length, x = iris$Sepal.Width) bf ## ----------------------------------------------------------------------------- samples = posterior(bf, iterations = 10000) ## ----------------------------------------------------------------------------- summary(samples) ## ----------------------------------------------------------------------------- plot(samples[,"rho"]) ## ----propprior,echo=FALSE,fig.width=10, fig.height=5,fig.cap=''--------------- p0 = .5 rnames = c("medium","wide","ultrawide") r = sapply(rnames,function(rname) BayesFactor:::rpriorValues("proptest",,rname)) leg_names = paste(rnames," (r=",round(r,3), ")", sep="") omega = seq(-5,5,len=100) pp = dlogis(omega,qlogis(p0),r[1]) plot(omega,pp, col="black", typ = 'l', lty=1, lwd=2, ylab="Prior density", xlab=expression(paste("True log odds ", omega)), yaxt='n') pp = dlogis(omega,qlogis(p0),r[2]) lines(omega, pp, col = "red",lty=1, lwd=2) pp = dlogis(omega,qlogis(p0),r[3]) lines(omega, pp, col = "blue",lty=1,lwd=2) axis(3,at = -2:2 * 2, labels=round(plogis(-2:2*2),2)) mtext(expression(paste("True probability ", pi)),3,2,adj=.5) legend(-5,.5,legend = leg_names, col=c("black","red","blue"), lwd=2,lty=1) ## ----------------------------------------------------------------------------- bf = proportionBF( 682, 682 + 243, p = 3/4) 1 / bf ## ----------------------------------------------------------------------------- binom.test(682, 682 + 243, p = 3/4) ## ----proppost,fig.width=10, fig.height=5,fig.cap=''--------------------------- chains = posterior(bf, iterations = 10000) plot(chains[,"p"], main = "Posterior of true probability\nof 'giant' progeny") ## ----results='asis', echo=FALSE----------------------------------------------- data(raceDolls) kable(raceDolls) ## ----------------------------------------------------------------------------- bf = contingencyTableBF(raceDolls, sampleType = "indepMulti", fixedMargin = "cols") bf ## ----------------------------------------------------------------------------- chisq.test(raceDolls) ## ----------------------------------------------------------------------------- chains = posterior(bf, iterations = 10000) ## ----------------------------------------------------------------------------- sameRaceGivenWhite = chains[,"pi[1,1]"] / chains[,"pi[*,1]"] sameRaceGivenBlack = chains[,"pi[1,2]"] / chains[,"pi[*,2]"] ## ----ctablechains,fig.width=10, fig.height=5,fig.cap=''----------------------- plot(mcmc(sameRaceGivenWhite - sameRaceGivenBlack), main = "Increase in probability of child picking\nsame race doll (white - black)") ## ----------------------------------------------------------------------------- data(puzzles) puzzleGenBF <- generalTestBF(RT ~ shape + color + shape:color + ID, data=puzzles, whichRandom="ID") puzzleGenBF ## ----------------------------------------------------------------------------- puzzleGenBF <- generalTestBF(RT ~ shape + color + shape:color + ID, data=puzzles, whichRandom="ID", neverExclude="ID") puzzleGenBF ## ----------------------------------------------------------------------------- puzzleGenBF <- generalTestBF(RT ~ shape + color + shape:color + shape:ID + ID, data=puzzles, whichRandom="ID", neverExclude="ID") puzzleGenBF ## ----------------------------------------------------------------------------- puzzleGenBF <- generalTestBF(RT ~ shape + color + shape:color + shape:ID + ID, data=puzzles, whichRandom="ID", neverExclude="^ID$") puzzleGenBF ## ----------------------------------------------------------------------------- puzzleCullBF <- generalTestBF(RT ~ shape + color + shape:color + ID, data=puzzles, whichRandom="ID", noSample=TRUE,whichModels='all') puzzleCullBF ## ----------------------------------------------------------------------------- missing = puzzleCullBF[ is.na(puzzleCullBF) ] done = puzzleCullBF[ !is.na(puzzleCullBF) ] missing ## ----------------------------------------------------------------------------- # get the names of the numerator models missingModels = names(missing)$numerator # search them to see if they contain "shape" or "color" - # results are logical vectors containsShape = grepl("shape",missingModels) containsColor = grepl("color",missingModels) # anything that does not contain "shape" and "color" containsOnlyOne = !(containsShape & containsColor) # restrict missing to only those of interest missingOfInterest = missing[containsOnlyOne] missingOfInterest ## ----------------------------------------------------------------------------- # recompute the Bayes factors for the missing models of interest sampledBayesFactors = recompute(missingOfInterest) sampledBayesFactors # Add them together with our other Bayes factors, already computed: completeBayesFactors = c(done, sampledBayesFactors) completeBayesFactors ## ----------------------------------------------------------------------------- data(puzzles) # Get MCMC chains corresponding to "full" model # We prevent sampling so we can see the parameter names # iterations argument is necessary, but not used fullModel = lmBF(RT ~ shape + color + shape:color + ID, data = puzzles, noSample=TRUE, posterior = TRUE, iterations=3) fullModel ## ----------------------------------------------------------------------------- fullModelFiltered = lmBF(RT ~ shape + color + shape:color + ID, data = puzzles, noSample=TRUE, posterior = TRUE, iterations=3,columnFilter="ID") fullModelFiltered ## ----------------------------------------------------------------------------- # Sample 10000 iterations, eliminating ID columns chains = lmBF(RT ~ shape + color + shape:color + ID, data = puzzles, posterior = TRUE, iterations=10000,columnFilter="ID") ## ----acfplot,fig.width=10,fig.height=5,echo=FALSE,fig.cap=''------------------ par(mfrow=c(1,2)) plot(as.vector(chains[1:1000,"shape-round"]),type="l",xlab="Iterations",ylab="parameter shape-round") acf(chains[,"shape-round"]) ## ----------------------------------------------------------------------------- chainsThinned = recompute(chains, iterations=20000, thin=2) # check size of MCMC chain dim(chainsThinned) ## ----acfplot2,fig.width=10,fig.height=5,echo=FALSE,fig.cap=''----------------- par(mfrow=c(1,2)) plot(as.vector(chainsThinned[1:1000,"shape-round"]),type="l",xlab="Iterations",ylab="parameter shape-round") acf(chainsThinned[,"shape-round"]) ## ----tidy=FALSE--------------------------------------------------------------- newprior.bf = anovaBF(RT ~ shape + color + shape:color + ID, data = puzzles, whichRandom = "ID",rscaleEffects = c( color = 1 )) newprior.bf
/scratch/gouwar.j/cran-all/cranData/BayesFactor/inst/doc/manual.R
--- title: "Using the 'BayesFactor' package, version 0.9.2+" author: "Richard D. Morey" date: '`r format(Sys.time(), "%d %B, %Y")`' vignette: > %\VignetteEngine{knitr::rmarkdown} %\VignetteIndexEntry{User's manual} \usepackage[utf8]{inputenc} output: knitr:::html_vignette: toc: no --- <a target="_blank" href="https://github.com/richarddmorey/BayesFactor"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://upload.wikimedia.org/wikipedia/commons/e/ef/GitHub_forkme_ribbon_right_green.png" alt="Fork me on GitHub"></a> ![BayesFactor](extra/logo.png) ---- Stable version: [CRAN page](https://cran.r-project.org/package=BayesFactor) - [Package NEWS (including version changes)](https://CRAN.R-project.org/package=BayesFactor/NEWS) Development version: [Development page](https://github.com/richarddmorey/BayesFactor) - [Development package NEWS](https://github.com/richarddmorey/BayesFactor/blob/master/pkg/BayesFactor/NEWS) <div class="social"> <a target="_blank" href="https://github.com/richarddmorey/BayesFactor"><img src="extra/github.png" alt="fork on github" border="0"/><!--span class="socialtext">&nbsp;on github</span--></a> </div> ### Table of Contents * Introductory material * [Getting help](#help) * [Introduction](#intro) * [Loading the package](#loading) * [Useful functions](#functions) * Performing analyses * [One-sample (and two-sample paired), and manipulating Bayes factor objects](#onesample) * [Two independent samples](#twosample) * [Meta-analytic t tests (0.9.8+)](#metat) * [ANOVA, fixed-effects](#fixed) * [ANOVA, mixed models (including repeated measures)](#mixed) * [Regression](#regression) * [General linear models: mixing continuous and categorical covariates](#glm) * [Linear correlations](#lincor) * [Tests of single proportions (0.9.9+)](#proptest) * [Contingency Tables (0.9.9+)](#ctables) * Additional tips and tricks (0.9.4+) * [Testing restrictions on linear models: generalTestBF()](#generalTestBF) * [Saving time: Pre-culling Bayes factor objects](#preculltricks) * [Saving memory: Thinning and filtering MCMC chains](#mcmctricks) * [Fine-tuning of prior scales (0.9.12-2+)](#priorscales) * [References](#references) ### Getting help <a id="help"></a> * [Help forums](https://forum.cogsci.nl/index.php?p=/categories/jasp-bayesfactor) * [Bug reports](https://github.com/richarddmorey/BayesFactor/issues?state=open) * [Developer email (richarddmorey at gmail.com)](mailto:[email protected]) ```{r echo=FALSE,message=FALSE,results='hide'} options(markdown.HTML.stylesheet = 'extra/manual.css') library(knitr) opts_chunk$set(dpi = 200, out.width = "67%") options(digits=3) require(graphics) set.seed(2) ``` ### Introduction <a id="intro"></a> The `BayesFactor` package enables the computation of Bayes factors in standard designs, such as one- and two- sample designs, ANOVA designs, and regression. The Bayes factors are based on work spread across several papers. This document is designed to show users how to compute Bayes factors using the package by example. It is not designed to present the models used in the comparisons in detail; for that, see the `BayesFactor` help and especially the references listed in this manual. Complete references are given at the [end of this document](#references). If you need help or think you've found a bug, please use the links at the top of this document to contact the developers. When asking a question or reporting a bug, please send example code and data, the exact errors you're seeing (a cut-and-paste from the R console will work) and instructions for reproducing it. Also, report the output of `BFInfo()` and `sessionInfo()`, and let us know what operating system you're running. ### Loading the package <a id="loading"></a> The `BayesFactor` package must be installed and loaded before it can be used. Installing the package can be done in several ways and will not be covered here. Once it is installed, use the `library` function to load it: ```{r message=FALSE} library(BayesFactor) ``` ```{r echo=FALSE,message=FALSE,results='hide'} options(BFprogress = FALSE) bfversion = BFInfo() session = sessionInfo()[[1]] rversion = paste(session$version.string," on ",session$platform,sep="") ``` This command will make the `BayesFactor` package ready to use. ### Some useful functions <a id="functions"></a> The table below lists some of the functions in the `BayesFactor` package that will be demonstrated in this manual. For more complete help on the use of these functions, see the corresponding `help()` page in R. Function | Description -------------------------|------------- `ttestBF` | Bayes factors for one- and two- sample designs `anovaBF` | Bayes factors comparing many ANOVA models `regressionBF` | Bayes factors comparing many linear regression models `generalTestBF` | Bayes factors for all restrictions on a full model (0.9.4+) `lmBF` | Bayes factors for specific linear models (ANOVA or regression) `correlationBF` | Bayes factors for linear correlations `proportionBF` | Bayes factors for tests of single proportions `contingencyTableBF` | Bayes factors for contingency tables `posterior` | Sample from the posterior distribution of the numerator of a Bayes factor object `recompute` | Recompute a Bayes factor or MCMC chain, possibly increasing the precision of the estimate `compare` | Compare two models; typically used to compare two models in `BayesFactor` MCMC objects #### Functions to manipulate Bayes factor objects The t test section below has examples showing how to manipulate Bayes factor objects, but all these functions will work with Bayes factors generated from any function in the `BayesFactor` package. Function | Description -------------------------|------------ `/` | Divide two Bayes factor objects to create new model comparisons, or invert with `1/` `t` | "Flip" (transpose) a Bayes factor object `c` | Concatenate two Bayes factor objects together, assuming they have the same denominator `[` | Use indexing to select a subset of the Bayes factors `plot` | plot a Bayes factor object `sort` | Sort a Bayes factor object `is.na` | Determine whether a Bayes factor object contains missing values `head`,`tail` | Return the `n` highest or lowest Bayes factor in an object `max`, `min` | Return the highest or lowest Bayes factor in an object `which.max`,`which.min` | Return the index of the highest or lowest Bayes factor `as.vector` | Convert to a simple vector (denominator will be lost!) `as.data.frame` | Convert to data.frame (denominator will be lost!) ### One- and two-sample designs (t tests) The `ttestBF` function is used to obtain Bayes factors corresponding to tests of a single sample's mean, or tests that two independent samples have the same mean. #### One-sample tests (and paired) <a id="onesample"></a> We use the `sleep` data set in R to demonstrate a one-sample t test. This is a paired design; for details about the data set, see `?sleep`. One way of analyzing these data is to compute difference scores by subtracting a participant's score in one condition from their score in the other: ```{r onesampdata} data(sleep) ## Compute difference scores diffScores = sleep$extra[1:10] - sleep$extra[11:20] ## Traditional two-tailed t test t.test(diffScores) ``` We can do a Bayesian version of this analysis using the `ttestBF` function, which performs the "JZS" t test described by [Rouder, Speckman, Sun, Morey, and Iverson (2009)](#Rouderttest). In this model, the true standardized difference $\delta=(\mu-\mu_0)/\sigma_\epsilon$ is assumed to be 0 under the null hypothesis, and $\text{Cauchy}(\text{scale}=r)$ under the alternative. The default $r$ scale in `BayesFactor` for t tests is $\sqrt{2}/2$. See `?ttestBF` for more details. ```{r onesampt} bf = ttestBF(x = diffScores) ## Equivalently: ## bf = ttestBF(x = sleep$extra[1:10],y=sleep$extra[11:20], paired=TRUE) bf ``` The `bf` object contains the Bayes factor, and shows the numerator and denominator models for the Bayes factor comparison. In our case, the Bayes factor for the comparison of the alternative versus the null is `r as.vector(bf)`. After the Bayes factor is a proportional error estimate on the Bayes factor. There are a number of operations we can perform on our Bayes factor, such as taking the reciprocal: ```{r recip} 1 / bf ``` or sampling from the posterior of the numerator model: ```{r tsamp} chains = posterior(bf, iterations = 1000) summary(chains) ``` The `posterior` function returns a object of type `BFmcmc`, which inherits the methods of the `mcmc` class from the [`coda` package](https://cran.r-project.org/package=coda). We can thus use `summary`, `plot`, and other useful methods on the result of `posterior`. If we were unhappy with the number of iterations we sampled for `chains`, we can `recompute` with more iterations, and then `plot` the results: ```{r tsamplplot,fig.width=10,fig.cap=''} chains2 = recompute(chains, iterations = 10000) plot(chains2[,1:2]) ``` Directional hypotheses can also be tested with `ttestBF` ([Morey & Rouder, 2011](#Moreyarea)). The argument `nullInterval` can be passed as a vector of length 2, and defines an interval to compare to the point null. If null interval is defined, _two_ Bayes factors are returned: the Bayes factor of the null interval against the alternative, and the Bayes factor of the _complement_ of the interval to the point null. Suppose, for instance, we wanted to test the one-sided hypotheses that $\delta<0$ versus the point null. We set `nullInterval` to `c(-Inf,0)`: ```{r onesamptinterval} bfInterval = ttestBF(x = diffScores, nullInterval=c(-Inf,0)) bfInterval ``` We may not be interested in tests against the point null. If we are interested in the Bayes factor test that $\delta<0$ versus $\delta>0$ we can compute it using the result above. Since the object contains two Bayes factors, both with the same denominator, and $$ \left.\frac{A}{C}\middle/\frac{B}{C}\right. = \frac{A}{B}, $$ we can divide the two Bayes factors in `bfInferval` to obtain the desired test: ```{r onesampledivide} bfInterval[1] / bfInterval[2] ``` The Bayes factor is about 340. When we have multiple Bayes factors that all have the same denominator, we can concatenate them into one object using the `c` function. Since `bf` and `bfInterval` both share the point null denominator, we can do this: ```{r onesampcat} allbf = c(bf, bfInterval) allbf ``` The object `allbf` now contains three Bayes factors, all of which share the same denominator. If you try to concatenate Bayes factors that do _not_ share the same denominator, `BayesFactor` will return an error. When you have a Bayes factor object with several numerators, there are several interesting ways to manipulate them. For instance, we can plot the Bayes factor object to obtain a graphical representation of the Bayes factors: ```{r plotonesamp,fig.width=10,fig.height=5,fig.cap=''} plot(allbf) ``` We can also divide a Bayes factor object by itself &mdash; or by a subset of itself &mdash; to obtain pairwise comparisons: ```{r onesamplist} bfmat = allbf / allbf bfmat ``` The resulting object is of type `BFBayesFactorList`, and is a list of Bayes factor comparisons all of the same numerators compared to different denominators. The resulting matrix can be subsetted to return individual Bayes factor objects, or new `BFBayesFactorList`s: ```{r onesamplist2} bfmat[,2] bfmat[1,] ``` and they can also be transposed: ```{r onesamplist3} bfmat[,1:2] t(bfmat[,1:2]) ``` If these values are desired in matrix form, the `as.matrix` function can be used to obtain a matrix. #### Two-sample test (independent groups) <a id="twosample"></a> The `ttestBF` function can also be used to compute Bayes factors in the two sample case as well. We use the `chickwts` data set to demonstrate the two-sample t test. The `chickwts` data set has six groups, but we reduce it to two for the demonstration. ```{r twosampledata} data(chickwts) ## Restrict to two groups chickwts = chickwts[chickwts$feed %in% c("horsebean","linseed"),] ## Drop unused factor levels chickwts$feed = factor(chickwts$feed) ## Plot data plot(weight ~ feed, data = chickwts, main = "Chick weights") ``` Chick weight appears to be affected by the feed type. ```{r} ## traditional t test t.test(weight ~ feed, data = chickwts, var.eq=TRUE) ``` We can also compute the corresponding Bayes factor. There are two ways of specifying a two-sample test: the formula interface and through the `x` and `y` arguments. We show the formula interface here: ```{r twosamplet} ## Compute Bayes factor bf = ttestBF(formula = weight ~ feed, data = chickwts) bf ``` As before, we can sample from the posterior distribution for the numerator model: ```{r twosampletsamp,fig.width=10,fig.cap=''} chains = posterior(bf, iterations = 10000) plot(chains[,2]) ``` Note that the samples assume an (equivalent) ANOVA model; see `?ttestBF` and for notes on the differences in interpretation of the $r$ scale parameter between the two models. ### Meta-analytic t tests (0.9.8+) <a id="metat"></a> Rouder and Morey (2011; [link](#RouderMetat)) discuss a meta-analytic extension of the $t$ test, whereby multiple $t$ statistics, along with their corresponding sample sizes, are combined in a single meta-analytic analysis. The $t$ statistics are assumed to arise from a a common effect size $\delta$. The prior for the effect size $\delta$ is the same as that for the $t$ tests described above. The `meta.ttestBF` function is used to perform meta-analytic $t$ tests. It requires as input a vector of $t$ statistics, and one or two vectors of sample sizes (arguments `n1` and `n2`). For a set of one-sample $t$ statistics, `n1` should be provided; for two-sample analyses, both `n1` and `n2` should be provided. As an example, we will replicate the analysis of Rouder & Morey (2011), using $t$ statistics from Bem (2010; see Rouder & Morey for reference). We begin by defining the one-sample $t$ statistics and sample sizes: ```{r bemdata} ## Bem's t statistics from four selected experiments t = c(-.15, 2.39, 2.42, 2.43) N = c(100, 150, 97, 99) ``` Rouder and Morey opted for a one-sided analysis, and used an $r$ scale parameter of 1 (instead of the current default in `BayesFactor` of $\sqrt{2}/2$). ```{r bemanalysis1} bf = meta.ttestBF(t=t, n1=N, nullInterval=c(0,Inf), rscale=1) bf ``` Notice that as above, the analysis yields a Bayes factor for our selected interval against the null, as well as the Bayes factor for the complement of the interval against the null. We can also sample from the posterior distribution of the standardized effect size $\delta$, as above, using the `posterior` function: ```{r bemposterior,fig.width=10,fig.cap=''} ## Do analysis again, without nullInterval restriction bf = meta.ttestBF(t=t, n1=N, rscale=1) ## Obtain posterior samples chains = posterior(bf, iterations = 10000) plot(chains) ``` Notice that the posterior samples will respect the `nullInterval` argument if given; in order to get unrestricted samples, perform an analysis with no interval restriction and pass it to the `posterior` function. See `?meta.ttestBF` for more information. ### ANOVA The `BayesFactor` package has two main functions that allow the comparison of models with factors as predictors (ANOVA): `anovaBF`, which computes several model estimates at once, and `lmBF`, which computes one comparison at a time. We begin by demonstrating a 3x2 fixed-effect ANOVA using the `ToothGrowth` data set. For details about the data set, see `?ToothGrowth`. #### Fixed-effects ANOVA <a id="fixed"></a> The `ToothGrowth` data set contains three columns: `len`, the dependent variable, each of which is the length of a guinea pig's tooth after treatment with Vitamin C; `supp`, which is the supplement type (orange juice or ascorbic acid); and `dose`, which is the amount of Vitamin C administered. ```{r fixeddata,fig.width=10,fig.height=5,fig.cap=''} data(ToothGrowth) ## Example plot from ?ToothGrowth coplot(len ~ dose | supp, data = ToothGrowth, panel = panel.smooth, xlab = "ToothGrowth data: length vs dose, given type of supplement") ## Treat dose as a factor ToothGrowth$dose = factor(ToothGrowth$dose) levels(ToothGrowth$dose) = c("Low", "Medium", "High") summary(aov(len ~ supp*dose, data=ToothGrowth)) ``` There appears to be a large effect of the dosage, a small effect of the supplement type, and perhaps a hint of an interaction. The `anovaBF` function will compute the Bayes factors of all models against the intercept-only model; by default, it will choose the subset of all models in which which an interaction can only be included if all constituent effects or interactions are included (argument `whichModels` is set to `withmain`, indicating that interactions can only enter in with their main effects). However, this setting can be changed, as we will demonstrate. First, we show the default behavior. ```{r } bf = anovaBF(len ~ supp*dose, data=ToothGrowth) bf ``` The function will build the requested models from the terms included in the right-hand side of the formula; we could have specified the sum of the two terms, and we would have gotten the same models. The Bayes factor analysis is consistent with the classical ANOVA analysis; the favored model is the full model, with both main effects and the two-way interaction. Suppose we were interested in comparing the two main-effects model and the full model to the `dose`-only model. We could use indexing and division, along with the `plot` function, to see a graphical representation of these comparisons: ```{r fixedbf,fig.width=10,fig.height=5,fig.cap=''} plot(bf[3:4] / bf[2]) ``` The model with the main effect of `supp` and the `supp:dose` interaction is preferred quite strongly over the `dose`-only model. There are a number of other options for how to select subsets of models to test. The `whichModels` argument to `anovaBF` controls which subsets are tested. As described previously, the default is `withmain`, where interactions are only allowed if all constituent sub-effects are included. The other three options currently available are `all`, which tests all models; `top`, which includes the full model and all models that can be formed by removing one interaction or main effect; and `bottom`, which adds single effects one at a time to the null model. The argument `whichModels='all'` should be used with caution: a three-way ANOVA model will contain $2^{2^3-1}-1 = 127$ model comparisons; a four-way ANOVA, $2^{2^4-1}-1 = 32767$ models, and a five-way ANOVA just over 2.1 billion models. Depending on the speed of your computer, a four-way ANOVA may take several hours to a day, but a five-way ANOVA is probably not feasible. One alternative is `whichModels='top'`, which reduces the number of comparisons to $2^k-1$, where $k$ is the number of factors, which is manageable. In orthogonal designs, one can construct tests of each main effect or interaction by comparing the full model to the model with all effects except the one of interest: ```{r } bf = anovaBF(len ~ supp*dose, data=ToothGrowth, whichModels="top") bf ``` Note that all of the Bayes factors are less than 1, indicating that removing any effect from the full model is deleterious. Another way we can reduce the number of models tested is simply to test only specific models of interest. In the example above, for instance, we might want to compare the model with the interaction to the model with only the main effects, if our effect of interest was the interaction. We can do this with the `lmBF` function. ```{r} bfMainEffects = lmBF(len ~ supp + dose, data = ToothGrowth) bfInteraction = lmBF(len ~ supp + dose + supp:dose, data = ToothGrowth) ## Compare the two models bf = bfInteraction / bfMainEffects bf ``` The model with the interaction effect is preferred by a factor of about 3. Suppose that we were unhappy with the ~`r round(extractBF(bf)$error*100,1)`% proportional error on the Bayes factor `bf`. `anovaBF` and `lmBF` use Monte Carlo integration to estimate the Bayes factors. The default number of Monte Carlo samples is 10,000 but this can be increased. We could use the `recompute` to reduce the error. The `recompute` function performs the sampling required to build the Bayes factor object again: ```{r} newbf = recompute(bf, iterations = 500000) newbf ``` The proportional error is now below 1%. As before, we can use MCMC methods to estimate parameters through the `posterior` function: ```{r} ## Sample from the posterior of the full model chains = posterior(bfInteraction, iterations = 10000) ## 1:13 are the only "interesting" parameters summary(chains[,1:13]) ``` And we can plot the posteriors of some selected effects: ```{r} plot(chains[,4:6]) ``` #### Mixed models (including repeated measures) <a id="mixed"></a> In order to demonstrate the analysis of mixed models using `BayesFactor`, we will load the `puzzles` data set, which is part of the `BayesFactor` package. See `?puzzles` for details. The data set consists of four columns: `RT` the dependent variable, which is the number of seconds that it took to complete a puzzle; `ID` which is a participant identifier; and `shape` and `color`, which are two factors that describe the type of puzzle solved. `shape` and `color` each have two levels, and each of 12 participants completed puzzles within combination of `shape` and `color`. The design is thus 2x2 factorial within-subjects. We first load the data, then perform a traditional within-subjects ANOVA. ```{r } data(puzzles) ``` ```{r puzzlesplot,fig.width=7,fig.height=5,echo=FALSE,fig.cap=''} ## plot the data aovObj = aov(RT ~ shape*color + Error(ID/(shape*color)), data=puzzles) matplot(t(matrix(puzzles$RT,12,4)),ty='b',pch=19,lwd=1,lty=1,col=rgb(0,0,0,.2), ylab="Completion time", xlab="Condition",xaxt='n') axis(1,at=1:4,lab=c("round&mono","square&mono","round&color","square&color")) mns = tapply(puzzles$RT,list(puzzles$color,puzzles$shape),mean)[c(2,4,1,3)] points(1:4,mns,pch=22,col="red",bg=rgb(1,0,0,.6),cex=2) # within-subject standard error, uses MSE from ANOVA stderr = sqrt(sum(aovObj[[5]]$residuals^2)/11)/sqrt(12) segments(1:4,mns + stderr,1:4,mns - stderr,col="red") ``` (Code for plot omitted) Individual circles joined by lines show participants; red squares/lines show the means and within-subject standard errors. From the plot, there appear to be main effects of `color` and shape, but no interaction. ```{r} summary(aov(RT ~ shape*color + Error(ID/(shape*color)), data=puzzles)) ``` The classical ANOVA appears to corroborate the impression from the plot. In order to compute the Bayes factor, we must tell `anovaBF` that `ID` is an additive effect on top of the other effects (as is typically assumed) and is a random factor. The `anovaBF` call below shows how this is done: ```{r tidy=FALSE} bf = anovaBF(RT ~ shape*color + ID, data = puzzles, whichRandom="ID") ``` We alert `anovaBF` to the random factor using the `whichRandom` argument. `whichRandom` should contain a character vector with the names of all random factors in it. All other factors are assumed to be fixed. The `anovaBF` will find all the fixed effects in the formula, and compute the Bayes factor for the subset of combinations determined by the `whichModels` argument (see the previous section). Note that `anovaBF` does not test random factors; they are assumed to be nuisance factors. The null model in a test with random factors is not the intercept-only model; it is the model containing the random effects. The Bayes factor object `bf` thus now contains Bayes factors comparing various combinations of the fixed effects and an additive effect of `ID` against a denominator containing only `ID`: ```{r} bf ``` The main effects model is preferred against all models. We can plot the Bayes factor object to obtain a graphical representation of the model comparisons: ```{r testplot,fig.width=10,fig.height=5,fig.cap=''} plot(bf) ``` Because the `anovaBF` function does not test random factors, we must use `lmBF` to build such tests. Doing so is straightforward. Suppose that we wished to test the random effect `ID` in the `puzzles` example. We might compare the full model `shape + color + shape:color + ID` to the same model without `ID`: ```{r} bfWithoutID = lmBF(RT ~ shape*color, data = puzzles) bfWithoutID ``` But notice that the denominator model is the intercept-only model; the denominator in the previous analysis was the `ID` only model. We need to compare the model with no `ID` effect to the model with only `ID`: ```{r} bfOnlyID = lmBF(RT ~ ID, whichRandom="ID",data = puzzles) bf2 = bfWithoutID / bfOnlyID bf2 ``` Since our `bf` object and `bf2` object now have the same denominator, we can concatenate them into one Bayes factor object: ```{r} bfall = c(bf,bf2) ``` and we can compare them by dividing: ```{r} bf[4] / bf2 ``` The model with `ID` is preferred by a factor of over 1 million, which is not surprising. Any model that is a combination of fixed and random factors, including interations between fixed and random factors, can be constructed and tested with `lmBF`. `anovaBF` is designed to be a convenience function as is therefore somewhat limited in flexibility with respect to the models types it can test; however, because random effects are often nuisance effects, we believe `anovaBF` will be sufficient for most researchers' use. ### Linear regression <a id="regression"></a> Model comparison in multiple linear regression using `BayesFactor` is done via the approach of [Liang, Paulo, Molina, Clyde, and Berger (2008)](#Liangetal). Further discussion can be found in [Rouder & Morey (in press)](#Rouderregression). To demonstrate Bayes factor model comparison in a linear regression context, we use the `attitude` data set in R. See `?attitude`. The `attitude` consists of the dependent variable `rating`, along with 6 predictors. We can use `BayesFactor` to compute the Bayes factors for many models simultaneously, or single Bayes factors against the model containing no predictors. ```{r regressData} data(attitude) ## Traditional multiple regression analysis lmObj = lm(rating ~ ., data = attitude) summary(lmObj) ``` The period (`.`) is shorthand for all remaining columns, besides `rating`. The predictors `complaints` and `learning` appear most stongly related to the dependent variable, especially `complaints`. In order to compute the Bayes factors for many model comparisons at onces, we use the `regressionBF` function. The most obvious set of all model comparisons is all possible additive models, which is returned by default: ```{r regressAll} bf = regressionBF(rating ~ ., data = attitude) length(bf) ``` The object `bf` now contains $2^p-1$, or `r length(bf)`, model comparisons. Large numbers of comparisons can get unweildy, so we can use the functions built into R to manipulate the Bayes factor object. ```{r regressSelect} ## Choose a specific model bf["privileges + learning + raises + critical + advance"] ## Best 6 models head(bf, n=6) ## Worst 4 models tail(bf, n=4) ``` ```{r regressSelectwhichmax,eval=FALSE} ## which model index is the best? which.max(bf) ``` ```{r regressSelectwhichmaxFake,echo=FALSE} ## which model index is the best? BayesFactor::which.max(bf) ``` ```{r regressSelect2} ## Compare the 5 best models to the best bf2 = head(bf) / max(bf) bf2 plot(bf2) ``` The model preferred by Bayes factor is the `complaints`-only model, followed by the `complaints + learning` model, as might have been expected by the classical analysis. We might also be interested in comparing the most complex model to all models that can be formed by removing a single covariate, or, similarly, comparing the intercept-only model to all models that can be formed by added a covariate. These comparisons can be done by setting the `whichModels` argument to `'top'` and `'bottom'`, respectively. For example, for testing against the most complex model: ```{r regresstop, fig.width=10, fig.height=5,fig.cap=''} bf = regressionBF(rating ~ ., data = attitude, whichModels = "top") ## The seventh model is the most complex bf plot(bf) ``` With all other covariates in the model, the model containing `complaints` is preferred to the model not containing `complaints` by a factor of almost 80. The model containing `learning`, is only barely favored to the one without (a factor of about 1.3). A similar "bottom-up" test can be done, by setting `whichModels` to `'bottom'`. ```{r regressbottom, fig.width=10, fig.height=5,fig.cap=''} bf = regressionBF(rating ~ ., data = attitude, whichModels = "bottom") plot(bf) ``` The mismatch between the tests of all models, the "top-down" test, and the "bottom-up" test shows that the covariates share variance with one another. As always, whether these tests are interpretable or useful will depend on the data at hand. In cases where it is desired to only compare a small number of models, the `lmBF` function can be used. Consider the case that we wish to compare the model containing only `complaints` to the model containing `complaints` and `learning`: ```{r lmregress1} complaintsOnlyBf = lmBF(rating ~ complaints, data = attitude) complaintsLearningBf = lmBF(rating ~ complaints + learning, data = attitude) ## Compare the two models complaintsOnlyBf / complaintsLearningBf ``` The `complaints`-only model is slightly preferred. As with the other Bayes factors, it is possible to sample from the posterior distribution of a particular model under consideration. If we wanted to sample from the posterior distribution of the `complaints + learning` model, we could use the `posterior` function: ```{r lmposterior} chains = posterior(complaintsLearningBf, iterations = 10000) summary(chains) ``` Compare these to the corresponding results from the classical regression analysis: ```{r lmregressclassical} summary(lm(rating ~ complaints + learning, data = attitude)) ``` The results are quite similar, apart from the intercept. This is due to the Bayesian model centering the covariates before analysis, so the `mu` parameter is the mean of $y$ rather than the expected value of the response variable when all uncentered covariates are equal to 0. <a id="glm"></a> General linear models: mixing continuous and categorical covariates -------- The `anovaBF` and `regressionBF` functions are convenience functions designed to test several hypotheses of a particular type at once. Neither function allows the mixing of continuous and categorical covariates. If it is desired to test a model including both kinds of covariates, `lmBF` function must be used. We will continue the `ToothGrowth` example, this time without converting `dose` to a categorical variable. Instead, we will model the logarithm of the dose. ```{r echo=FALSE,results='hide'} rm(ToothGrowth) ``` ```{r GLMdata} data(ToothGrowth) # model log2 of dose instead of dose directly ToothGrowth$dose = log2(ToothGrowth$dose) # Classical analysis for comparison lmToothGrowth <- lm(len ~ supp + dose + supp:dose, data=ToothGrowth) summary(lmToothGrowth) ``` The classical analysis, presented for comparison, reveals extremely low p values for the effects of the supplement type and of the dose, but the interaction p value is more moderate, at about 0.03. We can use the `lmBF` function to compute the Bayes factors for all models of interest against the null model, which in this case is the intercept-only model. We then concatenate them into a single Bayes factor object for convenience. ```{r GLMs} full <- lmBF(len ~ supp + dose + supp:dose, data=ToothGrowth) noInteraction <- lmBF(len ~ supp + dose, data=ToothGrowth) onlyDose <- lmBF(len ~ dose, data=ToothGrowth) onlySupp <- lmBF(len ~ supp, data=ToothGrowth) allBFs <- c(full, noInteraction, onlyDose, onlySupp) allBFs ``` The highest two Bayes factors belong to the full model and the model with no interaction. We can directly compute the Bayes factor for the simpler model with no interaction against the full model: ```{r GLMs2} full / noInteraction ``` The evidence here is clearly equivocal. We can also use the `posterior` function to compute parameter estimates. ```{r GLMposterior1} chainsFull <- posterior(full, iterations = 10000) # summary of the "interesting" parameters summary(chainsFull[,1:7]) ``` The left panel of the figure below shows the data and linear fits. The green points represent guinea pigs given the orange juice supplement (OJ); red points represent guinea pigs given the vitamin C supplement. The solid lines show the posterior means from the Bayesian model; the dashed lines show the classical least-squares fit when applied to each supplement separately. The fits are quite close. ```{r GLMposterior2,results='hide',echo=FALSE} chainsNoInt <- posterior(noInteraction, iterations = 10000) ``` ```{r GLMplot,echo=FALSE,fig.width=10, fig.height=5,fig.cap=''} ToothGrowth$dose <- ToothGrowth$dose - mean(ToothGrowth$dose) cmeans <- colMeans(chainsFull)[1:6] ints <- cmeans[1] + c(-1, 1) * cmeans[2] slps <- cmeans[4] + c(-1, 1) * cmeans[5] par(cex=1.8, mfrow=c(1,2)) plot(len ~ dose, data=ToothGrowth, pch=as.integer(ToothGrowth$supp)+20, bg = rgb(as.integer(ToothGrowth$supp)-1,2-as.integer(ToothGrowth$supp),0,.5),col=NULL,xaxt="n",ylab="Tooth length",xlab="Vitamin C dose (mg)") abline(a=ints[1],b=slps[1],col=2) abline(a=ints[2],b=slps[2],col=3) axis(1,at=-1:1,lab=2^(-1:1)) dataVC <- ToothGrowth[ToothGrowth$supp=="VC",] dataOJ <- ToothGrowth[ToothGrowth$supp=="OJ",] lmVC <- lm(len ~ dose, data=dataVC) lmOJ <- lm(len ~ dose, data=dataOJ) abline(lmVC,col=2,lty=2) abline(lmOJ,col=3,lty=2) mtext("Interaction",3,.1,adj=1,cex=1.3) # Do single slope cmeans <- colMeans(chainsNoInt)[1:4] ints <- cmeans[1] + c(-1, 1) * cmeans[2] slps <- cmeans[4] plot(len ~ dose, data=ToothGrowth, pch=as.integer(ToothGrowth$supp)+20, bg = rgb(as.integer(ToothGrowth$supp)-1,2-as.integer(ToothGrowth$supp),0,.5),col=NULL,xaxt="n",ylab="Tooth length",xlab="Vitamin C dose (mg)") abline(a=ints[1],b=slps,col=2) abline(a=ints[2],b=slps,col=3) axis(1,at=-1:1,lab=2^(-1:1)) mtext("No interaction",3,.1,adj=1,cex=1.3) ``` Because the no-interaction model fares so well against the interaction model, it may be instructive to examine the fit of the no-interaction model. We sample from the no-interaction model with the `posterior` function: ```{r eval=FALSE} chainsNoInt <- posterior(noInteraction, iterations = 10000) # summary of the "interesting" parameters summary(chainsNoInt[,1:5]) ``` ```{r echo=FALSE} summary(chainsNoInt[,1:5]) ``` The right panel of the figure above shows the fit of the no-interaction model to the data. This model appears to account for the data satisfactorily. Though the moderate p value of the classical result might lead us to reject the no-interaction model, the Bayes factor and the visual fit appear to agree that the evidence is equivocal at best. We have now analyzed the `ToothGrowth` data using both ANOVA (with `dose` as a factor) and regression (with `dose` as a continuous covariate). We may wish to compare the two approaches. We first create a column of the data with `dose` as a factor, then use `anovaBF`: ```{r} ToothGrowth$doseAsFactor <- factor(ToothGrowth$dose) levels(ToothGrowth$doseAsFactor) <- c(.5,1,2) aovBFs <- anovaBF(len ~ doseAsFactor + supp + doseAsFactor:supp, data = ToothGrowth) ``` Because all models we've considered are compared to the null intercept-only model, we can concatenate the `aovBFs` object with the Bayes factors we previously computed in this section: ```{r} allBFs <- c(aovBFs, full, noInteraction, onlyDose) ## eliminate the supp-only model, since it performs so badly allBFs <- allBFs[-1] ## Compare to best model allBFs / max(allBFs) ``` Two of the models score essentially equally well in terms of Bayes factors: `supp + dose + supp:dose` and `supp + dose`, suggesting that the interaction adds little. The Bayes factors where dose is treated as a factor are all worse than when dose is treated as a continuous covariate. This is likely due to a the added flexibility allowed by including more parameters. Plotting the Bayes factors shows how large the differences are: ```{r GLMplot2,echo=FALSE,fig.width=10, fig.height=5,fig.cap=''} plot(allBFs / max(allBFs)) ``` #### Linear correlation (0.9.12-4+) <a id="lincor"></a> Ly, Verhagen, and Wagenmakers (2015; [link](#LyCor)) present a Bayes factor test for linear correlation. The `BayesFactor` package allows the computing of the Bayes factor and sampling from the posterior of the Bayes factor. Note that the model and priors are somewhat different from those used in the linear regression models presented above; further discussion can be found in Ly et al. We demonstrate the use of the `correlationBF` function using Fisher's `iris` data set built into `R`. See the help (`?iris` in R) for more details. We will focus on the correlation between `Sepal.Length` and `Sepal.Width`. First, we create a scatterplot. ```{r} plot(Sepal.Width ~ Sepal.Length, data = iris) abline(lm(Sepal.Width ~ Sepal.Length, data = iris), col = "red") ``` There does not appear to be a substantial correlation between these two variables. We can compute a classical test of the correlation using `R`'s `cor.test` function: ```{r} cor.test(y = iris$Sepal.Length, x = iris$Sepal.Width) ``` The $p$ value is nonsignificant at typical $\alpha$ levels, and the point estimate is not terribly impressive at -0.12. To compute the corresponding Bayes factor test, we use the `correlationBF` function (note the default prior scale). ```{r} bf = correlationBF(y = iris$Sepal.Length, x = iris$Sepal.Width) bf ``` As would be expected from the middling $p$ value in the classical test, the Bayes factor test shows little evidence either way (about `r round(as.vector(1/bf),1)` in favor of the null). If we'd like to estimate the correlation on the assumption that it is non-zero, we can sample from the posterior distribution using the `posterior` function. ```{r} samples = posterior(bf, iterations = 10000) ``` The important parameter is `rho`, the estimate of the true linear correlation. ```{r} summary(samples) ``` The posterior mean and credible interval for `rho` are very close to the point estimate and confidence interval obtained from `cor.test`. We can also plot the full posterior distribution, if we like: ```{r} plot(samples[,"rho"]) ``` ### Tests of single proportions (0.9.9+) <a id="proptest"></a> The default test for a proportion assumes that all observations were independent with fixed probability $\pi$. The rule for stopping can be fixed $N$ ([binomial sampling](https://en.wikipedia.org/wiki/Binomial_distribution)) or a fixed number of successes ([negative binomial sampling](https://en.wikipedia.org/wiki/Negative_binomial_distribution)); unlike a significance test, the Bayes factor does not depend on the stopping rule. For the Bayes factor test of a single proportion, there are two hypotheses; the null hypothesis assumes that the probability $\pi$ is a fixed, known value $p$; under the alternative, the log-odds corresponding to $\pi$, denoted $\omega = \log(\pi/(1-\pi))$, has a logistic distribution centered on the log-odds corresponding to the null value $p$ (denoted $\omega_0 = \log(p/(1-p))$: \[ \omega \sim \mbox{logistic}(\mbox{mean}=\omega_0, \mbox{scale}=r) \] The default prior $r$ scale is 1/2. The figure below shows the prior distribution assuming the null hypothesis $p=0.5$, for the three named prior scale settings $r$ ("medium", "wide", and "ultrawide"). The default is "medium": ```{r propprior,echo=FALSE,fig.width=10, fig.height=5,fig.cap=''} p0 = .5 rnames = c("medium","wide","ultrawide") r = sapply(rnames,function(rname) BayesFactor:::rpriorValues("proptest",,rname)) leg_names = paste(rnames," (r=",round(r,3), ")", sep="") omega = seq(-5,5,len=100) pp = dlogis(omega,qlogis(p0),r[1]) plot(omega,pp, col="black", typ = 'l', lty=1, lwd=2, ylab="Prior density", xlab=expression(paste("True log odds ", omega)), yaxt='n') pp = dlogis(omega,qlogis(p0),r[2]) lines(omega, pp, col = "red",lty=1, lwd=2) pp = dlogis(omega,qlogis(p0),r[3]) lines(omega, pp, col = "blue",lty=1,lwd=2) axis(3,at = -2:2 * 2, labels=round(plogis(-2:2*2),2)) mtext(expression(paste("True probability ", pi)),3,2,adj=.5) legend(-5,.5,legend = leg_names, col=c("black","red","blue"), lwd=2,lty=1) ``` The following example is taken from `?binom.test`, which cites [Conover (1971)](#Conover). > Under (the assumption of) simple Mendelian inheritance, a cross between plants of two particular genotypes produces progeny 1/4 of which are "dwarf" and 3/4 of which are "giant", respectively. In an experiment to determine if this assumption is reasonable, a cross results in progeny having 243 dwarf and 682 giant plants. If "giant" is taken as success, the null hypothesis is that $p = 3/4$ and the alternative that $p \neq 3/4$. ```{r} bf = proportionBF( 682, 682 + 243, p = 3/4) 1 / bf ``` The Bayes factor favors the null hypothesis by a factor of about 7 (which is not surprising given that the observed proportion is 73.7%). In contrast, the best we can say about the classical result is that it is not statistically "significant": ```{r} binom.test(682, 682 + 243, p = 3/4) ``` Using the `posterior` function, we can draw samples from the posterior distribution of the true log odds and true probability and plot the estimate of the posterior. ```{r proppost,fig.width=10, fig.height=5,fig.cap=''} chains = posterior(bf, iterations = 10000) plot(chains[,"p"], main = "Posterior of true probability\nof 'giant' progeny") ``` ### Contingency tables (0.9.9+) <a id="ctables"></a> The `BayesFactor` package implements versions of [Gunel and Dickey's (1974)](#GunelDickey) contingency table Bayes factor tests. Bayes factors for contingency tests are computed using the `contingencyTableBF` function. The necessary arguments are a matrix of cell frequencies and details about the sampling plan that produced the data. Here, we provide an example analysis of [Hraba and Grant's (1970)](#HrabaGrant) data, included as part of the `BayesFactor` package as the `raceDolls` data set. 71 white children and 89 black children from Lincoln, Nebraska were offered two dolls, one of whose "race" was the same as the child's and one that was different (either white or black). The children were then asked to select one of the dolls, with prompts such as "Give me the doll that is a nice doll." 50 of the 71 white children (70%) selected the white doll, while 48 of the 89 black children (54%) selected the black doll. These data are shown in the table below: ```{r results='asis', echo=FALSE} data(raceDolls) kable(raceDolls) ``` We can perform a Bayes factor analysis using the `contingencyTableBF` function: ```{r} bf = contingencyTableBF(raceDolls, sampleType = "indepMulti", fixedMargin = "cols") bf ``` Here we used `sampleType="indepMulti"` and `fixedMargin="cols"` to specify that the columns are assumed to be sampled as independent multinomials with their total fixed. See the help at `?contingencyTableBF` for more details about possible sampling plans and the priors. The Bayes factor in favor of the alternative that the factors are not independent is just shy of 2, which is not very much evidence against the null hypothesis. For comparison, consider the results classical chi-square test, with continuity correction: ```{r} chisq.test(raceDolls) ``` The classical test is just barely statistically significant. We can also use the `posterior` function to estimate the difference in probabilities of selecing a doll of the same race between white and black children, assuming the non-independence alternative: ```{r} chains = posterior(bf, iterations = 10000) ``` For the independent multinomial sampling plan, the chains will contain the individual cell probabilities and the marginal column probabilities. We first need to compute the conditional probabilities from the results: ```{r} sameRaceGivenWhite = chains[,"pi[1,1]"] / chains[,"pi[*,1]"] sameRaceGivenBlack = chains[,"pi[1,2]"] / chains[,"pi[*,2]"] ``` ...and then plot the MCMC estimate of the difference: ```{r ctablechains,fig.width=10, fig.height=5,fig.cap=''} plot(mcmc(sameRaceGivenWhite - sameRaceGivenBlack), main = "Increase in probability of child picking\nsame race doll (white - black)") ``` For more information, see `?contingencyTableBF`. <a id="tricks"></a> Additional tips and tricks (0.9.4+) --------- In this section, tricks to help save time and memory are described. These tricks work with version BayesFactor version 0.9.4+, unless otherwise indicated. ### Testing restrictions on linear models: generalTestBF <a id="generalTestBF"></a> The convienience functions `anovaBF` and `regressionBF` are specifically designed for cetagorical and continuous covariates respectively, and have limitations that make those functions easier to use. For instance, `anovaBF` cannot incorporate continuous covariates, and treats random effects as untested nuissance parameters. The `regressionBF` on the other hand, being strictly for multiple regression, cannot incorporate categorical covariates. These functions exist for particular purposes, since guessing what model comparisons a user wants in general is difficult. The `lmBF` function, on the other hand, can handle any model but is limited to a single model comparison: the specified model against the intercept-only model. The `generalTestBF` function allows the testing of groups of models (like `anovaBF` and `regressionBF`) but can handle any kind of model (like `lmBF`). Users specify a full model, and `generalTestBF` successively removes terms from that model and tests the resulting submodels. For example, using the `puzzles` data set described above: ```{r} data(puzzles) puzzleGenBF <- generalTestBF(RT ~ shape + color + shape:color + ID, data=puzzles, whichRandom="ID") puzzleGenBF ``` The resulting 9 models are the full model, plus the models that can be built by removing a single term at a time from the full model. By default, the `generalTestBF` function will not eliminate a term that is involved in a higher-order interaction (for instance, we will not remove `shape` unless the `shape:color` interaction is also removed); this behavior can be modified through the `whichModels` argument. It is often the case that some terms are nuisance terms that we would like to always keep in the model. For instance, `ID` in the `puzzles` data set is a participant effect; we would not generally consider models without a participant effect to be plausible. We can use the `neverExclude` argument to the function to specify a set of search terms (technically, [extended regular expressions](https://stat.ethz.ch/R-manual/R-patched/library/base/html/regex.html)) that, if matched, will specify that the term is always to be kept, and never excluded. To keep the `ID` term: ```{r} puzzleGenBF <- generalTestBF(RT ~ shape + color + shape:color + ID, data=puzzles, whichRandom="ID", neverExclude="ID") puzzleGenBF ``` The function now only considers models that contain `ID`. In some cases &mdash; especially when variable names are short, or a term to be kept is part of an interaction term that can be eliminated &mdash; we need to be careful in specifying search terms using `neverExclude`. For instance, suppose we are interested in testing the `ID:shape` interaction ```{r} puzzleGenBF <- generalTestBF(RT ~ shape + color + shape:color + shape:ID + ID, data=puzzles, whichRandom="ID", neverExclude="ID") puzzleGenBF ``` The `shape:ID` interaction is never eliminated, because it matches the `ID` search term from `neverExclude`. [Regular expressions](https://stat.ethz.ch/R-manual/R-patched/library/base/html/regex.html) are useful here. There are special characters representing the beginning and ending of a string (`^` and `$`, respectively) that we can use to construct a regular expression that will match `ID` but not `shape:ID`: ```{r} puzzleGenBF <- generalTestBF(RT ~ shape + color + shape:color + shape:ID + ID, data=puzzles, whichRandom="ID", neverExclude="^ID$") puzzleGenBF ``` The `shape:ID` interaction term is now eliminated in some models, because it does not match `"^ID$"`. Multiple terms may be provided to `neverExclude` by providing a character vector; terms which match any element in the vector will always be included in model comparisons. ### Saving time: Pre-culling Bayes factor objects <a id="preculltricks"></a> In cases where the default analysis produces many models to compare, the sampling approach to computing Bayes factors can be time consuming. The `BayesFactor` package identifies situations where sampling is not needed and thus saves time, but any model in which there is more than one categorical factor or a mix of categorical and continuous predictors will require sampling. When a default analysis produces many models that are not of interest, much of the time spent sampling may be wasted. The main functions in the `BayesFactor` package include the `noSample` argument which, if true, will prevent sampling. If a Bayes factor can be computed without sampling, the package will compute it, returning `NA` for Bayes factors that would require sampling. Continuing using the `puzzles` dataset: ```{r} puzzleCullBF <- generalTestBF(RT ~ shape + color + shape:color + ID, data=puzzles, whichRandom="ID", noSample=TRUE,whichModels='all') puzzleCullBF ``` Here we use `whichModels='all'` for demonstration, in order to obtain more possible model comparisons. Notice that several of the Bayes factors were computable without sampling, and are reported. The others have missing values, because the Bayes factor would have required sampling to compute. For now, we can separate the missing and non-missing Bayes factors in separate variables. This is made easy by the `is.na` method for BayesFactor objects: ```{r} missing = puzzleCullBF[ is.na(puzzleCullBF) ] done = puzzleCullBF[ !is.na(puzzleCullBF) ] missing ``` The variable `missing` now contains all models for which we lack a Bayes factor. At this point, we decide which of the Bayes factors we would like to compute. We can do this in any way we like: we could simple specify a subset, like `missing[1:3]` or we could do something more complicated. Here, we will include based on the model formula, using the R function `grepl` ([?grepl](https://stat.ethz.ch/R-manual/R-devel/library/base/html/grep.html)). Suppose we only wanted models that did not include *both* `shape` and `color`. First, we obtain the names of the models in `missing`, and then test the names to see if they match our restriction with `grepl`. We can use the result to restrict the models to compare to only those of interest. ```{r} # get the names of the numerator models missingModels = names(missing)$numerator # search them to see if they contain "shape" or "color" - # results are logical vectors containsShape = grepl("shape",missingModels) containsColor = grepl("color",missingModels) # anything that does not contain "shape" and "color" containsOnlyOne = !(containsShape & containsColor) # restrict missing to only those of interest missingOfInterest = missing[containsOnlyOne] missingOfInterest ``` We have restricted our set down to `r length(missingOfInterest)` items from `r length(missing)` items. We can now use `recompute` to compute the missing Bayes factors: ```{r} # recompute the Bayes factors for the missing models of interest sampledBayesFactors = recompute(missingOfInterest) sampledBayesFactors # Add them together with our other Bayes factors, already computed: completeBayesFactors = c(done, sampledBayesFactors) completeBayesFactors ``` Note that we're still left with one model that contains both `shape` and `color`, because it was computed without sampling. Assuming that we were not interested in any model containing both `shape` and `color`, however, we may have saved considerable time by not sampling to estimate their Bayes factors. The `noSample` argument will also work with the sampling of posteriors. This is especially useful, for instance, if one would like to know what order the MCMC chain results will be output in before sampling. ### Saving memory: Thinning and filtering MCMC chains <a id="mcmctricks"></a> Modern computer systems, which have many gigabytes of RAM, contain sufficient memory to perform analyses of moderate scale using the `BayesFactor` package. Some systems &mdash; particularly older 32-bit systems &mdash; are limited in the amount of memory that can address. Posterior sampling can create output that is hundreds of megabytes in size. If a user conducts several of these analyses, R may not have sufficient memory to store the results. Consider, for instance, an analysis with 100 participants, 100 items, and two fixed effects with 3 levels each. We include all main effects in the model, as well as all two-way interactions (excluding the participant by item interaction). This results in 619 parameters. Because each number stored in an MCMC chain uses 8 bytes of memory, each iterations of the chain uses 8*619=4952 bytes. If a user then requests a 100,000 iteration MCMC chain &mdash; a large, but not unreasonably, sized MCMC chain &mdash; the resulting object will use about 500Mb of memory. This is most of the memory available to the default installation of R on a 32-bit Windows system. Even if a computer has a lot of memory, many of the parameters may not be interesting to the analyst. The participant and item effects, for instance, may be nuisance variation. If a user is not interested in the estimates, it is a waste of memory to include them in the MCMC chain. The `BayesFactor` package includes several methods for reducing the size of MCMC chains: column filtering and chain thinning. Column filtering ensures that certain parameters do not appear in the output; thinning reduces the length of MCMC chains by only keeping some of the iterations. #### Column filtering Consider again the `puzzles` data set. We begin by sampling from the MCMC chain of the model with the main effect of `shape` and `color`, along with their interaction, plus a participant effect: ```{r} data(puzzles) # Get MCMC chains corresponding to "full" model # We prevent sampling so we can see the parameter names # iterations argument is necessary, but not used fullModel = lmBF(RT ~ shape + color + shape:color + ID, data = puzzles, noSample=TRUE, posterior = TRUE, iterations=3) fullModel ``` Notice that the participant effects, which are often regarded as nuisance, are included in the chain. These parameters double the size of the MCMC object; if we are not interested in the parameter values, we could eliminate them from the output for a considerable savings. This does not mean, however, that the parameters are not estimated; they will still be used by `BayesFactor`, but will not be reported. To do this, we pass the `columnFilter` argument to the sampler, which surpresses output of any columns that arise from a term matched by an element in `columnFilter.` ```{r} fullModelFiltered = lmBF(RT ~ shape + color + shape:color + ID, data = puzzles, noSample=TRUE, posterior = TRUE, iterations=3,columnFilter="ID") fullModelFiltered ``` Like the `neverExclude` argument discussed [above](#generalTestBF), the `columnFilter` argument is a character vector of [extended regular expressions](https://stat.ethz.ch/R-manual/R-patched/library/base/html/regex.html). If a model term is matched by a search term in `columnFilter`, then all columns for term are eliminated from the MCMC output. Remember that `"ID"` will match anything containing letters `ID`; it would, for instance, also eliminate terms `GID` and `ID:shape`, if they existed. See the [manual section on `generalTestBF`](#generalTestBF) for details about how to use specific regular expressions to avoid eliminating columns by accident. #### Chain thinning MCMC chains are characterized by the fact that successive iterations are correlated with one another: that is, they are not indepenedent samples from the posterior distribution. To see this, we sample from the posterior of the full model and plot the results: ```{r} # Sample 10000 iterations, eliminating ID columns chains = lmBF(RT ~ shape + color + shape:color + ID, data = puzzles, posterior = TRUE, iterations=10000,columnFilter="ID") ``` The figure below shows the first 1000 iterations of the MCMC chain for a selected parameter (left), and the *autocorrelation function* [[CRAN](https://stat.ethz.ch/R-manual/R-patched/library/stats/html/acf.html) / [Wikipedia](https://en.wikipedia.org/wiki/Autocorrelation)] for the same parameter (right). ```{r acfplot,fig.width=10,fig.height=5,echo=FALSE,fig.cap=''} par(mfrow=c(1,2)) plot(as.vector(chains[1:1000,"shape-round"]),type="l",xlab="Iterations",ylab="parameter shape-round") acf(chains[,"shape-round"]) ``` The autocorrelation here is minimal, which will be the case in general for chains from the `BayesFactor` package. If we wanted to reduce it even further, we might consider *thinning* the chain: that is, keeping only every $k$ iterations. Thinning throws away information, and is generally not necessary or recommended; however, if memory is at a premium, we might prefer storing nearly independent samples to storing somewhat dependent samples. The autocorrelation plot shows that the autocorrelation is reduced to 0 after 2 iterations. To get nearly independent samples, then, we could thin to every $k=2$ iterations using the `thin` argument: ```{r} chainsThinned = recompute(chains, iterations=20000, thin=2) # check size of MCMC chain dim(chainsThinned) ``` Notice that we are left with 10,000 iterations, instead of the 20,000 we sampled, because half were thinned. The figure below shows the resulting MCMC chain and autocorrelation functions. The MCMC chain does not visually look very different, because the autocorrelation was minimal in the first place. However, the autocorrelation function no longer shows autocorrelation from one iteration to the next, implying that we have obtained 10,000 nearly independent samples. ```{r acfplot2,fig.width=10,fig.height=5,echo=FALSE,fig.cap=''} par(mfrow=c(1,2)) plot(as.vector(chainsThinned[1:1000,"shape-round"]),type="l",xlab="Iterations",ylab="parameter shape-round") acf(chainsThinned[,"shape-round"]) ``` ### Fine-tuning of prior scales (0.9.12-2+) <a id="priorscales"></a> Previous to version `0.9.12-2`, it was only possible to change the priors on a per-effect-type basis; ie, fixed effects all had the same prior scale, random effects had a different prior scale, and slopes had third prior scale. As of `0.9.12-2`, it is possible to change the prior on a per-effect basis for fixed and random effects (slopes still share a common prior, due to the use of the Liang et al. hyper-g priors for the slopes). This is accomplished via the `rscaleEffects` argument to `lmBF`, `anovaBF`, and `generalTestBF`. The `rscaleEffects` argument is a named vector. The names correspond to the effect you'd for which you'd like to set the prior, and the value is the prior scale value. Any settings in `rscaleEffects` will override the settings in `rscaleFixed` and `rscaleRandom`; if no settings are found in `rscaleEffects`, then the settings in `rscaleFixed` and `rscaleRandom` are used. We can demonstrate using the `puzzles` data set. Suppose we prefer a prior on the `color` main effect of $r=1$, a prior twice as wide as the default in `rscaleFixed`, $r=.5$. We set the prior scale for `color` using the `rscaleEffects` argument: ```{r tidy=FALSE} newprior.bf = anovaBF(RT ~ shape + color + shape:color + ID, data = puzzles, whichRandom = "ID",rscaleEffects = c( color = 1 )) newprior.bf ``` The other fixed effects, `shape` and `shape:color`, retain the prior scale of $r=.5$ from `rscaleFixed`. Compare these Bayes factors to the ones with in the [mixed modeling](#mixed) section above. References <a id="references"></a> --------- <a id="Conover"></a> Conover, W. J. (1971), Practical nonparametric statistics. New York: John Wiley & Sons. Pages 97–104. <a id="GunelDickey"></a> Gunel, E. and Dickey, J. (1974) Bayes Factors for Independence in Contingency Tables. Biometrika, 61, 545-557. ([JSTOR](https://www.jstor.org/stable/2334738)) <a id="HrabaGrant"></a> Hraba, J. and Grant, G. (1970). Black is Beautiful: A reexamination of racial preference and identification. Journal of Personality and Social Psychology, 16, 398-402. [psychnet.apa.org](https://psycnet.apa.org/psycinfo/1971-03987-001) <a id="Liangetal"></a> Liang, F. and Paulo, R. and Molina, G. and Clyde, M. A. and Berger, J. O. (2008). Mixtures of g-priors for Bayesian Variable Selection. Journal of the American Statistical Association, 103, pp. 410-423 ([Publisher](https://www.tandfonline.com/doi/abs/10.1198/016214507000001337)) <a id="Moreyarea"></a> Morey, R. D. and Rouder, J. N. (2011). Bayes Factor Approaches for Testing Interval Null Hypotheses. Psychological Methods, 16, pp. 406-419 ([Publisher](https://psycnet.apa.org/buy/2011-15467-001)) <a id="MoreyMCMC"></a> Morey, R. D. and Rouder, J. N. and Pratte, M. S. and Speckman, P. L. (2011). Using MCMC chain outputs to efficiently estimate Bayes factors. Journal of Mathematical Psychology, 55, pp. 368-378 ([Publisher](https://www.sciencedirect.com/science/article/pii/S0022249611000666)) <a id="Rouderregression"></a> Rouder, J. N. and Morey, R. D. (2013) Default Bayes Factors for Model Selection in Regression, Multivariate Behavioral Research, 47, pp. 877-903 ([Publisher](https://www.tandfonline.com/doi/abs/10.1080/00273171.2012.734737)) <a id="RouderANOVA"></a> Rouder, J. N. and Morey, R. D. and Speckman, P. L. and Province, J. M. (2012), Default Bayes Factors for ANOVA Designs. Journal of Mathematical Psychology, 56, pp. 356–374 ([Publisher](https://www.sciencedirect.com/science/article/pii/S0022249612000806)) <a id="Rouderttest"></a> Rouder, J. N. and Speckman, P. L. and Sun, D. and Morey, R. D. and Iverson, G. (2009). Bayesian t-tests for accepting and rejecting the null hypothesis. Psychonomic Bulletin and Review, 16, pp. 225-237 ([Publisher](https://link.springer.com/article/10.3758/PBR.16.2.225)) <a id="RouderMetat"></a> Rouder, J. N. and Morey, R. D. (2011). A Bayes Factor Meta-Analysis of Bem's ESP Claim. Psychonomic Bulletin &amp; Review 18, pp. 682-689 ([Publisher](https://link.springer.com/article/10.3758/s13423-011-0088-7)) <a id="LyCor"></a> Ly, A., Verhagen, A. J. & Wagenmakers, E.-J. (2015). Harold Jeffreys's Default Bayes Factor Hypothesis Tests: Explanation, Extension, and Application in Psychology. Journal of Mathematical Psychology ([Publisher](https://dx.doi.org/10.1016/j.jmp.2015.06.004)) ------- *This document was compiled with version `r bfversion` of BayesFactor (`r rversion`).*
/scratch/gouwar.j/cran-all/cranData/BayesFactor/inst/doc/manual.Rmd
## ----echo=FALSE,message=FALSE,results='hide'---------------------------------- options(markdown.HTML.stylesheet = 'extra/manual.css') library(knitr) options(digits=3) require(graphics) set.seed(2) ## ----message=FALSE,results='hide',echo=FALSE---------------------------------- library(BayesFactor) options(BFprogress = FALSE) bfversion = BFInfo() session = sessionInfo()[[1]] rversion = paste(session$version.string," on ",session$platform,sep="") ## ----------------------------------------------------------------------------- data(puzzles) bf = anovaBF(RT ~ shape*color + ID, whichRandom = "ID", data = puzzles) bf ## ----------------------------------------------------------------------------- prior.odds = newPriorOdds(bf, type = "equal") prior.odds ## ----------------------------------------------------------------------------- priorOdds(prior.odds) <- c(4,3,2,1) prior.odds ## ----------------------------------------------------------------------------- post.odds = prior.odds * bf post.odds ## ----------------------------------------------------------------------------- post.prob = as.BFprobability(post.odds) post.prob ## ----------------------------------------------------------------------------- post.prob / .5 ## ----------------------------------------------------------------------------- post.prob[1:3] ## ----------------------------------------------------------------------------- post.prob[1:3] / 1
/scratch/gouwar.j/cran-all/cranData/BayesFactor/inst/doc/odds_probs.R
<!-- %\VignetteEngine{knitr::knitr} %\VignetteIndexEntry{Odds and probabilities} \usepackage[utf8]{inputenc} --> <a target="_blank" href="https://github.com/richarddmorey/BayesFactor"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_green_007200.png" alt="Fork me on GitHub"></a> ![BayesFactor logo](extra/logo.png) ------ Odds and probabilities using BayesFactor =============================== Richard D. Morey ----------------- <div class="social"> <a target="_blank" href="https://bayesfactor.blogspot.co.uk/"><img src="extra/socialmedia/png/48x48/blogger.png" alt="BayesFactor blog" border="0"/><span class="socialtext">&nbsp;Follow the BayesFactor blog</span></a> </div> <div class="socialsep"></div> Share via<br/> <span class="social"><a target="_blank" href="https://www.facebook.com/sharer.php?u=https://richarddmorey.github.io/BayesFactor/"><img src="extra/socialmedia/png/32x32/facebook.png" alt="share on facebook"/></a> <a target="_blank" href="https://twitter.com/share?text=Check%20out%20BayesFactor%20for%20Bayesian%20data%20analysis:&url=https://richarddmorey.github.io/BayesFactor/"><img src="extra/socialmedia/png/32x32/twitter.png" alt="tweet BayesFactor"/></a> <a target="_blank" href="https://www.reddit.com/submit?url=https://richarddmorey.github.io/BayesFactor/"><img src="extra/socialmedia/png/32x32/reddit.png" alt="submit to reddit" border="0" /></a> <a target="_blank" href="mailto:?subject=BayesFactor R package&amp;body=Check out the BayesFactor software for Bayesian analysis: https://richarddmorey.github.io/BayesFactor/." title="share by email"><img src="extra/socialmedia/png/32x32/email.png" alt="share by email" border="0" /></a> </span> ---- ```{r echo=FALSE,message=FALSE,results='hide'} options(markdown.HTML.stylesheet = 'extra/manual.css') library(knitr) options(digits=3) require(graphics) set.seed(2) ``` ```{r message=FALSE,results='hide',echo=FALSE} library(BayesFactor) options(BFprogress = FALSE) bfversion = BFInfo() session = sessionInfo()[[1]] rversion = paste(session$version.string," on ",session$platform,sep="") ``` The Bayes factor is only one part of Bayesian model comparison. The Bayes factor represents the relative evidence between two models -- that is, the change in the model odds due to the data -- but the odds are what are being changed. For any two models ${\cal M}_0$ and ${\cal M}_1$ and data $y$, \[ \frac{P({\cal M}_1\mid y)}{P({\cal M}_0\mid y)} = \frac{P(y \mid {\cal M}_1)}{P(y\mid{\cal M}_0)} \times\frac{P({\cal M}_1)}{P({\cal M}_0)}; \] that is, the posterior odds are equal to the Bayes factor times the prior odds. Further, these odds can be converted to probabilities, if we assume that all the models sum to known probability. ### Prior odds with BayesFactor ```{r} data(puzzles) bf = anovaBF(RT ~ shape*color + ID, whichRandom = "ID", data = puzzles) bf ``` With the addition of `BFodds` objects, we can compute prior and posterior odds. A prior odds object can be created from the structure of an existing BayesFactor object: ```{r} prior.odds = newPriorOdds(bf, type = "equal") prior.odds ``` For now, the only type of prior odds is "equal". However, we can change the prior odds to whatever we like with the `priorOdds` function: ```{r} priorOdds(prior.odds) <- c(4,3,2,1) prior.odds ``` ### Posterior odds with BayesFactor We can multiply the prior odds by the Bayes factor to obtain posterior odds: ```{r} post.odds = prior.odds * bf post.odds ``` ### Prior/posterior probabilities with BayesFactor Odds objects can be converted to probabilities: ```{r} post.prob = as.BFprobability(post.odds) post.prob ``` By default the probabilities sum to 1, but we can change this by renormalizing. Note that this normalizing constant is arbitrary, but it can be helpful to set it to specific values. ```{r} post.prob / .5 ``` In addition, we can select subsets of the probabilities, and the normalizing constant is adjusted to the sum of the model probabilities: ```{r} post.prob[1:3] ``` ...which can, in turn, be renormalized: ```{r} post.prob[1:3] / 1 ``` In the future, the ability to filter these objects will be added, as well as model averaging based on posterior probabilities and samples. ------- <p>Social media icons by <a href="https://www.awicons.com/">Lokas Software</a>.</p> *This document was compiled with version `r bfversion` of BayesFactor (`r rversion`).*
/scratch/gouwar.j/cran-all/cranData/BayesFactor/inst/doc/odds_probs.Rmd
## ----echo=FALSE,message=FALSE,results='hide'---------------------------------- ## ----echo=FALSE,message=FALSE,results='hide'---------------------------------- options(markdown.HTML.stylesheet = 'extra/manual.css') library(knitr) opts_chunk$set(dpi = 200, out.width = "67%") library(BayesFactor) options(BFprogress = FALSE) bfversion = BFInfo() session = sessionInfo()[[1]] rversion = paste(session$version.string," on ",session$platform,sep="") set.seed(2) ## ----------------------------------------------------------------------------- # Create data x <- rnorm(20) x[1:10] = x[1:10] + .2 grp = factor(rep(1:2,each=10)) dat = data.frame(x=x,grp=grp) t.test(x ~ grp, data=dat) ## ----------------------------------------------------------------------------- as.vector(ttestBF(formula = x ~ grp, data=dat)) as.vector(anovaBF(x~grp, data=dat)) as.vector(generalTestBF(x~grp, data=dat)) ## ----------------------------------------------------------------------------- # create some data id = rnorm(10) eff = c(-1,1)*1 effCross = outer(id,eff,'+')+rnorm(length(id)*2) dat = data.frame(x=as.vector(effCross),id=factor(1:10), grp=factor(rep(1:2,each=length(id)))) dat$forReg = as.numeric(dat$grp)-1.5 idOnly = lmBF(x~id, data=dat, whichRandom="id") summary(aov(x~grp+Error(id/grp),data=dat)) ## ----------------------------------------------------------------------------- as.vector(lmBF(x ~ grp+id, data=dat, whichRandom="id")/idOnly) as.vector(lmBF(x ~ forReg+id, data=dat, whichRandom="id")/idOnly) ## ----------------------------------------------------------------------------- # create some data tstat = 3 NTwoSample = 500 effSampleSize = (NTwoSample^2)/(2*NTwoSample) effSize = tstat/sqrt(effSampleSize) # One sample x0 = rnorm(effSampleSize) x0 = (x0 - mean(x0))/sd(x0) + effSize t.test(x0) # Two sample x1 = rnorm(NTwoSample) x1 = (x1 - mean(x1))/sd(x1) x2 = x1 + effSize t.test(x2,x1) ## ----------------------------------------------------------------------------- log(as.vector(ttestBF(x0))) log(as.vector(ttestBF(x=x1,y=x2))) ## ----------------------------------------------------------------------------- # using the data previously defined t.test(x=dat$x[dat$grp==1],y=dat$x[dat$grp==2],paired=TRUE) as.vector(lmBF(x ~ grp+id, data=dat, whichRandom="id")/idOnly) as.vector(ttestBF(x=dat$x[dat$grp==1],y=dat$x[dat$grp==2],paired=TRUE))
/scratch/gouwar.j/cran-all/cranData/BayesFactor/inst/doc/priors.R
<!-- %\VignetteEngine{knitr::knitr} %\VignetteIndexEntry{Prior checks} \usepackage[utf8]{inputenc} --> ![alt text](extra/logo.png) ------ ```{r echo=FALSE,message=FALSE,results='hide'} ``` Prior checks =========== ```{r echo=FALSE,message=FALSE,results='hide'} options(markdown.HTML.stylesheet = 'extra/manual.css') library(knitr) opts_chunk$set(dpi = 200, out.width = "67%") library(BayesFactor) options(BFprogress = FALSE) bfversion = BFInfo() session = sessionInfo()[[1]] rversion = paste(session$version.string," on ",session$platform,sep="") set.seed(2) ``` The BayesFactor has a number of prior settings that should provide for a consistent Bayes factor. In this document, Bayes factors are checked for consistency. Independent-samples t test and ANOVA ------ The independent samples $t$ test and ANOVA functions should provide the same answers with the default prior settings. ```{r} # Create data x <- rnorm(20) x[1:10] = x[1:10] + .2 grp = factor(rep(1:2,each=10)) dat = data.frame(x=x,grp=grp) t.test(x ~ grp, data=dat) ``` If the prior settings are consistent, then all three of these numbers should be the same. ```{r} as.vector(ttestBF(formula = x ~ grp, data=dat)) as.vector(anovaBF(x~grp, data=dat)) as.vector(generalTestBF(x~grp, data=dat)) ``` Regression and ANOVA ------ In a paired design with an additive random factor and and a fixed effect with two levels, the Bayes factors should be the same, regardless of whether we treat the fixed factor as a factor or as a dummy-coded covariate. ```{r} # create some data id = rnorm(10) eff = c(-1,1)*1 effCross = outer(id,eff,'+')+rnorm(length(id)*2) dat = data.frame(x=as.vector(effCross),id=factor(1:10), grp=factor(rep(1:2,each=length(id)))) dat$forReg = as.numeric(dat$grp)-1.5 idOnly = lmBF(x~id, data=dat, whichRandom="id") summary(aov(x~grp+Error(id/grp),data=dat)) ``` If the prior settings are consistent, these two numbers should be almost the same (within MC estimation error). ```{r} as.vector(lmBF(x ~ grp+id, data=dat, whichRandom="id")/idOnly) as.vector(lmBF(x ~ forReg+id, data=dat, whichRandom="id")/idOnly) ``` Independent t test and paired t test ------- Given the effect size $\hat{\delta}=t\sqrt{N_{eff}}$, where the effective sample size $N_{eff}$ is the sample size in the one-sample case, and \[ N_{eff} = \frac{N_1N_2}{N_1+N_2} \] in the two-sample case, the Bayes factors should be the same for the one-sample and two sample case, given the same observed effect size, save for the difference from the degrees of freedom that affects the shape of the noncentral $t$ likelihood. The difference from the degrees of freedom should get smaller for a given $t$ as $N_{eff}\rightarrow\infty$. ```{r} # create some data tstat = 3 NTwoSample = 500 effSampleSize = (NTwoSample^2)/(2*NTwoSample) effSize = tstat/sqrt(effSampleSize) # One sample x0 = rnorm(effSampleSize) x0 = (x0 - mean(x0))/sd(x0) + effSize t.test(x0) # Two sample x1 = rnorm(NTwoSample) x1 = (x1 - mean(x1))/sd(x1) x2 = x1 + effSize t.test(x2,x1) ``` These (log) Bayes factors should be approximately the same. ```{r} log(as.vector(ttestBF(x0))) log(as.vector(ttestBF(x=x1,y=x2))) ``` Paired samples and ANOVA ------ A paired sample $t$ test and a linear mixed effects model should broadly agree. The two are based on different models &mdash; the paired t test has the participant effects substracted out, while the linear mixed effects model has a prior on the participant effects &mdash; but we'd expect them to lead to the same conclusions. These two Bayes factors should be lead to similar conclusions. ```{r} # using the data previously defined t.test(x=dat$x[dat$grp==1],y=dat$x[dat$grp==2],paired=TRUE) as.vector(lmBF(x ~ grp+id, data=dat, whichRandom="id")/idOnly) as.vector(ttestBF(x=dat$x[dat$grp==1],y=dat$x[dat$grp==2],paired=TRUE)) ``` ------- *This document was compiled with version `r bfversion` of BayesFactor (`r rversion`).*
/scratch/gouwar.j/cran-all/cranData/BayesFactor/inst/doc/priors.Rmd
<!-- %\VignetteEngine{knitr::knitr} %\VignetteIndexEntry{Demos and comparisons} \usepackage[utf8]{inputenc} --> ![alt text](extra/logo.png) ------ ```{r echo=FALSE,message=FALSE,results='hide'} library(BayesFactor) options(BFprogress = FALSE) bfversion = BFInfo() session = sessionInfo()[[1]] rversion = paste(session$version.string," on ",session$platform,sep="") options(markdown.HTML.stylesheet = 'extra/manual.css') library(knitr) opts_chunk$set(dpi = 200, out.width = "67%") options(digits=3) require(graphics) set.seed(2) ``` Comparison of BayesFactor against other packages ======================================================== This R markdown file runs a series of tests to ensure that the BayesFactor package is giving correct answers, and can gracefully handle probable input. ```{r message=FALSE,warning=FALSE} library(arm) library(lme4) ``` ANOVA ---------- First we generate some data. ```{r} # Number of participants N <- 20 sig2 <- 1 sig2ID <- 1 # 3x3x3 design, with participant as random factor effects <- expand.grid(A = c("A1","A2","A3"), B = c("B1","B2","B3"), C = c("C1","C2","C3"), ID = paste("Sub",1:N,sep="") ) Xdata <- model.matrix(~ A*B*C + ID, data=effects) beta <- matrix(c(50, -.2,.2, 0,0, .1,-.1, rnorm(N-1,0,sqrt(sig2ID)), 0,0,0,0, -.1,.1,.1,-.1, 0,0,0,0, 0,0,0,0,0,0,0,0), ncol=1) effects$y = rnorm(Xdata%*%beta,Xdata%*%beta,sqrt(sig2)) ``` ```{r} # Typical repeated measures ANOVA summary(fullaov <- aov(y ~ A*B*C + Error(ID/(A*B*C)),data=effects)) ``` We can plot the data with standard errors: ```{r fig.width=10,fig.height=4} mns <- tapply(effects$y,list(effects$A,effects$B,effects$C),mean) stderr = sqrt((sum(resid(fullaov[[3]])^2)/fullaov[[3]]$df.resid)/N) par(mfrow=c(1,3),cex=1.1) for(i in 1:3){ matplot(mns[,,i],xaxt='n',typ='b',xlab="A",main=paste("C",i), ylim=range(mns)+c(-1,1)*stderr,ylab="y") axis(1,at=1:3,lab=1:3) segments(1:3 + mns[,,i]*0,mns[,,i] + stderr,1:3 + mns[,,i]*0,mns[,,i] - stderr,col=rgb(0,0,0,.3)) } ``` ### Bayes factor Compute the Bayes factors, while testing the Laplace approximation ```{r} t.is = system.time(bfs.is <- anovaBF(y ~ A*B*C + ID, data = effects, whichRandom="ID") ) t.la = system.time(bfs.la <- anovaBF(y ~ A*B*C + ID, data = effects, whichRandom="ID", method = "laplace") ) ``` ```{r fig.width=6,fig.height=6} t.is t.la plot(log(extractBF(sort(bfs.is))$bf),log(extractBF(sort(bfs.la))$bf), xlab="Default Sampler",ylab="Laplace approximation", pch=21,bg=rgb(0,0,1,.2),col="black",asp=TRUE,cex=1.2) abline(0,1) bfs.is ``` Comparison to lmer and arm ------ We can use samples from the posterior distribution to compare `BayesFactor` with `lmer` and `arm`. ```{r message=FALSE} chains <- lmBF(y ~ A + B + C + ID, data=effects, whichRandom = "ID", posterior=TRUE, iterations=10000) lmerObj <- lmer(y ~ A + B + C + (1|ID), data=effects) # Use arm function sim() to sample from posterior chainsLmer = sim(lmerObj,n.sims=10000) ``` Compare estimates of variance ```{r} BF.sig2 <- chains[,colnames(chains)=="sig2"] AG.sig2 <- (chainsLmer@sigma)^2 qqplot(log(BF.sig2),log(AG.sig2),pch=21,bg=rgb(0,0,1,.2), col=NULL,asp=TRUE,cex=1,xlab="BayesFactor samples", ylab="arm samples",main="Posterior samples of\nerror variance") abline(0,1) ``` Compare estimates of participant effects: ```{r} AG.raneff <- chainsLmer@ranef$ID[,,1] BF.raneff <- chains[,grep('ID-',colnames(chains),fixed='TRUE')] plot(colMeans(BF.raneff),colMeans(AG.raneff),pch=21,bg=rgb(0,0,1,.2),col="black",asp=TRUE,cex=1.2,xlab="BayesFactor estimate",ylab="arm estimate",main="Random effect posterior means") abline(0,1) ``` Compare estimates of fixed effects: ```{r tidy=FALSE} AG.fixeff <- chainsLmer@fixef BF.fixeff <- chains[,1:10] # Adjust AG results from reference cell to sum to 0 Z = c(1, 1/3, 1/3, 1/3, 1/3, 1/3, 1/3, 0, -1/3, -1/3, 0, 0, 0, 0, 0, 2/3, -1/3, 0, 0, 0, 0, 0, -1/3, 2/3, 0, 0, 0, 0, 0, 0, 0, -1/3, -1/3, 0, 0, 0, 0, 0, 2/3, -1/3, 0, 0, 0, 0, 0, -1/3, 2/3, 0, 0, 0, 0, 0, 0, 0, -1/3, -1/3, 0, 0, 0, 0, 0, 2/3, -1/3, 0, 0, 0, 0, 0, -1/3, 2/3) dim(Z) = c(7,10) Z = t(Z) AG.fixeff2 = t(Z%*%t(AG.fixeff)) ## Our grand mean has heavier tails qqplot(BF.fixeff[,1],AG.fixeff2[,1],pch=21,bg=rgb(0,0,1,.2),col=NULL,asp=TRUE,cex=1,xlab="BayesFactor estimate",ylab="arm estimate",main="Grand mean posterior samples") abline(0,1) plot(colMeans(BF.fixeff[,-1]),colMeans(AG.fixeff2[,-1]),pch=21,bg=rgb(0,0,1,.2),col="black",asp=TRUE,cex=1.2,xlab="BayesFactor estimate",ylab="arm estimate",main="Fixed effect posterior means") abline(0,1) ## Compare posterior standard deviations BFsd = apply(BF.fixeff[,-1],2,sd) AGsd = apply(AG.fixeff2[,-1],2,sd) plot(sort(AGsd/BFsd),pch=21,bg=rgb(0,0,1,.2),col="black",cex=1.2,ylab="Ratio of posterior standard deviations (arm/BF)",xlab="Fixed effect index") ## AG estimates are slightly larger, consistent with sig2 estimates ## probably due to prior ``` Another comparison with lmer ----------- We begin by loading required packages... ```{r message=FALSE,warning=FALSE} library(languageR) library(xtable) ``` ...and creating the data set to analyze. ```{r} data(primingHeidPrevRT) primingHeidPrevRT$lRTmin1 <- log(primingHeidPrevRT$RTmin1) ###Frequentist lr4 <- lmer(RT ~ Condition + (1|Word)+ (1|Subject) + lRTmin1 + RTtoPrime + ResponseToPrime + ResponseToPrime*RTtoPrime +BaseFrequency ,primingHeidPrevRT) # Get rid rid of some outlying response times INDOL <- which(scale(resid(lr4)) < 2.5) primHeidOL <- primingHeidPrevRT[INDOL,] ``` The first thing we have to do is center the continuous variables. This is done automatically by lmBF(), as required by Liang et al. (2008). This, of course, changes the definition of the intercept. ```{r} # Center continuous variables primHeidOL$BaseFrequency <- primHeidOL$BaseFrequency - mean(primHeidOL$BaseFrequency) primHeidOL$lRTmin1 <- primHeidOL$lRTmin1 - mean(primHeidOL$lRTmin1) primHeidOL$RTtoPrime <- primHeidOL$RTtoPrime - mean(primHeidOL$RTtoPrime) ``` Now we perform both analyses on the same data, and place the fixed effect estimates for both packages into their own vectors. ```{r} # LMER lr4b <- lmer( RT ~ Condition + ResponseToPrime + (1|Word)+ (1|Subject) + lRTmin1 + RTtoPrime + ResponseToPrime*RTtoPrime + BaseFrequency , primHeidOL) # BayesFactor B5out <- lmBF( RT ~ Condition + ResponseToPrime + Word + Subject + lRTmin1 + RTtoPrime + ResponseToPrime*RTtoPrime + BaseFrequency , primHeidOL , whichRandom = c("Word", "Subject"), posterior = TRUE, iteration = 50000,columnFilter=c("Word","Subject")) lmerEff <- fixef(lr4b) bfEff <- colMeans(B5out[,1:10]) ``` `lmer` uses a "reference cell" parameterization, rather than imposing sum-to-0 constraints. We can tell what the reference cell is by looking at the parameter names. ```{r results='asis'} print(xtable(cbind("lmer fixed effects"=names(lmerEff))), type='html') ``` Notice what's missing: for the categorical parameters, we are missing `Conditionbaseheid` and `ResponseToPrimecorrect`. For the slope parameters, we are missing `ResponseToPrimecorrect:RTtoPrime`. The missing effects tell us what the reference cells are. Since the reference cell parameterization is just a linear transformation of the sum-to-0 parameterization, we can create a matrix that allows us to move from one to the other. We call this $10 \times 7$ matrix `Z`. It takes the 7 "reference-cell" parameters from `lmer` and maps them into the 10 linearly constrained parameters from `lmBF`. The first row of `Z` transforms the intercept (reference cell) to the grand mean (sum-to-0). We have to add half of the two fixed effects back into the intercept. The second and third row divide the totl effect of `Condition` into two equal parts, one for `baseheid` and one for `heid`. Rows four and five do the same for `ResponseToPrime`. The slopes that do not enter into interactions are fine as they are; however, `ResponseToPrimecorrect:RTtoPrime` serves as our reference cell for the `ResponseToPrime:RTtoPrime` interaction. We treat these slopes analogously to the grand mean; we take `RTtoPrime` and add half the `ResponseToPrimeincorrect:RTtoPrime` effect to it, to make it a grand mean slope. The last two rows divide up the `ResponseToPrimeincorrect:RTtoPrime` effect between `ResponseToPrimeincorrect:RTtoPrime` and `ResponseToPrimecorrect:RTtoPrime`. ```{r tidy=FALSE} # Adjust lmer results from reference cell to sum to 0 Z = c(1, 1/2, 1/2, 0, 0, 0, 0, 0, -1/2, 0, 0, 0, 0, 0, 0, 1/2, 0, 0, 0, 0, 0, 0, 0,-1/2, 0, 0, 0, 0, 0, 0, 1/2, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1/2, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, -1/2, 0, 0, 0, 0, 0, 0, 1/2) dim(Z) = c(7,10) Z = t(Z) # Do reparameterization by pre-multimplying the parameter vector by Z reparLmer <- Z %*% matrix(lmerEff,ncol=1) # put results in data.frame for comparison sideBySide <- data.frame(BayesFactor=bfEff,lmer=reparLmer) ``` We can look at them side by side for comparison: ```{r results='asis'} print(xtable(sideBySide,digits=4), type='html') ``` ...and plot them: ```{r} # Notice Bayesian shrinkage par(cex=1.5) plot(sideBySide[-1,],pch=21,bg=rgb(0,0,1,.2),col="black",asp=TRUE,cex=1.2, main="fixed effects\n (excluding grand mean)") abline(0,1, lty=2) ``` The results are quite close to one another, with a bit of Bayesian shrinkage. ------- *This document was compiled with version `r bfversion` of BayesFactor (`r rversion`).*
/scratch/gouwar.j/cran-all/cranData/BayesFactor/vignettes/compare_lme4.Rmd
<!-- %\VignetteEngine{knitr::knitr} %\VignetteIndexEntry{Vignette menu} \usepackage[utf8]{inputenc} --> ![alt text](extra/logo.png) ------ BayesFactor manual files ------ ```{r echo=FALSE,message=FALSE,results='hide'} options(markdown.HTML.stylesheet = 'extra/manual.css') library(knitr) ``` * [Main manual](manual.html) * [Posterior odds and probabilities](odds_probs.html) * [Prior checks](priors.html) * [Comparison to arm/lmer](compare_lme4.html)
/scratch/gouwar.j/cran-all/cranData/BayesFactor/vignettes/index.Rmd
--- title: "Using the 'BayesFactor' package, version 0.9.2+" author: "Richard D. Morey" date: '`r format(Sys.time(), "%d %B, %Y")`' vignette: > %\VignetteEngine{knitr::rmarkdown} %\VignetteIndexEntry{User's manual} \usepackage[utf8]{inputenc} output: knitr:::html_vignette: toc: no --- <a target="_blank" href="https://github.com/richarddmorey/BayesFactor"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://upload.wikimedia.org/wikipedia/commons/e/ef/GitHub_forkme_ribbon_right_green.png" alt="Fork me on GitHub"></a> ![BayesFactor](extra/logo.png) ---- Stable version: [CRAN page](https://cran.r-project.org/package=BayesFactor) - [Package NEWS (including version changes)](https://CRAN.R-project.org/package=BayesFactor/NEWS) Development version: [Development page](https://github.com/richarddmorey/BayesFactor) - [Development package NEWS](https://github.com/richarddmorey/BayesFactor/blob/master/pkg/BayesFactor/NEWS) <div class="social"> <a target="_blank" href="https://github.com/richarddmorey/BayesFactor"><img src="extra/github.png" alt="fork on github" border="0"/><!--span class="socialtext">&nbsp;on github</span--></a> </div> ### Table of Contents * Introductory material * [Getting help](#help) * [Introduction](#intro) * [Loading the package](#loading) * [Useful functions](#functions) * Performing analyses * [One-sample (and two-sample paired), and manipulating Bayes factor objects](#onesample) * [Two independent samples](#twosample) * [Meta-analytic t tests (0.9.8+)](#metat) * [ANOVA, fixed-effects](#fixed) * [ANOVA, mixed models (including repeated measures)](#mixed) * [Regression](#regression) * [General linear models: mixing continuous and categorical covariates](#glm) * [Linear correlations](#lincor) * [Tests of single proportions (0.9.9+)](#proptest) * [Contingency Tables (0.9.9+)](#ctables) * Additional tips and tricks (0.9.4+) * [Testing restrictions on linear models: generalTestBF()](#generalTestBF) * [Saving time: Pre-culling Bayes factor objects](#preculltricks) * [Saving memory: Thinning and filtering MCMC chains](#mcmctricks) * [Fine-tuning of prior scales (0.9.12-2+)](#priorscales) * [References](#references) ### Getting help <a id="help"></a> * [Help forums](https://forum.cogsci.nl/index.php?p=/categories/jasp-bayesfactor) * [Bug reports](https://github.com/richarddmorey/BayesFactor/issues?state=open) * [Developer email (richarddmorey at gmail.com)](mailto:[email protected]) ```{r echo=FALSE,message=FALSE,results='hide'} options(markdown.HTML.stylesheet = 'extra/manual.css') library(knitr) opts_chunk$set(dpi = 200, out.width = "67%") options(digits=3) require(graphics) set.seed(2) ``` ### Introduction <a id="intro"></a> The `BayesFactor` package enables the computation of Bayes factors in standard designs, such as one- and two- sample designs, ANOVA designs, and regression. The Bayes factors are based on work spread across several papers. This document is designed to show users how to compute Bayes factors using the package by example. It is not designed to present the models used in the comparisons in detail; for that, see the `BayesFactor` help and especially the references listed in this manual. Complete references are given at the [end of this document](#references). If you need help or think you've found a bug, please use the links at the top of this document to contact the developers. When asking a question or reporting a bug, please send example code and data, the exact errors you're seeing (a cut-and-paste from the R console will work) and instructions for reproducing it. Also, report the output of `BFInfo()` and `sessionInfo()`, and let us know what operating system you're running. ### Loading the package <a id="loading"></a> The `BayesFactor` package must be installed and loaded before it can be used. Installing the package can be done in several ways and will not be covered here. Once it is installed, use the `library` function to load it: ```{r message=FALSE} library(BayesFactor) ``` ```{r echo=FALSE,message=FALSE,results='hide'} options(BFprogress = FALSE) bfversion = BFInfo() session = sessionInfo()[[1]] rversion = paste(session$version.string," on ",session$platform,sep="") ``` This command will make the `BayesFactor` package ready to use. ### Some useful functions <a id="functions"></a> The table below lists some of the functions in the `BayesFactor` package that will be demonstrated in this manual. For more complete help on the use of these functions, see the corresponding `help()` page in R. Function | Description -------------------------|------------- `ttestBF` | Bayes factors for one- and two- sample designs `anovaBF` | Bayes factors comparing many ANOVA models `regressionBF` | Bayes factors comparing many linear regression models `generalTestBF` | Bayes factors for all restrictions on a full model (0.9.4+) `lmBF` | Bayes factors for specific linear models (ANOVA or regression) `correlationBF` | Bayes factors for linear correlations `proportionBF` | Bayes factors for tests of single proportions `contingencyTableBF` | Bayes factors for contingency tables `posterior` | Sample from the posterior distribution of the numerator of a Bayes factor object `recompute` | Recompute a Bayes factor or MCMC chain, possibly increasing the precision of the estimate `compare` | Compare two models; typically used to compare two models in `BayesFactor` MCMC objects #### Functions to manipulate Bayes factor objects The t test section below has examples showing how to manipulate Bayes factor objects, but all these functions will work with Bayes factors generated from any function in the `BayesFactor` package. Function | Description -------------------------|------------ `/` | Divide two Bayes factor objects to create new model comparisons, or invert with `1/` `t` | "Flip" (transpose) a Bayes factor object `c` | Concatenate two Bayes factor objects together, assuming they have the same denominator `[` | Use indexing to select a subset of the Bayes factors `plot` | plot a Bayes factor object `sort` | Sort a Bayes factor object `is.na` | Determine whether a Bayes factor object contains missing values `head`,`tail` | Return the `n` highest or lowest Bayes factor in an object `max`, `min` | Return the highest or lowest Bayes factor in an object `which.max`,`which.min` | Return the index of the highest or lowest Bayes factor `as.vector` | Convert to a simple vector (denominator will be lost!) `as.data.frame` | Convert to data.frame (denominator will be lost!) ### One- and two-sample designs (t tests) The `ttestBF` function is used to obtain Bayes factors corresponding to tests of a single sample's mean, or tests that two independent samples have the same mean. #### One-sample tests (and paired) <a id="onesample"></a> We use the `sleep` data set in R to demonstrate a one-sample t test. This is a paired design; for details about the data set, see `?sleep`. One way of analyzing these data is to compute difference scores by subtracting a participant's score in one condition from their score in the other: ```{r onesampdata} data(sleep) ## Compute difference scores diffScores = sleep$extra[1:10] - sleep$extra[11:20] ## Traditional two-tailed t test t.test(diffScores) ``` We can do a Bayesian version of this analysis using the `ttestBF` function, which performs the "JZS" t test described by [Rouder, Speckman, Sun, Morey, and Iverson (2009)](#Rouderttest). In this model, the true standardized difference $\delta=(\mu-\mu_0)/\sigma_\epsilon$ is assumed to be 0 under the null hypothesis, and $\text{Cauchy}(\text{scale}=r)$ under the alternative. The default $r$ scale in `BayesFactor` for t tests is $\sqrt{2}/2$. See `?ttestBF` for more details. ```{r onesampt} bf = ttestBF(x = diffScores) ## Equivalently: ## bf = ttestBF(x = sleep$extra[1:10],y=sleep$extra[11:20], paired=TRUE) bf ``` The `bf` object contains the Bayes factor, and shows the numerator and denominator models for the Bayes factor comparison. In our case, the Bayes factor for the comparison of the alternative versus the null is `r as.vector(bf)`. After the Bayes factor is a proportional error estimate on the Bayes factor. There are a number of operations we can perform on our Bayes factor, such as taking the reciprocal: ```{r recip} 1 / bf ``` or sampling from the posterior of the numerator model: ```{r tsamp} chains = posterior(bf, iterations = 1000) summary(chains) ``` The `posterior` function returns a object of type `BFmcmc`, which inherits the methods of the `mcmc` class from the [`coda` package](https://cran.r-project.org/package=coda). We can thus use `summary`, `plot`, and other useful methods on the result of `posterior`. If we were unhappy with the number of iterations we sampled for `chains`, we can `recompute` with more iterations, and then `plot` the results: ```{r tsamplplot,fig.width=10,fig.cap=''} chains2 = recompute(chains, iterations = 10000) plot(chains2[,1:2]) ``` Directional hypotheses can also be tested with `ttestBF` ([Morey & Rouder, 2011](#Moreyarea)). The argument `nullInterval` can be passed as a vector of length 2, and defines an interval to compare to the point null. If null interval is defined, _two_ Bayes factors are returned: the Bayes factor of the null interval against the alternative, and the Bayes factor of the _complement_ of the interval to the point null. Suppose, for instance, we wanted to test the one-sided hypotheses that $\delta<0$ versus the point null. We set `nullInterval` to `c(-Inf,0)`: ```{r onesamptinterval} bfInterval = ttestBF(x = diffScores, nullInterval=c(-Inf,0)) bfInterval ``` We may not be interested in tests against the point null. If we are interested in the Bayes factor test that $\delta<0$ versus $\delta>0$ we can compute it using the result above. Since the object contains two Bayes factors, both with the same denominator, and $$ \left.\frac{A}{C}\middle/\frac{B}{C}\right. = \frac{A}{B}, $$ we can divide the two Bayes factors in `bfInferval` to obtain the desired test: ```{r onesampledivide} bfInterval[1] / bfInterval[2] ``` The Bayes factor is about 340. When we have multiple Bayes factors that all have the same denominator, we can concatenate them into one object using the `c` function. Since `bf` and `bfInterval` both share the point null denominator, we can do this: ```{r onesampcat} allbf = c(bf, bfInterval) allbf ``` The object `allbf` now contains three Bayes factors, all of which share the same denominator. If you try to concatenate Bayes factors that do _not_ share the same denominator, `BayesFactor` will return an error. When you have a Bayes factor object with several numerators, there are several interesting ways to manipulate them. For instance, we can plot the Bayes factor object to obtain a graphical representation of the Bayes factors: ```{r plotonesamp,fig.width=10,fig.height=5,fig.cap=''} plot(allbf) ``` We can also divide a Bayes factor object by itself &mdash; or by a subset of itself &mdash; to obtain pairwise comparisons: ```{r onesamplist} bfmat = allbf / allbf bfmat ``` The resulting object is of type `BFBayesFactorList`, and is a list of Bayes factor comparisons all of the same numerators compared to different denominators. The resulting matrix can be subsetted to return individual Bayes factor objects, or new `BFBayesFactorList`s: ```{r onesamplist2} bfmat[,2] bfmat[1,] ``` and they can also be transposed: ```{r onesamplist3} bfmat[,1:2] t(bfmat[,1:2]) ``` If these values are desired in matrix form, the `as.matrix` function can be used to obtain a matrix. #### Two-sample test (independent groups) <a id="twosample"></a> The `ttestBF` function can also be used to compute Bayes factors in the two sample case as well. We use the `chickwts` data set to demonstrate the two-sample t test. The `chickwts` data set has six groups, but we reduce it to two for the demonstration. ```{r twosampledata} data(chickwts) ## Restrict to two groups chickwts = chickwts[chickwts$feed %in% c("horsebean","linseed"),] ## Drop unused factor levels chickwts$feed = factor(chickwts$feed) ## Plot data plot(weight ~ feed, data = chickwts, main = "Chick weights") ``` Chick weight appears to be affected by the feed type. ```{r} ## traditional t test t.test(weight ~ feed, data = chickwts, var.eq=TRUE) ``` We can also compute the corresponding Bayes factor. There are two ways of specifying a two-sample test: the formula interface and through the `x` and `y` arguments. We show the formula interface here: ```{r twosamplet} ## Compute Bayes factor bf = ttestBF(formula = weight ~ feed, data = chickwts) bf ``` As before, we can sample from the posterior distribution for the numerator model: ```{r twosampletsamp,fig.width=10,fig.cap=''} chains = posterior(bf, iterations = 10000) plot(chains[,2]) ``` Note that the samples assume an (equivalent) ANOVA model; see `?ttestBF` and for notes on the differences in interpretation of the $r$ scale parameter between the two models. ### Meta-analytic t tests (0.9.8+) <a id="metat"></a> Rouder and Morey (2011; [link](#RouderMetat)) discuss a meta-analytic extension of the $t$ test, whereby multiple $t$ statistics, along with their corresponding sample sizes, are combined in a single meta-analytic analysis. The $t$ statistics are assumed to arise from a a common effect size $\delta$. The prior for the effect size $\delta$ is the same as that for the $t$ tests described above. The `meta.ttestBF` function is used to perform meta-analytic $t$ tests. It requires as input a vector of $t$ statistics, and one or two vectors of sample sizes (arguments `n1` and `n2`). For a set of one-sample $t$ statistics, `n1` should be provided; for two-sample analyses, both `n1` and `n2` should be provided. As an example, we will replicate the analysis of Rouder & Morey (2011), using $t$ statistics from Bem (2010; see Rouder & Morey for reference). We begin by defining the one-sample $t$ statistics and sample sizes: ```{r bemdata} ## Bem's t statistics from four selected experiments t = c(-.15, 2.39, 2.42, 2.43) N = c(100, 150, 97, 99) ``` Rouder and Morey opted for a one-sided analysis, and used an $r$ scale parameter of 1 (instead of the current default in `BayesFactor` of $\sqrt{2}/2$). ```{r bemanalysis1} bf = meta.ttestBF(t=t, n1=N, nullInterval=c(0,Inf), rscale=1) bf ``` Notice that as above, the analysis yields a Bayes factor for our selected interval against the null, as well as the Bayes factor for the complement of the interval against the null. We can also sample from the posterior distribution of the standardized effect size $\delta$, as above, using the `posterior` function: ```{r bemposterior,fig.width=10,fig.cap=''} ## Do analysis again, without nullInterval restriction bf = meta.ttestBF(t=t, n1=N, rscale=1) ## Obtain posterior samples chains = posterior(bf, iterations = 10000) plot(chains) ``` Notice that the posterior samples will respect the `nullInterval` argument if given; in order to get unrestricted samples, perform an analysis with no interval restriction and pass it to the `posterior` function. See `?meta.ttestBF` for more information. ### ANOVA The `BayesFactor` package has two main functions that allow the comparison of models with factors as predictors (ANOVA): `anovaBF`, which computes several model estimates at once, and `lmBF`, which computes one comparison at a time. We begin by demonstrating a 3x2 fixed-effect ANOVA using the `ToothGrowth` data set. For details about the data set, see `?ToothGrowth`. #### Fixed-effects ANOVA <a id="fixed"></a> The `ToothGrowth` data set contains three columns: `len`, the dependent variable, each of which is the length of a guinea pig's tooth after treatment with Vitamin C; `supp`, which is the supplement type (orange juice or ascorbic acid); and `dose`, which is the amount of Vitamin C administered. ```{r fixeddata,fig.width=10,fig.height=5,fig.cap=''} data(ToothGrowth) ## Example plot from ?ToothGrowth coplot(len ~ dose | supp, data = ToothGrowth, panel = panel.smooth, xlab = "ToothGrowth data: length vs dose, given type of supplement") ## Treat dose as a factor ToothGrowth$dose = factor(ToothGrowth$dose) levels(ToothGrowth$dose) = c("Low", "Medium", "High") summary(aov(len ~ supp*dose, data=ToothGrowth)) ``` There appears to be a large effect of the dosage, a small effect of the supplement type, and perhaps a hint of an interaction. The `anovaBF` function will compute the Bayes factors of all models against the intercept-only model; by default, it will choose the subset of all models in which which an interaction can only be included if all constituent effects or interactions are included (argument `whichModels` is set to `withmain`, indicating that interactions can only enter in with their main effects). However, this setting can be changed, as we will demonstrate. First, we show the default behavior. ```{r } bf = anovaBF(len ~ supp*dose, data=ToothGrowth) bf ``` The function will build the requested models from the terms included in the right-hand side of the formula; we could have specified the sum of the two terms, and we would have gotten the same models. The Bayes factor analysis is consistent with the classical ANOVA analysis; the favored model is the full model, with both main effects and the two-way interaction. Suppose we were interested in comparing the two main-effects model and the full model to the `dose`-only model. We could use indexing and division, along with the `plot` function, to see a graphical representation of these comparisons: ```{r fixedbf,fig.width=10,fig.height=5,fig.cap=''} plot(bf[3:4] / bf[2]) ``` The model with the main effect of `supp` and the `supp:dose` interaction is preferred quite strongly over the `dose`-only model. There are a number of other options for how to select subsets of models to test. The `whichModels` argument to `anovaBF` controls which subsets are tested. As described previously, the default is `withmain`, where interactions are only allowed if all constituent sub-effects are included. The other three options currently available are `all`, which tests all models; `top`, which includes the full model and all models that can be formed by removing one interaction or main effect; and `bottom`, which adds single effects one at a time to the null model. The argument `whichModels='all'` should be used with caution: a three-way ANOVA model will contain $2^{2^3-1}-1 = 127$ model comparisons; a four-way ANOVA, $2^{2^4-1}-1 = 32767$ models, and a five-way ANOVA just over 2.1 billion models. Depending on the speed of your computer, a four-way ANOVA may take several hours to a day, but a five-way ANOVA is probably not feasible. One alternative is `whichModels='top'`, which reduces the number of comparisons to $2^k-1$, where $k$ is the number of factors, which is manageable. In orthogonal designs, one can construct tests of each main effect or interaction by comparing the full model to the model with all effects except the one of interest: ```{r } bf = anovaBF(len ~ supp*dose, data=ToothGrowth, whichModels="top") bf ``` Note that all of the Bayes factors are less than 1, indicating that removing any effect from the full model is deleterious. Another way we can reduce the number of models tested is simply to test only specific models of interest. In the example above, for instance, we might want to compare the model with the interaction to the model with only the main effects, if our effect of interest was the interaction. We can do this with the `lmBF` function. ```{r} bfMainEffects = lmBF(len ~ supp + dose, data = ToothGrowth) bfInteraction = lmBF(len ~ supp + dose + supp:dose, data = ToothGrowth) ## Compare the two models bf = bfInteraction / bfMainEffects bf ``` The model with the interaction effect is preferred by a factor of about 3. Suppose that we were unhappy with the ~`r round(extractBF(bf)$error*100,1)`% proportional error on the Bayes factor `bf`. `anovaBF` and `lmBF` use Monte Carlo integration to estimate the Bayes factors. The default number of Monte Carlo samples is 10,000 but this can be increased. We could use the `recompute` to reduce the error. The `recompute` function performs the sampling required to build the Bayes factor object again: ```{r} newbf = recompute(bf, iterations = 500000) newbf ``` The proportional error is now below 1%. As before, we can use MCMC methods to estimate parameters through the `posterior` function: ```{r} ## Sample from the posterior of the full model chains = posterior(bfInteraction, iterations = 10000) ## 1:13 are the only "interesting" parameters summary(chains[,1:13]) ``` And we can plot the posteriors of some selected effects: ```{r} plot(chains[,4:6]) ``` #### Mixed models (including repeated measures) <a id="mixed"></a> In order to demonstrate the analysis of mixed models using `BayesFactor`, we will load the `puzzles` data set, which is part of the `BayesFactor` package. See `?puzzles` for details. The data set consists of four columns: `RT` the dependent variable, which is the number of seconds that it took to complete a puzzle; `ID` which is a participant identifier; and `shape` and `color`, which are two factors that describe the type of puzzle solved. `shape` and `color` each have two levels, and each of 12 participants completed puzzles within combination of `shape` and `color`. The design is thus 2x2 factorial within-subjects. We first load the data, then perform a traditional within-subjects ANOVA. ```{r } data(puzzles) ``` ```{r puzzlesplot,fig.width=7,fig.height=5,echo=FALSE,fig.cap=''} ## plot the data aovObj = aov(RT ~ shape*color + Error(ID/(shape*color)), data=puzzles) matplot(t(matrix(puzzles$RT,12,4)),ty='b',pch=19,lwd=1,lty=1,col=rgb(0,0,0,.2), ylab="Completion time", xlab="Condition",xaxt='n') axis(1,at=1:4,lab=c("round&mono","square&mono","round&color","square&color")) mns = tapply(puzzles$RT,list(puzzles$color,puzzles$shape),mean)[c(2,4,1,3)] points(1:4,mns,pch=22,col="red",bg=rgb(1,0,0,.6),cex=2) # within-subject standard error, uses MSE from ANOVA stderr = sqrt(sum(aovObj[[5]]$residuals^2)/11)/sqrt(12) segments(1:4,mns + stderr,1:4,mns - stderr,col="red") ``` (Code for plot omitted) Individual circles joined by lines show participants; red squares/lines show the means and within-subject standard errors. From the plot, there appear to be main effects of `color` and shape, but no interaction. ```{r} summary(aov(RT ~ shape*color + Error(ID/(shape*color)), data=puzzles)) ``` The classical ANOVA appears to corroborate the impression from the plot. In order to compute the Bayes factor, we must tell `anovaBF` that `ID` is an additive effect on top of the other effects (as is typically assumed) and is a random factor. The `anovaBF` call below shows how this is done: ```{r tidy=FALSE} bf = anovaBF(RT ~ shape*color + ID, data = puzzles, whichRandom="ID") ``` We alert `anovaBF` to the random factor using the `whichRandom` argument. `whichRandom` should contain a character vector with the names of all random factors in it. All other factors are assumed to be fixed. The `anovaBF` will find all the fixed effects in the formula, and compute the Bayes factor for the subset of combinations determined by the `whichModels` argument (see the previous section). Note that `anovaBF` does not test random factors; they are assumed to be nuisance factors. The null model in a test with random factors is not the intercept-only model; it is the model containing the random effects. The Bayes factor object `bf` thus now contains Bayes factors comparing various combinations of the fixed effects and an additive effect of `ID` against a denominator containing only `ID`: ```{r} bf ``` The main effects model is preferred against all models. We can plot the Bayes factor object to obtain a graphical representation of the model comparisons: ```{r testplot,fig.width=10,fig.height=5,fig.cap=''} plot(bf) ``` Because the `anovaBF` function does not test random factors, we must use `lmBF` to build such tests. Doing so is straightforward. Suppose that we wished to test the random effect `ID` in the `puzzles` example. We might compare the full model `shape + color + shape:color + ID` to the same model without `ID`: ```{r} bfWithoutID = lmBF(RT ~ shape*color, data = puzzles) bfWithoutID ``` But notice that the denominator model is the intercept-only model; the denominator in the previous analysis was the `ID` only model. We need to compare the model with no `ID` effect to the model with only `ID`: ```{r} bfOnlyID = lmBF(RT ~ ID, whichRandom="ID",data = puzzles) bf2 = bfWithoutID / bfOnlyID bf2 ``` Since our `bf` object and `bf2` object now have the same denominator, we can concatenate them into one Bayes factor object: ```{r} bfall = c(bf,bf2) ``` and we can compare them by dividing: ```{r} bf[4] / bf2 ``` The model with `ID` is preferred by a factor of over 1 million, which is not surprising. Any model that is a combination of fixed and random factors, including interations between fixed and random factors, can be constructed and tested with `lmBF`. `anovaBF` is designed to be a convenience function as is therefore somewhat limited in flexibility with respect to the models types it can test; however, because random effects are often nuisance effects, we believe `anovaBF` will be sufficient for most researchers' use. ### Linear regression <a id="regression"></a> Model comparison in multiple linear regression using `BayesFactor` is done via the approach of [Liang, Paulo, Molina, Clyde, and Berger (2008)](#Liangetal). Further discussion can be found in [Rouder & Morey (in press)](#Rouderregression). To demonstrate Bayes factor model comparison in a linear regression context, we use the `attitude` data set in R. See `?attitude`. The `attitude` consists of the dependent variable `rating`, along with 6 predictors. We can use `BayesFactor` to compute the Bayes factors for many models simultaneously, or single Bayes factors against the model containing no predictors. ```{r regressData} data(attitude) ## Traditional multiple regression analysis lmObj = lm(rating ~ ., data = attitude) summary(lmObj) ``` The period (`.`) is shorthand for all remaining columns, besides `rating`. The predictors `complaints` and `learning` appear most stongly related to the dependent variable, especially `complaints`. In order to compute the Bayes factors for many model comparisons at onces, we use the `regressionBF` function. The most obvious set of all model comparisons is all possible additive models, which is returned by default: ```{r regressAll} bf = regressionBF(rating ~ ., data = attitude) length(bf) ``` The object `bf` now contains $2^p-1$, or `r length(bf)`, model comparisons. Large numbers of comparisons can get unweildy, so we can use the functions built into R to manipulate the Bayes factor object. ```{r regressSelect} ## Choose a specific model bf["privileges + learning + raises + critical + advance"] ## Best 6 models head(bf, n=6) ## Worst 4 models tail(bf, n=4) ``` ```{r regressSelectwhichmax,eval=FALSE} ## which model index is the best? which.max(bf) ``` ```{r regressSelectwhichmaxFake,echo=FALSE} ## which model index is the best? BayesFactor::which.max(bf) ``` ```{r regressSelect2} ## Compare the 5 best models to the best bf2 = head(bf) / max(bf) bf2 plot(bf2) ``` The model preferred by Bayes factor is the `complaints`-only model, followed by the `complaints + learning` model, as might have been expected by the classical analysis. We might also be interested in comparing the most complex model to all models that can be formed by removing a single covariate, or, similarly, comparing the intercept-only model to all models that can be formed by added a covariate. These comparisons can be done by setting the `whichModels` argument to `'top'` and `'bottom'`, respectively. For example, for testing against the most complex model: ```{r regresstop, fig.width=10, fig.height=5,fig.cap=''} bf = regressionBF(rating ~ ., data = attitude, whichModels = "top") ## The seventh model is the most complex bf plot(bf) ``` With all other covariates in the model, the model containing `complaints` is preferred to the model not containing `complaints` by a factor of almost 80. The model containing `learning`, is only barely favored to the one without (a factor of about 1.3). A similar "bottom-up" test can be done, by setting `whichModels` to `'bottom'`. ```{r regressbottom, fig.width=10, fig.height=5,fig.cap=''} bf = regressionBF(rating ~ ., data = attitude, whichModels = "bottom") plot(bf) ``` The mismatch between the tests of all models, the "top-down" test, and the "bottom-up" test shows that the covariates share variance with one another. As always, whether these tests are interpretable or useful will depend on the data at hand. In cases where it is desired to only compare a small number of models, the `lmBF` function can be used. Consider the case that we wish to compare the model containing only `complaints` to the model containing `complaints` and `learning`: ```{r lmregress1} complaintsOnlyBf = lmBF(rating ~ complaints, data = attitude) complaintsLearningBf = lmBF(rating ~ complaints + learning, data = attitude) ## Compare the two models complaintsOnlyBf / complaintsLearningBf ``` The `complaints`-only model is slightly preferred. As with the other Bayes factors, it is possible to sample from the posterior distribution of a particular model under consideration. If we wanted to sample from the posterior distribution of the `complaints + learning` model, we could use the `posterior` function: ```{r lmposterior} chains = posterior(complaintsLearningBf, iterations = 10000) summary(chains) ``` Compare these to the corresponding results from the classical regression analysis: ```{r lmregressclassical} summary(lm(rating ~ complaints + learning, data = attitude)) ``` The results are quite similar, apart from the intercept. This is due to the Bayesian model centering the covariates before analysis, so the `mu` parameter is the mean of $y$ rather than the expected value of the response variable when all uncentered covariates are equal to 0. <a id="glm"></a> General linear models: mixing continuous and categorical covariates -------- The `anovaBF` and `regressionBF` functions are convenience functions designed to test several hypotheses of a particular type at once. Neither function allows the mixing of continuous and categorical covariates. If it is desired to test a model including both kinds of covariates, `lmBF` function must be used. We will continue the `ToothGrowth` example, this time without converting `dose` to a categorical variable. Instead, we will model the logarithm of the dose. ```{r echo=FALSE,results='hide'} rm(ToothGrowth) ``` ```{r GLMdata} data(ToothGrowth) # model log2 of dose instead of dose directly ToothGrowth$dose = log2(ToothGrowth$dose) # Classical analysis for comparison lmToothGrowth <- lm(len ~ supp + dose + supp:dose, data=ToothGrowth) summary(lmToothGrowth) ``` The classical analysis, presented for comparison, reveals extremely low p values for the effects of the supplement type and of the dose, but the interaction p value is more moderate, at about 0.03. We can use the `lmBF` function to compute the Bayes factors for all models of interest against the null model, which in this case is the intercept-only model. We then concatenate them into a single Bayes factor object for convenience. ```{r GLMs} full <- lmBF(len ~ supp + dose + supp:dose, data=ToothGrowth) noInteraction <- lmBF(len ~ supp + dose, data=ToothGrowth) onlyDose <- lmBF(len ~ dose, data=ToothGrowth) onlySupp <- lmBF(len ~ supp, data=ToothGrowth) allBFs <- c(full, noInteraction, onlyDose, onlySupp) allBFs ``` The highest two Bayes factors belong to the full model and the model with no interaction. We can directly compute the Bayes factor for the simpler model with no interaction against the full model: ```{r GLMs2} full / noInteraction ``` The evidence here is clearly equivocal. We can also use the `posterior` function to compute parameter estimates. ```{r GLMposterior1} chainsFull <- posterior(full, iterations = 10000) # summary of the "interesting" parameters summary(chainsFull[,1:7]) ``` The left panel of the figure below shows the data and linear fits. The green points represent guinea pigs given the orange juice supplement (OJ); red points represent guinea pigs given the vitamin C supplement. The solid lines show the posterior means from the Bayesian model; the dashed lines show the classical least-squares fit when applied to each supplement separately. The fits are quite close. ```{r GLMposterior2,results='hide',echo=FALSE} chainsNoInt <- posterior(noInteraction, iterations = 10000) ``` ```{r GLMplot,echo=FALSE,fig.width=10, fig.height=5,fig.cap=''} ToothGrowth$dose <- ToothGrowth$dose - mean(ToothGrowth$dose) cmeans <- colMeans(chainsFull)[1:6] ints <- cmeans[1] + c(-1, 1) * cmeans[2] slps <- cmeans[4] + c(-1, 1) * cmeans[5] par(cex=1.8, mfrow=c(1,2)) plot(len ~ dose, data=ToothGrowth, pch=as.integer(ToothGrowth$supp)+20, bg = rgb(as.integer(ToothGrowth$supp)-1,2-as.integer(ToothGrowth$supp),0,.5),col=NULL,xaxt="n",ylab="Tooth length",xlab="Vitamin C dose (mg)") abline(a=ints[1],b=slps[1],col=2) abline(a=ints[2],b=slps[2],col=3) axis(1,at=-1:1,lab=2^(-1:1)) dataVC <- ToothGrowth[ToothGrowth$supp=="VC",] dataOJ <- ToothGrowth[ToothGrowth$supp=="OJ",] lmVC <- lm(len ~ dose, data=dataVC) lmOJ <- lm(len ~ dose, data=dataOJ) abline(lmVC,col=2,lty=2) abline(lmOJ,col=3,lty=2) mtext("Interaction",3,.1,adj=1,cex=1.3) # Do single slope cmeans <- colMeans(chainsNoInt)[1:4] ints <- cmeans[1] + c(-1, 1) * cmeans[2] slps <- cmeans[4] plot(len ~ dose, data=ToothGrowth, pch=as.integer(ToothGrowth$supp)+20, bg = rgb(as.integer(ToothGrowth$supp)-1,2-as.integer(ToothGrowth$supp),0,.5),col=NULL,xaxt="n",ylab="Tooth length",xlab="Vitamin C dose (mg)") abline(a=ints[1],b=slps,col=2) abline(a=ints[2],b=slps,col=3) axis(1,at=-1:1,lab=2^(-1:1)) mtext("No interaction",3,.1,adj=1,cex=1.3) ``` Because the no-interaction model fares so well against the interaction model, it may be instructive to examine the fit of the no-interaction model. We sample from the no-interaction model with the `posterior` function: ```{r eval=FALSE} chainsNoInt <- posterior(noInteraction, iterations = 10000) # summary of the "interesting" parameters summary(chainsNoInt[,1:5]) ``` ```{r echo=FALSE} summary(chainsNoInt[,1:5]) ``` The right panel of the figure above shows the fit of the no-interaction model to the data. This model appears to account for the data satisfactorily. Though the moderate p value of the classical result might lead us to reject the no-interaction model, the Bayes factor and the visual fit appear to agree that the evidence is equivocal at best. We have now analyzed the `ToothGrowth` data using both ANOVA (with `dose` as a factor) and regression (with `dose` as a continuous covariate). We may wish to compare the two approaches. We first create a column of the data with `dose` as a factor, then use `anovaBF`: ```{r} ToothGrowth$doseAsFactor <- factor(ToothGrowth$dose) levels(ToothGrowth$doseAsFactor) <- c(.5,1,2) aovBFs <- anovaBF(len ~ doseAsFactor + supp + doseAsFactor:supp, data = ToothGrowth) ``` Because all models we've considered are compared to the null intercept-only model, we can concatenate the `aovBFs` object with the Bayes factors we previously computed in this section: ```{r} allBFs <- c(aovBFs, full, noInteraction, onlyDose) ## eliminate the supp-only model, since it performs so badly allBFs <- allBFs[-1] ## Compare to best model allBFs / max(allBFs) ``` Two of the models score essentially equally well in terms of Bayes factors: `supp + dose + supp:dose` and `supp + dose`, suggesting that the interaction adds little. The Bayes factors where dose is treated as a factor are all worse than when dose is treated as a continuous covariate. This is likely due to a the added flexibility allowed by including more parameters. Plotting the Bayes factors shows how large the differences are: ```{r GLMplot2,echo=FALSE,fig.width=10, fig.height=5,fig.cap=''} plot(allBFs / max(allBFs)) ``` #### Linear correlation (0.9.12-4+) <a id="lincor"></a> Ly, Verhagen, and Wagenmakers (2015; [link](#LyCor)) present a Bayes factor test for linear correlation. The `BayesFactor` package allows the computing of the Bayes factor and sampling from the posterior of the Bayes factor. Note that the model and priors are somewhat different from those used in the linear regression models presented above; further discussion can be found in Ly et al. We demonstrate the use of the `correlationBF` function using Fisher's `iris` data set built into `R`. See the help (`?iris` in R) for more details. We will focus on the correlation between `Sepal.Length` and `Sepal.Width`. First, we create a scatterplot. ```{r} plot(Sepal.Width ~ Sepal.Length, data = iris) abline(lm(Sepal.Width ~ Sepal.Length, data = iris), col = "red") ``` There does not appear to be a substantial correlation between these two variables. We can compute a classical test of the correlation using `R`'s `cor.test` function: ```{r} cor.test(y = iris$Sepal.Length, x = iris$Sepal.Width) ``` The $p$ value is nonsignificant at typical $\alpha$ levels, and the point estimate is not terribly impressive at -0.12. To compute the corresponding Bayes factor test, we use the `correlationBF` function (note the default prior scale). ```{r} bf = correlationBF(y = iris$Sepal.Length, x = iris$Sepal.Width) bf ``` As would be expected from the middling $p$ value in the classical test, the Bayes factor test shows little evidence either way (about `r round(as.vector(1/bf),1)` in favor of the null). If we'd like to estimate the correlation on the assumption that it is non-zero, we can sample from the posterior distribution using the `posterior` function. ```{r} samples = posterior(bf, iterations = 10000) ``` The important parameter is `rho`, the estimate of the true linear correlation. ```{r} summary(samples) ``` The posterior mean and credible interval for `rho` are very close to the point estimate and confidence interval obtained from `cor.test`. We can also plot the full posterior distribution, if we like: ```{r} plot(samples[,"rho"]) ``` ### Tests of single proportions (0.9.9+) <a id="proptest"></a> The default test for a proportion assumes that all observations were independent with fixed probability $\pi$. The rule for stopping can be fixed $N$ ([binomial sampling](https://en.wikipedia.org/wiki/Binomial_distribution)) or a fixed number of successes ([negative binomial sampling](https://en.wikipedia.org/wiki/Negative_binomial_distribution)); unlike a significance test, the Bayes factor does not depend on the stopping rule. For the Bayes factor test of a single proportion, there are two hypotheses; the null hypothesis assumes that the probability $\pi$ is a fixed, known value $p$; under the alternative, the log-odds corresponding to $\pi$, denoted $\omega = \log(\pi/(1-\pi))$, has a logistic distribution centered on the log-odds corresponding to the null value $p$ (denoted $\omega_0 = \log(p/(1-p))$: \[ \omega \sim \mbox{logistic}(\mbox{mean}=\omega_0, \mbox{scale}=r) \] The default prior $r$ scale is 1/2. The figure below shows the prior distribution assuming the null hypothesis $p=0.5$, for the three named prior scale settings $r$ ("medium", "wide", and "ultrawide"). The default is "medium": ```{r propprior,echo=FALSE,fig.width=10, fig.height=5,fig.cap=''} p0 = .5 rnames = c("medium","wide","ultrawide") r = sapply(rnames,function(rname) BayesFactor:::rpriorValues("proptest",,rname)) leg_names = paste(rnames," (r=",round(r,3), ")", sep="") omega = seq(-5,5,len=100) pp = dlogis(omega,qlogis(p0),r[1]) plot(omega,pp, col="black", typ = 'l', lty=1, lwd=2, ylab="Prior density", xlab=expression(paste("True log odds ", omega)), yaxt='n') pp = dlogis(omega,qlogis(p0),r[2]) lines(omega, pp, col = "red",lty=1, lwd=2) pp = dlogis(omega,qlogis(p0),r[3]) lines(omega, pp, col = "blue",lty=1,lwd=2) axis(3,at = -2:2 * 2, labels=round(plogis(-2:2*2),2)) mtext(expression(paste("True probability ", pi)),3,2,adj=.5) legend(-5,.5,legend = leg_names, col=c("black","red","blue"), lwd=2,lty=1) ``` The following example is taken from `?binom.test`, which cites [Conover (1971)](#Conover). > Under (the assumption of) simple Mendelian inheritance, a cross between plants of two particular genotypes produces progeny 1/4 of which are "dwarf" and 3/4 of which are "giant", respectively. In an experiment to determine if this assumption is reasonable, a cross results in progeny having 243 dwarf and 682 giant plants. If "giant" is taken as success, the null hypothesis is that $p = 3/4$ and the alternative that $p \neq 3/4$. ```{r} bf = proportionBF( 682, 682 + 243, p = 3/4) 1 / bf ``` The Bayes factor favors the null hypothesis by a factor of about 7 (which is not surprising given that the observed proportion is 73.7%). In contrast, the best we can say about the classical result is that it is not statistically "significant": ```{r} binom.test(682, 682 + 243, p = 3/4) ``` Using the `posterior` function, we can draw samples from the posterior distribution of the true log odds and true probability and plot the estimate of the posterior. ```{r proppost,fig.width=10, fig.height=5,fig.cap=''} chains = posterior(bf, iterations = 10000) plot(chains[,"p"], main = "Posterior of true probability\nof 'giant' progeny") ``` ### Contingency tables (0.9.9+) <a id="ctables"></a> The `BayesFactor` package implements versions of [Gunel and Dickey's (1974)](#GunelDickey) contingency table Bayes factor tests. Bayes factors for contingency tests are computed using the `contingencyTableBF` function. The necessary arguments are a matrix of cell frequencies and details about the sampling plan that produced the data. Here, we provide an example analysis of [Hraba and Grant's (1970)](#HrabaGrant) data, included as part of the `BayesFactor` package as the `raceDolls` data set. 71 white children and 89 black children from Lincoln, Nebraska were offered two dolls, one of whose "race" was the same as the child's and one that was different (either white or black). The children were then asked to select one of the dolls, with prompts such as "Give me the doll that is a nice doll." 50 of the 71 white children (70%) selected the white doll, while 48 of the 89 black children (54%) selected the black doll. These data are shown in the table below: ```{r results='asis', echo=FALSE} data(raceDolls) kable(raceDolls) ``` We can perform a Bayes factor analysis using the `contingencyTableBF` function: ```{r} bf = contingencyTableBF(raceDolls, sampleType = "indepMulti", fixedMargin = "cols") bf ``` Here we used `sampleType="indepMulti"` and `fixedMargin="cols"` to specify that the columns are assumed to be sampled as independent multinomials with their total fixed. See the help at `?contingencyTableBF` for more details about possible sampling plans and the priors. The Bayes factor in favor of the alternative that the factors are not independent is just shy of 2, which is not very much evidence against the null hypothesis. For comparison, consider the results classical chi-square test, with continuity correction: ```{r} chisq.test(raceDolls) ``` The classical test is just barely statistically significant. We can also use the `posterior` function to estimate the difference in probabilities of selecing a doll of the same race between white and black children, assuming the non-independence alternative: ```{r} chains = posterior(bf, iterations = 10000) ``` For the independent multinomial sampling plan, the chains will contain the individual cell probabilities and the marginal column probabilities. We first need to compute the conditional probabilities from the results: ```{r} sameRaceGivenWhite = chains[,"pi[1,1]"] / chains[,"pi[*,1]"] sameRaceGivenBlack = chains[,"pi[1,2]"] / chains[,"pi[*,2]"] ``` ...and then plot the MCMC estimate of the difference: ```{r ctablechains,fig.width=10, fig.height=5,fig.cap=''} plot(mcmc(sameRaceGivenWhite - sameRaceGivenBlack), main = "Increase in probability of child picking\nsame race doll (white - black)") ``` For more information, see `?contingencyTableBF`. <a id="tricks"></a> Additional tips and tricks (0.9.4+) --------- In this section, tricks to help save time and memory are described. These tricks work with version BayesFactor version 0.9.4+, unless otherwise indicated. ### Testing restrictions on linear models: generalTestBF <a id="generalTestBF"></a> The convienience functions `anovaBF` and `regressionBF` are specifically designed for cetagorical and continuous covariates respectively, and have limitations that make those functions easier to use. For instance, `anovaBF` cannot incorporate continuous covariates, and treats random effects as untested nuissance parameters. The `regressionBF` on the other hand, being strictly for multiple regression, cannot incorporate categorical covariates. These functions exist for particular purposes, since guessing what model comparisons a user wants in general is difficult. The `lmBF` function, on the other hand, can handle any model but is limited to a single model comparison: the specified model against the intercept-only model. The `generalTestBF` function allows the testing of groups of models (like `anovaBF` and `regressionBF`) but can handle any kind of model (like `lmBF`). Users specify a full model, and `generalTestBF` successively removes terms from that model and tests the resulting submodels. For example, using the `puzzles` data set described above: ```{r} data(puzzles) puzzleGenBF <- generalTestBF(RT ~ shape + color + shape:color + ID, data=puzzles, whichRandom="ID") puzzleGenBF ``` The resulting 9 models are the full model, plus the models that can be built by removing a single term at a time from the full model. By default, the `generalTestBF` function will not eliminate a term that is involved in a higher-order interaction (for instance, we will not remove `shape` unless the `shape:color` interaction is also removed); this behavior can be modified through the `whichModels` argument. It is often the case that some terms are nuisance terms that we would like to always keep in the model. For instance, `ID` in the `puzzles` data set is a participant effect; we would not generally consider models without a participant effect to be plausible. We can use the `neverExclude` argument to the function to specify a set of search terms (technically, [extended regular expressions](https://stat.ethz.ch/R-manual/R-patched/library/base/html/regex.html)) that, if matched, will specify that the term is always to be kept, and never excluded. To keep the `ID` term: ```{r} puzzleGenBF <- generalTestBF(RT ~ shape + color + shape:color + ID, data=puzzles, whichRandom="ID", neverExclude="ID") puzzleGenBF ``` The function now only considers models that contain `ID`. In some cases &mdash; especially when variable names are short, or a term to be kept is part of an interaction term that can be eliminated &mdash; we need to be careful in specifying search terms using `neverExclude`. For instance, suppose we are interested in testing the `ID:shape` interaction ```{r} puzzleGenBF <- generalTestBF(RT ~ shape + color + shape:color + shape:ID + ID, data=puzzles, whichRandom="ID", neverExclude="ID") puzzleGenBF ``` The `shape:ID` interaction is never eliminated, because it matches the `ID` search term from `neverExclude`. [Regular expressions](https://stat.ethz.ch/R-manual/R-patched/library/base/html/regex.html) are useful here. There are special characters representing the beginning and ending of a string (`^` and `$`, respectively) that we can use to construct a regular expression that will match `ID` but not `shape:ID`: ```{r} puzzleGenBF <- generalTestBF(RT ~ shape + color + shape:color + shape:ID + ID, data=puzzles, whichRandom="ID", neverExclude="^ID$") puzzleGenBF ``` The `shape:ID` interaction term is now eliminated in some models, because it does not match `"^ID$"`. Multiple terms may be provided to `neverExclude` by providing a character vector; terms which match any element in the vector will always be included in model comparisons. ### Saving time: Pre-culling Bayes factor objects <a id="preculltricks"></a> In cases where the default analysis produces many models to compare, the sampling approach to computing Bayes factors can be time consuming. The `BayesFactor` package identifies situations where sampling is not needed and thus saves time, but any model in which there is more than one categorical factor or a mix of categorical and continuous predictors will require sampling. When a default analysis produces many models that are not of interest, much of the time spent sampling may be wasted. The main functions in the `BayesFactor` package include the `noSample` argument which, if true, will prevent sampling. If a Bayes factor can be computed without sampling, the package will compute it, returning `NA` for Bayes factors that would require sampling. Continuing using the `puzzles` dataset: ```{r} puzzleCullBF <- generalTestBF(RT ~ shape + color + shape:color + ID, data=puzzles, whichRandom="ID", noSample=TRUE,whichModels='all') puzzleCullBF ``` Here we use `whichModels='all'` for demonstration, in order to obtain more possible model comparisons. Notice that several of the Bayes factors were computable without sampling, and are reported. The others have missing values, because the Bayes factor would have required sampling to compute. For now, we can separate the missing and non-missing Bayes factors in separate variables. This is made easy by the `is.na` method for BayesFactor objects: ```{r} missing = puzzleCullBF[ is.na(puzzleCullBF) ] done = puzzleCullBF[ !is.na(puzzleCullBF) ] missing ``` The variable `missing` now contains all models for which we lack a Bayes factor. At this point, we decide which of the Bayes factors we would like to compute. We can do this in any way we like: we could simple specify a subset, like `missing[1:3]` or we could do something more complicated. Here, we will include based on the model formula, using the R function `grepl` ([?grepl](https://stat.ethz.ch/R-manual/R-devel/library/base/html/grep.html)). Suppose we only wanted models that did not include *both* `shape` and `color`. First, we obtain the names of the models in `missing`, and then test the names to see if they match our restriction with `grepl`. We can use the result to restrict the models to compare to only those of interest. ```{r} # get the names of the numerator models missingModels = names(missing)$numerator # search them to see if they contain "shape" or "color" - # results are logical vectors containsShape = grepl("shape",missingModels) containsColor = grepl("color",missingModels) # anything that does not contain "shape" and "color" containsOnlyOne = !(containsShape & containsColor) # restrict missing to only those of interest missingOfInterest = missing[containsOnlyOne] missingOfInterest ``` We have restricted our set down to `r length(missingOfInterest)` items from `r length(missing)` items. We can now use `recompute` to compute the missing Bayes factors: ```{r} # recompute the Bayes factors for the missing models of interest sampledBayesFactors = recompute(missingOfInterest) sampledBayesFactors # Add them together with our other Bayes factors, already computed: completeBayesFactors = c(done, sampledBayesFactors) completeBayesFactors ``` Note that we're still left with one model that contains both `shape` and `color`, because it was computed without sampling. Assuming that we were not interested in any model containing both `shape` and `color`, however, we may have saved considerable time by not sampling to estimate their Bayes factors. The `noSample` argument will also work with the sampling of posteriors. This is especially useful, for instance, if one would like to know what order the MCMC chain results will be output in before sampling. ### Saving memory: Thinning and filtering MCMC chains <a id="mcmctricks"></a> Modern computer systems, which have many gigabytes of RAM, contain sufficient memory to perform analyses of moderate scale using the `BayesFactor` package. Some systems &mdash; particularly older 32-bit systems &mdash; are limited in the amount of memory that can address. Posterior sampling can create output that is hundreds of megabytes in size. If a user conducts several of these analyses, R may not have sufficient memory to store the results. Consider, for instance, an analysis with 100 participants, 100 items, and two fixed effects with 3 levels each. We include all main effects in the model, as well as all two-way interactions (excluding the participant by item interaction). This results in 619 parameters. Because each number stored in an MCMC chain uses 8 bytes of memory, each iterations of the chain uses 8*619=4952 bytes. If a user then requests a 100,000 iteration MCMC chain &mdash; a large, but not unreasonably, sized MCMC chain &mdash; the resulting object will use about 500Mb of memory. This is most of the memory available to the default installation of R on a 32-bit Windows system. Even if a computer has a lot of memory, many of the parameters may not be interesting to the analyst. The participant and item effects, for instance, may be nuisance variation. If a user is not interested in the estimates, it is a waste of memory to include them in the MCMC chain. The `BayesFactor` package includes several methods for reducing the size of MCMC chains: column filtering and chain thinning. Column filtering ensures that certain parameters do not appear in the output; thinning reduces the length of MCMC chains by only keeping some of the iterations. #### Column filtering Consider again the `puzzles` data set. We begin by sampling from the MCMC chain of the model with the main effect of `shape` and `color`, along with their interaction, plus a participant effect: ```{r} data(puzzles) # Get MCMC chains corresponding to "full" model # We prevent sampling so we can see the parameter names # iterations argument is necessary, but not used fullModel = lmBF(RT ~ shape + color + shape:color + ID, data = puzzles, noSample=TRUE, posterior = TRUE, iterations=3) fullModel ``` Notice that the participant effects, which are often regarded as nuisance, are included in the chain. These parameters double the size of the MCMC object; if we are not interested in the parameter values, we could eliminate them from the output for a considerable savings. This does not mean, however, that the parameters are not estimated; they will still be used by `BayesFactor`, but will not be reported. To do this, we pass the `columnFilter` argument to the sampler, which surpresses output of any columns that arise from a term matched by an element in `columnFilter.` ```{r} fullModelFiltered = lmBF(RT ~ shape + color + shape:color + ID, data = puzzles, noSample=TRUE, posterior = TRUE, iterations=3,columnFilter="ID") fullModelFiltered ``` Like the `neverExclude` argument discussed [above](#generalTestBF), the `columnFilter` argument is a character vector of [extended regular expressions](https://stat.ethz.ch/R-manual/R-patched/library/base/html/regex.html). If a model term is matched by a search term in `columnFilter`, then all columns for term are eliminated from the MCMC output. Remember that `"ID"` will match anything containing letters `ID`; it would, for instance, also eliminate terms `GID` and `ID:shape`, if they existed. See the [manual section on `generalTestBF`](#generalTestBF) for details about how to use specific regular expressions to avoid eliminating columns by accident. #### Chain thinning MCMC chains are characterized by the fact that successive iterations are correlated with one another: that is, they are not indepenedent samples from the posterior distribution. To see this, we sample from the posterior of the full model and plot the results: ```{r} # Sample 10000 iterations, eliminating ID columns chains = lmBF(RT ~ shape + color + shape:color + ID, data = puzzles, posterior = TRUE, iterations=10000,columnFilter="ID") ``` The figure below shows the first 1000 iterations of the MCMC chain for a selected parameter (left), and the *autocorrelation function* [[CRAN](https://stat.ethz.ch/R-manual/R-patched/library/stats/html/acf.html) / [Wikipedia](https://en.wikipedia.org/wiki/Autocorrelation)] for the same parameter (right). ```{r acfplot,fig.width=10,fig.height=5,echo=FALSE,fig.cap=''} par(mfrow=c(1,2)) plot(as.vector(chains[1:1000,"shape-round"]),type="l",xlab="Iterations",ylab="parameter shape-round") acf(chains[,"shape-round"]) ``` The autocorrelation here is minimal, which will be the case in general for chains from the `BayesFactor` package. If we wanted to reduce it even further, we might consider *thinning* the chain: that is, keeping only every $k$ iterations. Thinning throws away information, and is generally not necessary or recommended; however, if memory is at a premium, we might prefer storing nearly independent samples to storing somewhat dependent samples. The autocorrelation plot shows that the autocorrelation is reduced to 0 after 2 iterations. To get nearly independent samples, then, we could thin to every $k=2$ iterations using the `thin` argument: ```{r} chainsThinned = recompute(chains, iterations=20000, thin=2) # check size of MCMC chain dim(chainsThinned) ``` Notice that we are left with 10,000 iterations, instead of the 20,000 we sampled, because half were thinned. The figure below shows the resulting MCMC chain and autocorrelation functions. The MCMC chain does not visually look very different, because the autocorrelation was minimal in the first place. However, the autocorrelation function no longer shows autocorrelation from one iteration to the next, implying that we have obtained 10,000 nearly independent samples. ```{r acfplot2,fig.width=10,fig.height=5,echo=FALSE,fig.cap=''} par(mfrow=c(1,2)) plot(as.vector(chainsThinned[1:1000,"shape-round"]),type="l",xlab="Iterations",ylab="parameter shape-round") acf(chainsThinned[,"shape-round"]) ``` ### Fine-tuning of prior scales (0.9.12-2+) <a id="priorscales"></a> Previous to version `0.9.12-2`, it was only possible to change the priors on a per-effect-type basis; ie, fixed effects all had the same prior scale, random effects had a different prior scale, and slopes had third prior scale. As of `0.9.12-2`, it is possible to change the prior on a per-effect basis for fixed and random effects (slopes still share a common prior, due to the use of the Liang et al. hyper-g priors for the slopes). This is accomplished via the `rscaleEffects` argument to `lmBF`, `anovaBF`, and `generalTestBF`. The `rscaleEffects` argument is a named vector. The names correspond to the effect you'd for which you'd like to set the prior, and the value is the prior scale value. Any settings in `rscaleEffects` will override the settings in `rscaleFixed` and `rscaleRandom`; if no settings are found in `rscaleEffects`, then the settings in `rscaleFixed` and `rscaleRandom` are used. We can demonstrate using the `puzzles` data set. Suppose we prefer a prior on the `color` main effect of $r=1$, a prior twice as wide as the default in `rscaleFixed`, $r=.5$. We set the prior scale for `color` using the `rscaleEffects` argument: ```{r tidy=FALSE} newprior.bf = anovaBF(RT ~ shape + color + shape:color + ID, data = puzzles, whichRandom = "ID",rscaleEffects = c( color = 1 )) newprior.bf ``` The other fixed effects, `shape` and `shape:color`, retain the prior scale of $r=.5$ from `rscaleFixed`. Compare these Bayes factors to the ones with in the [mixed modeling](#mixed) section above. References <a id="references"></a> --------- <a id="Conover"></a> Conover, W. J. (1971), Practical nonparametric statistics. New York: John Wiley & Sons. Pages 97–104. <a id="GunelDickey"></a> Gunel, E. and Dickey, J. (1974) Bayes Factors for Independence in Contingency Tables. Biometrika, 61, 545-557. ([JSTOR](https://www.jstor.org/stable/2334738)) <a id="HrabaGrant"></a> Hraba, J. and Grant, G. (1970). Black is Beautiful: A reexamination of racial preference and identification. Journal of Personality and Social Psychology, 16, 398-402. [psychnet.apa.org](https://psycnet.apa.org/psycinfo/1971-03987-001) <a id="Liangetal"></a> Liang, F. and Paulo, R. and Molina, G. and Clyde, M. A. and Berger, J. O. (2008). Mixtures of g-priors for Bayesian Variable Selection. Journal of the American Statistical Association, 103, pp. 410-423 ([Publisher](https://www.tandfonline.com/doi/abs/10.1198/016214507000001337)) <a id="Moreyarea"></a> Morey, R. D. and Rouder, J. N. (2011). Bayes Factor Approaches for Testing Interval Null Hypotheses. Psychological Methods, 16, pp. 406-419 ([Publisher](https://psycnet.apa.org/buy/2011-15467-001)) <a id="MoreyMCMC"></a> Morey, R. D. and Rouder, J. N. and Pratte, M. S. and Speckman, P. L. (2011). Using MCMC chain outputs to efficiently estimate Bayes factors. Journal of Mathematical Psychology, 55, pp. 368-378 ([Publisher](https://www.sciencedirect.com/science/article/pii/S0022249611000666)) <a id="Rouderregression"></a> Rouder, J. N. and Morey, R. D. (2013) Default Bayes Factors for Model Selection in Regression, Multivariate Behavioral Research, 47, pp. 877-903 ([Publisher](https://www.tandfonline.com/doi/abs/10.1080/00273171.2012.734737)) <a id="RouderANOVA"></a> Rouder, J. N. and Morey, R. D. and Speckman, P. L. and Province, J. M. (2012), Default Bayes Factors for ANOVA Designs. Journal of Mathematical Psychology, 56, pp. 356–374 ([Publisher](https://www.sciencedirect.com/science/article/pii/S0022249612000806)) <a id="Rouderttest"></a> Rouder, J. N. and Speckman, P. L. and Sun, D. and Morey, R. D. and Iverson, G. (2009). Bayesian t-tests for accepting and rejecting the null hypothesis. Psychonomic Bulletin and Review, 16, pp. 225-237 ([Publisher](https://link.springer.com/article/10.3758/PBR.16.2.225)) <a id="RouderMetat"></a> Rouder, J. N. and Morey, R. D. (2011). A Bayes Factor Meta-Analysis of Bem's ESP Claim. Psychonomic Bulletin &amp; Review 18, pp. 682-689 ([Publisher](https://link.springer.com/article/10.3758/s13423-011-0088-7)) <a id="LyCor"></a> Ly, A., Verhagen, A. J. & Wagenmakers, E.-J. (2015). Harold Jeffreys's Default Bayes Factor Hypothesis Tests: Explanation, Extension, and Application in Psychology. Journal of Mathematical Psychology ([Publisher](https://dx.doi.org/10.1016/j.jmp.2015.06.004)) ------- *This document was compiled with version `r bfversion` of BayesFactor (`r rversion`).*
/scratch/gouwar.j/cran-all/cranData/BayesFactor/vignettes/manual.Rmd
<!-- %\VignetteEngine{knitr::knitr} %\VignetteIndexEntry{Odds and probabilities} \usepackage[utf8]{inputenc} --> <a target="_blank" href="https://github.com/richarddmorey/BayesFactor"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_green_007200.png" alt="Fork me on GitHub"></a> ![BayesFactor logo](extra/logo.png) ------ Odds and probabilities using BayesFactor =============================== Richard D. Morey ----------------- <div class="social"> <a target="_blank" href="https://bayesfactor.blogspot.co.uk/"><img src="extra/socialmedia/png/48x48/blogger.png" alt="BayesFactor blog" border="0"/><span class="socialtext">&nbsp;Follow the BayesFactor blog</span></a> </div> <div class="socialsep"></div> Share via<br/> <span class="social"><a target="_blank" href="https://www.facebook.com/sharer.php?u=https://richarddmorey.github.io/BayesFactor/"><img src="extra/socialmedia/png/32x32/facebook.png" alt="share on facebook"/></a> <a target="_blank" href="https://twitter.com/share?text=Check%20out%20BayesFactor%20for%20Bayesian%20data%20analysis:&url=https://richarddmorey.github.io/BayesFactor/"><img src="extra/socialmedia/png/32x32/twitter.png" alt="tweet BayesFactor"/></a> <a target="_blank" href="https://www.reddit.com/submit?url=https://richarddmorey.github.io/BayesFactor/"><img src="extra/socialmedia/png/32x32/reddit.png" alt="submit to reddit" border="0" /></a> <a target="_blank" href="mailto:?subject=BayesFactor R package&amp;body=Check out the BayesFactor software for Bayesian analysis: https://richarddmorey.github.io/BayesFactor/." title="share by email"><img src="extra/socialmedia/png/32x32/email.png" alt="share by email" border="0" /></a> </span> ---- ```{r echo=FALSE,message=FALSE,results='hide'} options(markdown.HTML.stylesheet = 'extra/manual.css') library(knitr) options(digits=3) require(graphics) set.seed(2) ``` ```{r message=FALSE,results='hide',echo=FALSE} library(BayesFactor) options(BFprogress = FALSE) bfversion = BFInfo() session = sessionInfo()[[1]] rversion = paste(session$version.string," on ",session$platform,sep="") ``` The Bayes factor is only one part of Bayesian model comparison. The Bayes factor represents the relative evidence between two models -- that is, the change in the model odds due to the data -- but the odds are what are being changed. For any two models ${\cal M}_0$ and ${\cal M}_1$ and data $y$, \[ \frac{P({\cal M}_1\mid y)}{P({\cal M}_0\mid y)} = \frac{P(y \mid {\cal M}_1)}{P(y\mid{\cal M}_0)} \times\frac{P({\cal M}_1)}{P({\cal M}_0)}; \] that is, the posterior odds are equal to the Bayes factor times the prior odds. Further, these odds can be converted to probabilities, if we assume that all the models sum to known probability. ### Prior odds with BayesFactor ```{r} data(puzzles) bf = anovaBF(RT ~ shape*color + ID, whichRandom = "ID", data = puzzles) bf ``` With the addition of `BFodds` objects, we can compute prior and posterior odds. A prior odds object can be created from the structure of an existing BayesFactor object: ```{r} prior.odds = newPriorOdds(bf, type = "equal") prior.odds ``` For now, the only type of prior odds is "equal". However, we can change the prior odds to whatever we like with the `priorOdds` function: ```{r} priorOdds(prior.odds) <- c(4,3,2,1) prior.odds ``` ### Posterior odds with BayesFactor We can multiply the prior odds by the Bayes factor to obtain posterior odds: ```{r} post.odds = prior.odds * bf post.odds ``` ### Prior/posterior probabilities with BayesFactor Odds objects can be converted to probabilities: ```{r} post.prob = as.BFprobability(post.odds) post.prob ``` By default the probabilities sum to 1, but we can change this by renormalizing. Note that this normalizing constant is arbitrary, but it can be helpful to set it to specific values. ```{r} post.prob / .5 ``` In addition, we can select subsets of the probabilities, and the normalizing constant is adjusted to the sum of the model probabilities: ```{r} post.prob[1:3] ``` ...which can, in turn, be renormalized: ```{r} post.prob[1:3] / 1 ``` In the future, the ability to filter these objects will be added, as well as model averaging based on posterior probabilities and samples. ------- <p>Social media icons by <a href="https://www.awicons.com/">Lokas Software</a>.</p> *This document was compiled with version `r bfversion` of BayesFactor (`r rversion`).*
/scratch/gouwar.j/cran-all/cranData/BayesFactor/vignettes/odds_probs.Rmd
<!-- %\VignetteEngine{knitr::knitr} %\VignetteIndexEntry{Prior checks} \usepackage[utf8]{inputenc} --> ![alt text](extra/logo.png) ------ ```{r echo=FALSE,message=FALSE,results='hide'} ``` Prior checks =========== ```{r echo=FALSE,message=FALSE,results='hide'} options(markdown.HTML.stylesheet = 'extra/manual.css') library(knitr) opts_chunk$set(dpi = 200, out.width = "67%") library(BayesFactor) options(BFprogress = FALSE) bfversion = BFInfo() session = sessionInfo()[[1]] rversion = paste(session$version.string," on ",session$platform,sep="") set.seed(2) ``` The BayesFactor has a number of prior settings that should provide for a consistent Bayes factor. In this document, Bayes factors are checked for consistency. Independent-samples t test and ANOVA ------ The independent samples $t$ test and ANOVA functions should provide the same answers with the default prior settings. ```{r} # Create data x <- rnorm(20) x[1:10] = x[1:10] + .2 grp = factor(rep(1:2,each=10)) dat = data.frame(x=x,grp=grp) t.test(x ~ grp, data=dat) ``` If the prior settings are consistent, then all three of these numbers should be the same. ```{r} as.vector(ttestBF(formula = x ~ grp, data=dat)) as.vector(anovaBF(x~grp, data=dat)) as.vector(generalTestBF(x~grp, data=dat)) ``` Regression and ANOVA ------ In a paired design with an additive random factor and and a fixed effect with two levels, the Bayes factors should be the same, regardless of whether we treat the fixed factor as a factor or as a dummy-coded covariate. ```{r} # create some data id = rnorm(10) eff = c(-1,1)*1 effCross = outer(id,eff,'+')+rnorm(length(id)*2) dat = data.frame(x=as.vector(effCross),id=factor(1:10), grp=factor(rep(1:2,each=length(id)))) dat$forReg = as.numeric(dat$grp)-1.5 idOnly = lmBF(x~id, data=dat, whichRandom="id") summary(aov(x~grp+Error(id/grp),data=dat)) ``` If the prior settings are consistent, these two numbers should be almost the same (within MC estimation error). ```{r} as.vector(lmBF(x ~ grp+id, data=dat, whichRandom="id")/idOnly) as.vector(lmBF(x ~ forReg+id, data=dat, whichRandom="id")/idOnly) ``` Independent t test and paired t test ------- Given the effect size $\hat{\delta}=t\sqrt{N_{eff}}$, where the effective sample size $N_{eff}$ is the sample size in the one-sample case, and \[ N_{eff} = \frac{N_1N_2}{N_1+N_2} \] in the two-sample case, the Bayes factors should be the same for the one-sample and two sample case, given the same observed effect size, save for the difference from the degrees of freedom that affects the shape of the noncentral $t$ likelihood. The difference from the degrees of freedom should get smaller for a given $t$ as $N_{eff}\rightarrow\infty$. ```{r} # create some data tstat = 3 NTwoSample = 500 effSampleSize = (NTwoSample^2)/(2*NTwoSample) effSize = tstat/sqrt(effSampleSize) # One sample x0 = rnorm(effSampleSize) x0 = (x0 - mean(x0))/sd(x0) + effSize t.test(x0) # Two sample x1 = rnorm(NTwoSample) x1 = (x1 - mean(x1))/sd(x1) x2 = x1 + effSize t.test(x2,x1) ``` These (log) Bayes factors should be approximately the same. ```{r} log(as.vector(ttestBF(x0))) log(as.vector(ttestBF(x=x1,y=x2))) ``` Paired samples and ANOVA ------ A paired sample $t$ test and a linear mixed effects model should broadly agree. The two are based on different models &mdash; the paired t test has the participant effects substracted out, while the linear mixed effects model has a prior on the participant effects &mdash; but we'd expect them to lead to the same conclusions. These two Bayes factors should be lead to similar conclusions. ```{r} # using the data previously defined t.test(x=dat$x[dat$grp==1],y=dat$x[dat$grp==2],paired=TRUE) as.vector(lmBF(x ~ grp+id, data=dat, whichRandom="id")/idOnly) as.vector(ttestBF(x=dat$x[dat$grp==1],y=dat$x[dat$grp==2],paired=TRUE)) ``` ------- *This document was compiled with version `r bfversion` of BayesFactor (`r rversion`).*
/scratch/gouwar.j/cran-all/cranData/BayesFactor/vignettes/priors.Rmd
#' @keywords internal "_PACKAGE" ## usethis namespace: start #' @importFrom stats rnorm ## usethis namespace: end NULL
/scratch/gouwar.j/cran-all/cranData/BayesFluxR/R/BayesFluxR-package.R
#' Installs Julia packages if needed #' #' @param ... strings of package names #' .install_pkg <- function(...){ for (pkg in as.character(list(...))) { JuliaCall::julia_install_package_if_needed(pkg) } } #' Obtain the status of the current Julia project .julia_project_status <- function(){ JuliaCall::julia_command("Pkg.status()") } #' Loads Julia packages #' #' @param ... strings of package names .using <- function(...){ for (pkg in list(...)) { JuliaCall::julia_library(pkg) } } #' Set a seed both in Julia and R #' #' @param seed seed to be used #' #' @return No return value, called for side effects. #' @examples #' \dontrun{ #' ## Needs previous call to `BayesFluxR_setup` which is time #' ## consuming and requires Julia and BayesFlux.jl #' BayesFluxR_setup(installJulia=TRUE, seed=123) #' .set_seed(123) #' } #' @export .set_seed <- function(seed){ JuliaCall::julia_command(sprintf("Random.seed!(%i);", seed)) set.seed(seed) message("Set the seed of Julia and R to ", seed) } #' Set up of the Julia environment needed for BayesFlux #' #' This will set up a new Julia environment in the current working #' directory or another folder if provided. This environment will #' then be set with all Julia dependencies needed. #' #' @param pkg_check (Default=TRUE) Check whether needed Julia packages #' are installed #' @param nthreads (Default=4) How many threads to make available to Julia #' @param seed Seed to be used. #' @param env_path The path to were the Julia environment should be created. #' By default, this is the current working directory. #' @param installJulia (Default=TRUE) Whether to install Julia #' @param ... Other parameters passed on to \code{\link[JuliaCall]{julia_setup}} #' #' @return No return value, called for side effects. #' @examples #' \dontrun{ #' ## Time consuming and requires Julia and BayesFlux.jl #' BayesFluxR_setup(installJulia=TRUE, seed=123) #' } #' @export BayesFluxR_setup <- function(pkg_check = TRUE, nthreads = 4, seed = NULL, env_path = getwd(), installJulia = FALSE, ...){ Sys.setenv(JULIA_NUM_THREADS = sprintf("%i", nthreads)) julia <- JuliaCall::julia_setup(installJulia = installJulia, ...) JuliaCall::julia_library("Pkg") sym.env <- get_random_symbol() JuliaCall::julia_assign(sym.env, env_path) JuliaCall::julia_command(sprintf("Pkg.activate(%s)", sym.env)) # pkgs_needed <- list("https://github.com/enweg/BayesFlux.jl.git", "Flux", "Distributions", "Random") pkgs_needed <- list("BayesFlux", "Flux", "Distributions", "Random", "DataFrames") if (pkg_check){ do.call(.install_pkg, pkgs_needed) } do.call(.using, c(c("BayesFlux", "Flux"), pkgs_needed[-c(1:2)])) if (!is.null(seed)) .set_seed(seed) } #' Chain various layers together to form a network #' #' @param ... Comma separated layers #' #' @return List with the following content #' \itemize{ #' \item juliavar - the julia variable containing the network #' \item specification - the string representation of the network #' \item nc - the julia variable for the network constructor #' } #' @examples #' \dontrun{ #' ## Needs previous call to `BayesFluxR_setup` which is time #' ## consuming and requires Julia and BayesFlux.jl #' BayesFluxR_setup(installJulia=TRUE, seed=123) #' Chain(LSTM(5, 5)) #' Chain(RNN(5, 5, "tanh")) #' Chain(Dense(1, 5)) #' } #' #' #' @export Chain <- function(...){ julia <- "Chain(" julia_layer_strings <- c() for (elem in list(...)){ # julia <- paste0(julia, elem$julia, ",") julia_layer_strings <- c(julia_layer_strings, elem$julia) } julia_layer_strings <- paste0(julia_layer_strings, collapse = ", ") julia <- paste0(julia, julia_layer_strings) julia <- paste0(julia, ")") sym.net <- get_random_symbol() JuliaCall::julia_command(sprintf("%s = %s", sym.net, julia)) # creating a NetworkConstructor sym.nc <- get_random_symbol() JuliaCall::julia_command(sprintf("%s = destruct(%s);", sym.nc, sym.net)) out <- list(juliavar = sym.net, specification = julia, nc = sym.nc) return(out) } #' Create a Bayesian Neural Network #' #' @param x For a Feedforward structure, this must be a matrix of dimensions #' variables x observations; For a recurrent structure, this must be a #' tensor of dimensions sequence_length x number_variables x number_sequences; #' In general, the last dimension is always the dimension over which will be batched. #' @param y A vector or matrix with observations. #' @param like Likelihood; See for example \code{\link{likelihood.feedforward_normal}} #' @param prior Prior; See for example \code{\link{prior.gaussian}} #' @param init Initialiser; See for example \code{\link{initialise.allsame}} #' #' @return List with the following content #' \itemize{ #' \item `juliavar` - the julia variable containing the BNN #' \item `juliacode` - the string representation of the BNN #' \item `x` - x #' \item `juliax` - julia variable holding x #' \item `y` - y #' \item `juliay` - julia variable holding y #' } #' @examples #' \dontrun{ #' ## Needs previous call to `BayesFluxR_setup` which is time #' ## consuming and requires Julia and BayesFlux.jl #' BayesFluxR_setup(installJulia=TRUE, seed=123) #' net <- Chain(Dense(5, 1)) #' like <- likelihood.feedforward_normal(net, Gamma(2.0, 0.5)) #' prior <- prior.gaussian(net, 0.5) #' init <- initialise.allsame(Normal(0, 0.5), like, prior) #' x <- matrix(rnorm(5*100), nrow = 5) #' y <- rnorm(100) #' bnn <- BNN(x, y, like, prior, init) #' sampler <- sampler.SGLD() #' ch <- mcmc(bnn, 10, 1000, sampler) #' } #' #' #' @export BNN <- function(x, y, like, prior, init){ sym.x <- get_random_symbol() sym.y <- get_random_symbol() JuliaCall::julia_assign(sym.x, x) JuliaCall::julia_command(sprintf("%s = Float32.(%s);", sym.x, sym.x)) JuliaCall::julia_assign(sym.y, y) JuliaCall::julia_command(sprintf("%s = Float32.(%s);", sym.y, sym.y)) juliavar <- get_random_symbol() juliacode <- sprintf("BNN(%s, %s, %s, %s, %s)", sym.x, sym.y, like$juliavar, prior$juliavar, init$juliavar) JuliaCall::julia_command(sprintf("%s = %s;", juliavar, juliacode)) out <- list(juliavar = juliavar, juliacode = juliacode, x = x, y = y, juliax = sym.x, juliay = sym.y) class(out) <- "BNN" return(out) } #' Obtain the total parameters of the BNN #' #' @param bnn A BNN formed using \code{\link{BNN}} #' #' @return The total number of parameters in the BNN #' @examples #' \dontrun{ #' ## Needs previous call to `BayesFluxR_setup` which is time #' ## consuming and requires Julia and BayesFlux.jl #' BayesFluxR_setup(installJulia=TRUE, seed=123) #' net <- Chain(Dense(5, 1)) #' like <- likelihood.feedforward_normal(net, Gamma(2.0, 0.5)) #' prior <- prior.gaussian(net, 0.5) #' init <- initialise.allsame(Normal(0, 0.5), like, prior) #' x <- matrix(rnorm(5*100), nrow = 5) #' y <- rnorm(100) #' bnn <- BNN(x, y, like, prior, init) #' BNN.totparams(bnn) #' } #' #' @export BNN.totparams <- function(bnn) { totparams <- JuliaCall::julia_eval(sprintf("%s.num_total_params", bnn$juliavar)) return(totparams) }
/scratch/gouwar.j/cran-all/cranData/BayesFluxR/R/BayesFluxR.R
#' Use the diagonal of sample covariance matrix as inverse mass matrix. #' #' @param adapt_steps Number of adaptation steps #' @param windowlength Lookback window length for calculation of covariance #' @param kappa How much to shrink towards the identity #' @param epsilon Small value to add to diagonal so as to avoid numerical #' non-pos-def problem #' #' @return list containing `juliavar` and `juliacode` and all given arguments. #' @examples #' \dontrun{ #' ## Needs previous call to `BayesFluxR_setup` which is time #' ## consuming and requires Julia and BayesFlux.jl #' BayesFluxR_setup(installJulia=TRUE, seed=123) #' net <- Chain(Dense(5, 1)) #' like <- likelihood.feedforward_normal(net, Gamma(2.0, 0.5)) #' prior <- prior.gaussian(net, 0.5) #' init <- initialise.allsame(Normal(0, 0.5), like, prior) #' x <- matrix(rnorm(5*100), nrow = 5) #' y <- rnorm(100) #' bnn <- BNN(x, y, like, prior, init) #' madapter <- madapter.DiagCov(100, 10) #' sampler <- sampler.GGMC(madapter = madapter) #' ch <- mcmc(bnn, 10, 1000, sampler) #' } #' #' @export madapter.DiagCov <- function(adapt_steps, windowlength, kappa = 0.5, epsilon = 1e-6){ juliavar <- get_random_symbol() juliacode <- sprintf("DiagCovMassAdapter(%i, %i; kappa = Float32(%e), epsilon = Float32(%e))", adapt_steps, windowlength, kappa, epsilon) JuliaCall::julia_command(sprintf("%s = %s", juliavar, juliacode)) out <- list(juliavar = juliavar, juliacode = juliacode, adapt_steps = adapt_steps, windowlength = windowlength, kappa = kappa, epsilon = epsilon) return(out) } #' Use a fixed mass matrix #' #' @param mat (Default=NULL); inverse mass matrix; If `NULL`, then #' identity matrix will be used #' #' @return list with `juliavar` and `juliacode` and given matrix or `NULL` #' @examples #' \dontrun{ #' ## Needs previous call to `BayesFluxR_setup` which is time #' ## consuming and requires Julia and BayesFlux.jl #' BayesFluxR_setup(installJulia=TRUE, seed=123) #' net <- Chain(Dense(5, 1)) #' like <- likelihood.feedforward_normal(net, Gamma(2.0, 0.5)) #' prior <- prior.gaussian(net, 0.5) #' init <- initialise.allsame(Normal(0, 0.5), like, prior) #' x <- matrix(rnorm(5*100), nrow = 5) #' y <- rnorm(100) #' bnn <- BNN(x, y, like, prior, init) #' madapter <- madapter.FixedMassMatrix() #' sampler <- sampler.GGMC(madapter = madapter) #' ch <- mcmc(bnn, 10, 1000, sampler) #' #' #' # Providing a non-sense weight matrix #' weight_matrix <- matrix(runif(BNN.totparams(bnn)^2, 0, 1), #' nrow = BNN.totparams(bnn)) #' madapter2 <- madapter.FixedMassMatrix(weight_matrix) #' sampler2 <- sampler.GGMC(madapter = madapter2) #' ch2 <- mcmc(bnn, 10, 1000, sampler2) #' } #' #' @export madapter.FixedMassMatrix <- function(mat = NULL){ juliacode <- "FixedMassAdapter()" if (!is.null(mat)){ sym.mat <- get_random_symbol() JuliaCall::julia_assign(sym.mat, mat) JuliaCall::julia_command(sprintf("%s = Float32.(%s)", sym.mat, sym.mat)) juliacode <- sprintf("FixedMassAdapter(%s)", sym.mat) } juliavar <- get_random_symbol() JuliaCall::julia_command(sprintf("%s = %s", juliavar, juliacode)) out <- list(juliavar = juliavar, juliacode = juliacode, minv = mat) return(out) } #' Use the full covariance matrix as inverse mass matrix #' #' @inheritParams madapter.DiagCov #' #' @return see \code{\link{madapter.DiagCov}} #' #' @examples #' \dontrun{ #' ## Needs previous call to `BayesFluxR_setup` which is time #' ## consuming and requires Julia and BayesFlux.jl #' BayesFluxR_setup(installJulia=TRUE, seed=123) #' net <- Chain(Dense(5, 1)) #' like <- likelihood.feedforward_normal(net, Gamma(2.0, 0.5)) #' prior <- prior.gaussian(net, 0.5) #' init <- initialise.allsame(Normal(0, 0.5), like, prior) #' x <- matrix(rnorm(5*100), nrow = 5) #' y <- rnorm(100) #' bnn <- BNN(x, y, like, prior, init) #' madapter <- madapter.FullCov(100, 10) #' sampler <- sampler.GGMC(madapter = madapter) #' ch <- mcmc(bnn, 10, 1000, sampler) #' } #' @export madapter.FullCov <- function(adapt_steps, windowlength, kappa = 0.5, epsilon = 1e-6){ juliavar <- get_random_symbol() juliacode <- sprintf("FullCovMassAdapter(%i, %i; kappa = Float32(%e), epsilon = Float32(%e))", adapt_steps, windowlength, kappa, epsilon) JuliaCall::julia_command(sprintf("%s = %s", juliavar, juliacode)) out <- list(juliavar = juliavar, juliacode = juliacode, adapt_steps = adapt_steps, windowlength = windowlength, kappa = kappa, epsilon = epsilon) return(out) } #' Use RMSProp to adapt the inverse mass matrix. #' #' Use RMSProp as a preconditions/mass matrix adapter. This was proposed in Li, C., #' Chen, C., Carlson, D., & Carin, L. (2016, February). Preconditioned stochastic #' gradient Langevin dynamics for deep neural networks. In Thirtieth AAAI #' Conference on Artificial Intelligence for the use in SGLD and related methods. #' #' @param adapt_steps number of adaptation steps #' @param lambda see above paper #' @param alpha see above paper #' #' @return list with `juliavar` and `juliacode` and all given arguments #' @examples #' \dontrun{ #' ## Needs previous call to `BayesFluxR_setup` which is time #' ## consuming and requires Julia and BayesFlux.jl #' BayesFluxR_setup(installJulia=TRUE, seed=123) #' net <- Chain(Dense(5, 1)) #' like <- likelihood.feedforward_normal(net, Gamma(2.0, 0.5)) #' prior <- prior.gaussian(net, 0.5) #' init <- initialise.allsame(Normal(0, 0.5), like, prior) #' x <- matrix(rnorm(5*100), nrow = 5) #' y <- rnorm(100) #' bnn <- BNN(x, y, like, prior, init) #' madapter <- madapter.RMSProp(100) #' sampler <- sampler.GGMC(madapter = madapter) #' ch <- mcmc(bnn, 10, 1000, sampler) #' } #' #' @export madapter.RMSProp <- function(adapt_steps, lambda = 1e-5, alpha = 0.99){ JuliaCall::julia_source(system.file("Julia/ascii-translate.jl", package = "BayesFluxR")) juliavar <- get_random_symbol() juliacode <- sprintf("ascii_RMSPropMassAdapter(%i; lambda = Float32(%e), alpha = Float32(%e))", adapt_steps, lambda, alpha) JuliaCall::julia_command(sprintf("%s = %s", juliavar, juliacode)) out <- list(juliavar = juliavar, juliacode = juliacode, lambda = lambda, alpha = alpha) return(out) }
/scratch/gouwar.j/cran-all/cranData/BayesFluxR/R/adapter-mass.R
#' Use a constant stepsize in mcmc #' #' @param l stepsize #' #' @return list with `juliavar`, `juliacode` and the given arguments #' @examples #' \dontrun{ #' ## Needs previous call to `BayesFluxR_setup` which is time #' ## consuming and requires Julia and BayesFlux.jl #' BayesFluxR_setup(installJulia=TRUE, seed=123) #' net <- Chain(Dense(5, 1)) #' like <- likelihood.feedforward_normal(net, Gamma(2.0, 0.5)) #' prior <- prior.gaussian(net, 0.5) #' init <- initialise.allsame(Normal(0, 0.5), like, prior) #' x <- matrix(rnorm(5*100), nrow = 5) #' y <- rnorm(100) #' bnn <- BNN(x, y, like, prior, init) #' sadapter <- sadapter.Const(1e-5) #' sampler <- sampler.GGMC(sadapter = sadapter) #' ch <- mcmc(bnn, 10, 1000, sampler) #' } #' #' @export sadapter.Const <- function(l){ juliavar <- get_random_symbol() juliacode <- sprintf("ConstantStepsize(Float32(%e))", l) JuliaCall::julia_command(sprintf("%s = %s", juliavar, juliacode)) out <- list(juliavar = juliavar, juliacode = juliacode, l = l) return(out) } #' Use Dual Averaging like in STAN to tune stepsize #' #' @param adapt_steps number of adaptation steps #' @param initial_stepsize initial stepsize #' @param target_accept target acceptance ratio #' @param gamma See STAN manual NUTS paper #' @param t0 See STAN manual or NUTS paper #' @param kappa See STAN manual or NUTS paper #' #' @return list with `juliavar`, `juliacode`, and all given arguments #' @examples #' \dontrun{ #' ## Needs previous call to `BayesFluxR_setup` which is time #' ## consuming and requires Julia and BayesFlux.jl #' BayesFluxR_setup(installJulia=TRUE, seed=123) #' net <- Chain(Dense(5, 1)) #' like <- likelihood.feedforward_normal(net, Gamma(2.0, 0.5)) #' prior <- prior.gaussian(net, 0.5) #' init <- initialise.allsame(Normal(0, 0.5), like, prior) #' x <- matrix(rnorm(5*100), nrow = 5) #' y <- rnorm(100) #' bnn <- BNN(x, y, like, prior, init) #' sadapter <- sadapter.DualAverage(100) #' sampler <- sampler.GGMC(sadapter = sadapter) #' ch <- mcmc(bnn, 10, 1000, sampler) #' } #' #' @export sadapter.DualAverage <- function(adapt_steps, initial_stepsize=1.0, target_accept = 0.65, gamma = 0.05, t0 = 10, kappa = 0.75) { juliavar <- get_random_symbol() juliacode <- sprintf("DualAveragingStepSize(Float32(%e); target_accept = Float32(%e), gamma = Float32(%e), t0 = %i, kappa = Float32(%e), adapt_steps = %i)", initial_stepsize, target_accept, gamma, t0, kappa, adapt_steps) JuliaCall::julia_command(sprintf("%s = %s", juliavar, juliacode)) out <- list(juliavar = juliavar, juliacode = juliacode, adapt_steps = adapt_steps, initial_stepsize = initial_stepsize, target_accept = target_accept, gamma = gamma, t0 = t0, kappa = kappa) return(out) }
/scratch/gouwar.j/cran-all/cranData/BayesFluxR/R/adapter-stepsize.R
#' Create a Gamma Prior #' #' Creates a Gamma prior in Julia using Distributions.jl #' #' @param shape shape parameter #' @param scale scale parameter #' #' @return A list with the following content #' \itemize{ #' \item juliavar - julia variable containing the distribution #' \item juliacode - julia code used to create the distribution #' } #' @examples #' \dontrun{ #' ## Needs previous call to `BayesFluxR_setup` which is time #' ## consuming and requires Julia and BayesFlux.jl #' BayesFluxR_setup(installJulia=TRUE, seed=123) #' net <- Chain(Dense(5, 1)) #' like <- likelihood.feedforward_normal(net, Gamma(2.0, 0.5)) #' } #' #' @export Gamma <- function(shape=2.0, scale=2.0){ juliacode <- sprintf("Gamma(%e, %e)", shape, scale) symbol <- get_random_symbol() JuliaCall::julia_command(sprintf("%s = %s;", symbol, juliacode)) out <- list(juliavar = symbol, juliacode = juliacode) return(out) } #' Create an Inverse-Gamma Prior #' #' Creates and Inverse Gamma prior in Julia using Distributions.jl #' #' @inheritParams Gamma #' @seealso \code{\link{Gamma}} #' #' @return A list with the following content #' \itemize{ #' \item juliavar - julia variable containing the distribution #' \item juliacode - julia code used to create the distribution #' } #' @examples #' \dontrun{ #' ## Needs previous call to `BayesFluxR_setup` which is time #' ## consuming and requires Julia and BayesFlux.jl #' BayesFluxR_setup(installJulia=TRUE, seed=123) #' net <- Chain(Dense(5, 1)) #' like <- likelihood.feedforward_normal(net, InverseGamma(2.0, 0.5)) #' } #' @export InverseGamma <- function(shape=2.0, scale=2.0){ juliacode <- sprintf("InverseGamma(%e, %e)", shape, scale) symbol <- get_random_symbol() JuliaCall::julia_command(sprintf("%s = %s;", symbol, juliacode)) out <- list(juliavar = symbol, juliacode = juliacode) return(out) } #' Create a Normal Prior #' #' Creates a Normal prior in Julia using Distributions.jl. This can #' then be truncated using \code{\link{Truncated}} to obtain a prior #' that could then be used as a variance prior. #' #' @param mu Mean #' @param sigma Standard Deviation #' #' @return see \code{\link{Gamma}} #' @examples #' \dontrun{ #' ## Needs previous call to `BayesFluxR_setup` which is time #' ## consuming and requires Julia and BayesFlux.jl #' BayesFluxR_setup(installJulia=TRUE, seed=123) #' net <- Chain(Dense(5, 1)) #' like <- likelihood.feedforward_normal(net, Truncated(Normal(0, 0.5), 0, Inf)) #' } #' #' @export Normal <- function(mu=0, sigma=1){ juliacode <- sprintf("Normal(%e, %e)", mu, sigma) symbol <- get_random_symbol() JuliaCall::julia_command(sprintf("%s = %s;", symbol, juliacode)) out <- list(juliavar = symbol, juliacode = juliacode) return(out) } #' Truncates a Distribution #' #' Truncates a Julia Distribution between `lower` and `upper`. #' #' @param dist A Julia Distribution created using \code{\link{Gamma}}, #' \code{\link{InverseGamma}} ... #' @param lower lower bound #' @param upper upper bound #' #' @return see \code{\link{Gamma}} #' @examples #' \dontrun{ #' ## Needs previous call to `BayesFluxR_setup` which is time #' ## consuming and requires Julia and BayesFlux.jl #' BayesFluxR_setup(installJulia=TRUE, seed=123) #' net <- Chain(Dense(5, 1)) #' like <- likelihood.feedforward_normal(net, Truncated(Normal(0, 0.5), 0, Inf)) #' } #' #' @export Truncated <- function(dist, lower, upper){ juliacode <- sprintf("Truncated(%s, %e, %e)", dist$juliacode, lower, upper) symbol <- get_random_symbol() JuliaCall::julia_command(sprintf("%s = %s;", symbol, juliacode)) out <- list(juliavar = symbol, juliacode = juliacode) return(out) }
/scratch/gouwar.j/cran-all/cranData/BayesFluxR/R/distributions.R
#' Initialises all parameters of the network, all hyper parameters #' of the prior and all additional parameters #' of the likelihood by drawing random values from `dist`. #' #' @param dist A distribution; See for example \code{\link{Normal}} #' @param like A likelihood; See for example \code{\link{likelihood.feedforward_normal}} #' @param prior A prior; See for example \code{\link{prior.gaussian}} #' #' @return A list containing the following #' \itemize{ #' \item `juliavar` - julia variable storing the initialiser #' \item `juliacode` - julia code used to create the initialiser #' } #' @examples #' \dontrun{ #' ## Needs previous call to `BayesFluxR_setup` which is time #' ## consuming and requires Julia and BayesFlux.jl #' BayesFluxR_setup(installJulia=TRUE, seed=123) #' net <- Chain(Dense(5, 1)) #' like <- likelihood.feedforward_normal(net, Gamma(2.0, 0.5)) #' prior <- prior.gaussian(net, 0.5) #' init <- initialise.allsame(Normal(0, 0.5), like, prior) #' x <- matrix(rnorm(5*100), nrow = 5) #' y <- rnorm(100) #' bnn <- BNN(x, y, like, prior, init) #' BNN.totparams(bnn) #' } #' #' @export initialise.allsame <- function(dist, like, prior){ juliacode <- sprintf("InitialiseAllSame(%s, %s, %s)", dist$juliavar, like$juliavar, prior$juliavar) juliavar <- get_random_symbol() JuliaCall::julia_command(sprintf("%s = %s;", juliavar, juliacode)) out <- list(juliavar = juliavar, juliacode = juliacode) return(out) }
/scratch/gouwar.j/cran-all/cranData/BayesFluxR/R/initialisers.R
#' Create a Dense layer with `in_size` inputs and `out_size` outputs using `act` activation function #' #' @param in_size Input size #' @param out_size Output size #' @param act Activation function #' #' @return A list with the following content #' \itemize{ #' \item in_size - Input Size #' \item out_size - Output Size #' \item activation - Activation Function #' \item julia - Julia code representing the Layer #' } #' #' @examples #' \dontrun{ #' ## Needs previous call to `BayesFluxR_setup` which is time #' ## consuming and requires Julia and BayesFlux.jl #' BayesFluxR_setup(installJulia=TRUE, seed=123) #' net <- Chain(Dense(5, 5, "relu")) #' } #' #' @export Dense <- function(in_size, out_size, act = c("identity", "sigmoid", "tanh", "relu")) { act <- match.arg(act) juliacode <- sprintf("Dense(%i, %i, %s)", in_size, out_size, act) out <- list( in_size = in_size, out_size = out_size, activation = act, julia = juliacode ) return(out) } #' Create a RNN layer with `in_size` input, `out_size` hidden state and `act` activation function #' #' @inherit Dense params return #' @seealso \code{\link{Dense}} #' @examples #' \dontrun{ #' ## Needs previous call to `BayesFluxR_setup` which is time #' ## consuming and requires Julia and BayesFlux.jl #' BayesFluxR_setup(installJulia=TRUE, seed=123) #' net <- Chain(RNN(5, 5, "tanh")) #' } #' #' @export RNN <- function(in_size, out_size, act = c("sigmoid", "tanh", "identity", "relu")){ act <- match.arg(act) juliacode <- sprintf("RNN(%i, %i, %s)", in_size, out_size, act) out <- list( in_size = in_size, out_size = out_size, activation = act, julia = juliacode ) } #' Create an LSTM layer with `in_size` input size, and `out_size` hidden state size #' #' @inherit Dense params #' @return A list with the following content #' \itemize{ #' \item in_size - Input Size #' \item out_size - Output Size #' \item julia - Julia code representing the Layer #' } #' @seealso \code{\link{Dense}} #' @examples #' \dontrun{ #' ## Needs previous call to `BayesFluxR_setup` which is time #' ## consuming and requires Julia and BayesFlux.jl #' BayesFluxR_setup(installJulia=TRUE, seed=123) #' net <- Chain(LSTM(5, 5)) #' } #' #' @export LSTM <- function(in_size, out_size){ juliacode <- sprintf("LSTM(%i, %i)", in_size, out_size) out <- list( in_size = in_size, out_size = out_size, julia = juliacode ) return(out) }
/scratch/gouwar.j/cran-all/cranData/BayesFluxR/R/layers.R
###################################################################### #### Feedforward Lkelihoods ########################################## #' Use a Normal likelihood for a Feedforward network #' #' This creates a likelihood of the form #' \deqn{y_i \sim Normal(net(x_i), \sigma)\;\forall i=1,...,N} #' where the \eqn{x_i} is fed through the network in a standard feedforward way. #' #' @param chain Network structure obtained using \code{link{Chain}} #' @param sig_prior A prior distribution for sigma defined using #' \code{\link{Gamma}}, \code{link{InverGamma}}, #' \code{\link{Truncated}}, \code{\link{Normal}} #' #' @return A list containing the following #' \itemize{ #' \item juliavar - julia variable containing the likelihood #' \item juliacode - julia code used to create the likelihood #' } #' @examples #' \dontrun{ #' ## Needs previous call to `BayesFluxR_setup` which is time #' ## consuming and requires Julia and BayesFlux.jl #' BayesFluxR_setup(installJulia=TRUE, seed=123) #' net <- Chain(Dense(5, 1)) #' like <- likelihood.feedforward_normal(net, Gamma(2.0, 0.5)) #' prior <- prior.gaussian(net, 0.5) #' init <- initialise.allsame(Normal(0, 0.5), like, prior) #' x <- matrix(rnorm(5*100), nrow = 5) #' y <- rnorm(100) #' bnn <- BNN(x, y, like, prior, init) #' BNN.totparams(bnn) #' } #' #' @export likelihood.feedforward_normal <- function(chain, sig_prior){ juliacode <- sprintf("FeedforwardNormal(%s, %s)", chain$nc, sig_prior$juliavar) symbol <- get_random_symbol() JuliaCall::julia_command(sprintf("%s = %s;", symbol, juliacode)) out <- list(juliavar = symbol, juliacode = juliacode) return(out) } #' Use a t-Distribution likelihood for a Feedforward network #' #' This creates a likelihood of the form #' \deqn{\frac{y_i - net(x_i)}{\sigma} \sim T_\nu\;\forall i=1,...,N} #' where the \eqn{x_i} is fed through the network in the standard feedforward way. #' #' @inheritParams likelihood.feedforward_normal #' @param nu DF of TDist #' #' @return see \code{\link{likelihood.feedforward_normal}} #' @examples #' \dontrun{ #' ## Needs previous call to `BayesFluxR_setup` which is time #' ## consuming and requires Julia and BayesFlux.jl #' BayesFluxR_setup(installJulia=TRUE, seed=123) #' net <- Chain(Dense(5, 1)) #' like <- likelihood.feedforward_tdist(net, Gamma(2.0, 0.5), nu=8) #' prior <- prior.gaussian(net, 0.5) #' init <- initialise.allsame(Normal(0, 0.5), like, prior) #' x <- matrix(rnorm(5*100), nrow = 5) #' y <- rnorm(100) #' bnn <- BNN(x, y, like, prior, init) #' BNN.totparams(bnn) #' } #' #' @export likelihood.feedforward_tdist <- function(chain, sig_prior, nu=30){ juliacode <- sprintf("BayesFlux.FeedforwardTDist(%s, %s, Float32(%e))", chain$nc, sig_prior$juliavar, nu) symbol <- get_random_symbol() JuliaCall::julia_command(sprintf("%s = %s;", symbol, juliacode)) out <- list(juliavar = symbol, juliacode = juliacode) return(out) } ###################################################################### #### Seq. To One ##################################################### #' Use a Normal likelihood for a seq-to-one recurrent network #' #' This creates a likelihood of the form #' \deqn{y_i \sim Normal(net(x_i), \sigma), i=1,...,N} #' Here \eqn{x_i} is a subsequence which will be fed through the recurrent #' network to obtain the final output \eqn{net(x_i) = \hat{y}_i}. Thus, if #' one has a single time series, and splits the single time series into subsequences #' of length K which are then used to predict the next output of the time series, then #' each \eqn{x_i} consists of K consecutive observations of the time series. In a sense #' one constraints the maximum memory length of the network this way. #' #' @inheritParams likelihood.feedforward_normal #' @return see \code{\link{likelihood.feedforward_normal}} #' @examples #' \dontrun{ #' ## Needs previous call to `BayesFluxR_setup` which is time #' ## consuming and requires Julia and BayesFlux.jl #' BayesFluxR_setup(installJulia=TRUE, seed=123) #' net <- Chain(RNN(5, 1)) #' like <- likelihood.seqtoone_normal(net, Gamma(2.0, 0.5)) #' prior <- prior.gaussian(net, 0.5) #' init <- initialise.allsame(Normal(0, 0.5), like, prior) #' x <- array(rnorm(5*100*10), dim=c(10,5,100)) #' y <- rnorm(100) #' bnn <- BNN(x, y, like, prior, init) #' BNN.totparams(bnn) #' } #' #' @export likelihood.seqtoone_normal <- function(chain, sig_prior){ juliacode <- sprintf("BayesFlux.SeqToOneNormal(%s, %s)", chain$nc, sig_prior$juliavar) sym <- get_random_symbol() JuliaCall::julia_command(sprintf("%s = %s;", sym, juliacode)) out <- list(juliavar = sym, juliacode = juliacode) return(out) } #' Use a T-likelihood for a seq-to-one recurrent network. #' #' See \code{\link{likelihood.seqtoone_normal}} and \code{\link{likelihood.feedforward_tdist}} #' for details, #' #' @inheritParams likelihood.feedforward_tdist #' #' @return see \code{\link{likelihood.feedforward_normal}} #' @examples #' \dontrun{ #' ## Needs previous call to `BayesFluxR_setup` which is time #' ## consuming and requires Julia and BayesFlux.jl #' BayesFluxR_setup(installJulia=TRUE, seed=123) #' net <- Chain(RNN(5, 1)) #' like <- likelihood.seqtoone_tdist(net, Gamma(2.0, 0.5), nu=5) #' prior <- prior.gaussian(net, 0.5) #' init <- initialise.allsame(Normal(0, 0.5), like, prior) #' x <- array(rnorm(5*100*10), dim=c(10,5,100)) #' y <- rnorm(100) #' bnn <- BNN(x, y, like, prior, init) #' BNN.totparams(bnn) #' } #' #' @export likelihood.seqtoone_tdist <- function(chain, sig_prior, nu = 30){ juliacode <- sprintf("BayesFlux.SeqToOneTDist(%s, %s, Float32(%e))", chain$nc, sig_prior$juliavar, nu) sym <- get_random_symbol() JuliaCall::julia_command(sprintf("%s = %s;", sym, juliacode)) out <- list(juliavar = sym, juliacode = juliacode) return(out) }
/scratch/gouwar.j/cran-all/cranData/BayesFluxR/R/likelihoods.R
#' Stochastic Gradient Langevin Dynamics as proposed in Welling, M., & Teh, Y. W. #' (n.d.). Bayesian Learning via Stochastic Gradient Langevin Dynamics. 8. #' #' Stepsizes will be adapted according to #' \deqn{a(b+t)^{-\gamma}} #' #' @param stepsize_a See eq. above #' @param stepsize_b See eq. above #' @param stepsize_gamma see eq. above #' @param min_stepsize Do not decrease stepsize beyond this #' #' @return a list with `juliavar`, `juliacode`, and all given arguments #' @examples #' \dontrun{ #' ## Needs previous call to `BayesFluxR_setup` which is time #' ## consuming and requires Julia and BayesFlux.jl #' BayesFluxR_setup(installJulia=TRUE, seed=123) #' net <- Chain(Dense(5, 1)) #' like <- likelihood.feedforward_normal(net, Gamma(2.0, 0.5)) #' prior <- prior.gaussian(net, 0.5) #' init <- initialise.allsame(Normal(0, 0.5), like, prior) #' x <- matrix(rnorm(5*100), nrow = 5) #' y <- rnorm(100) #' bnn <- BNN(x, y, like, prior, init) #' sampler <- sampler.SGLD() #' ch <- mcmc(bnn, 10, 1000, sampler) #' } #' #' @export sampler.SGLD <- function(stepsize_a = 0.1, stepsize_b = 0, stepsize_gamma = 0.55, min_stepsize = -Inf){ JuliaCall::julia_source(system.file("Julia/ascii-translate.jl", package = "BayesFluxR")) juliavar <- get_random_symbol() juliacode <- sprintf("ascii_SGLD(; stepsize_a = Float32(%e), stepsize_b = Float32(%e), stepsize_gamma = Float32(%e), min_stepsize = Float32(%s))", stepsize_a, stepsize_b, stepsize_gamma, min_stepsize) JuliaCall::julia_command(sprintf("%s = %s;", juliavar, juliacode)) out <- list(juliavar = juliavar, juliacode = juliacode, stepsize_a = stepsize_a, stepsize_b = stepsize_b, stepsize_gamma = stepsize_gamma) return(out) } #' Adaptive Metropolis Hastings as introduced in #' #' Haario, H., Saksman, E., & Tamminen, J. (2001). An adaptive Metropolis #' algorithm. Bernoulli, 223-242. #' #' @param bnn BNN obtained using \code{\link{BNN}} #' @param t0 Number of iterators before covariance adaptation will be started. #' Also the lookback period for covariance adaptation. #' @param sd Tuning parameter; See paper #' @param eps Used for numerical reasons. Increase this if pos-def-error thrown. #' #' @return a list with `juliavar`, `juliacode`, and all given arguments #' @examples #' \dontrun{ #' ## Needs previous call to `BayesFluxR_setup` which is time #' ## consuming and requires Julia and BayesFlux.jl #' BayesFluxR_setup(installJulia=TRUE, seed=123) #' net <- Chain(Dense(5, 1)) #' like <- likelihood.feedforward_normal(net, Gamma(2.0, 0.5)) #' prior <- prior.gaussian(net, 0.5) #' init <- initialise.allsame(Normal(0, 0.5), like, prior) #' x <- matrix(rnorm(5*100), nrow = 5) #' y <- rnorm(100) #' bnn <- BNN(x, y, like, prior, init) #' sampler <- sampler.AdaptiveMH(bnn, 10, 1) #' ch <- mcmc(bnn, 10, 1000, sampler) #' } #' #' @export sampler.AdaptiveMH <- function(bnn, t0, sd, eps=1e-6){ C0 = diag(x = rep(1, BNN.totparams(bnn))) sym.C0 = get_random_symbol() JuliaCall::julia_assign(sym.C0, C0) JuliaCall::julia_command(sprintf("%s = Float32.(%s);", sym.C0, sym.C0)) juliavar <- get_random_symbol() juliacode <- sprintf("AdaptiveMH(%s, %i, Float32(%e), Float32(%e))", sym.C0, t0, sd, eps) JuliaCall::julia_command(sprintf("%s = %s;", juliavar, juliacode)) out <- list(juliavar = juliavar, juliacode = juliacode, C0 = C0, t0 = t0, sd = sd, eps = eps) return(out) } #' Gradient Guided Monte Carlo #' #' Proposed in Garriga-Alonso, A., & Fortuin, V. (2021). Exact langevin dynamics #' with stochastic gradients. arXiv preprint arXiv:2102.01691. #' #' @param beta See paper #' @param l stepsize #' @param sadapter Stepsize adapter; Not used in original paper #' @param madapter Mass adapter; Not used in ogirinal paper #' @param steps Number of steps before accept/reject #' #' @return a list with `juliavar`, `juliacode` and all provided arguments. #' @examples #' \dontrun{ #' ## Needs previous call to `BayesFluxR_setup` which is time #' ## consuming and requires Julia and BayesFlux.jl #' BayesFluxR_setup(installJulia=TRUE, seed=123) #' net <- Chain(Dense(5, 1)) #' like <- likelihood.feedforward_normal(net, Gamma(2.0, 0.5)) #' prior <- prior.gaussian(net, 0.5) #' init <- initialise.allsame(Normal(0, 0.5), like, prior) #' x <- matrix(rnorm(5*100), nrow = 5) #' y <- rnorm(100) #' bnn <- BNN(x, y, like, prior, init) #' sadapter <- sadapter.DualAverage(100) #' sampler <- sampler.GGMC(sadapter = sadapter) #' ch <- mcmc(bnn, 10, 1000, sampler) #' } #' #' @export sampler.GGMC <- function(beta = 0.1, l = 1.0, sadapter = sadapter.DualAverage(1000), madapter = madapter.FixedMassMatrix(), steps = 3){ JuliaCall::julia_source(system.file("Julia/ascii-translate.jl", package = "BayesFluxR")) juliavar <- get_random_symbol() juliacode <- sprintf("ascii_GGMC(; beta = Float32(%e), l = Float32(%e), sadapter = %s, madapter = %s, steps = %i)", beta, l, sadapter$juliavar, madapter$juliavar, steps) JuliaCall::julia_command(sprintf("%s = %s;", juliavar, juliacode)) out <- list(juliavar = juliavar, juliacode = juliacode, beta = beta, l = l, sadapter = sadapter, madapter = madapter, steps = steps) return(out) } #' Standard Hamiltonian Monte Carlo (Hybrid Monte Carlo). #' #' Allows for the use of stochastic gradients, but the validity of doing so is not clear. #' #' This is motivated by parts of the discussion in #' Neal, R. M. (1996). Bayesian Learning for Neural Networks (Vol. 118). Springer #' New York. https://doi.org/10.1007/978-1-4612-0745-0 #' #' @param l stepsize #' @param path_len number of leapfrog steps #' @param sadapter Stepsize adapter #' @param madapter Mass adapter #' #' @return a list with `juliavar`, `juliacode`, and all given arguments #' @examples #' \dontrun{ #' ## Needs previous call to `BayesFluxR_setup` which is time #' ## consuming and requires Julia and BayesFlux.jl #' BayesFluxR_setup(installJulia=TRUE, seed=123) #' net <- Chain(Dense(5, 1)) #' like <- likelihood.feedforward_normal(net, Gamma(2.0, 0.5)) #' prior <- prior.gaussian(net, 0.5) #' init <- initialise.allsame(Normal(0, 0.5), like, prior) #' x <- matrix(rnorm(5*100), nrow = 5) #' y <- rnorm(100) #' bnn <- BNN(x, y, like, prior, init) #' sadapter <- sadapter.DualAverage(100) #' sampler <- sampler.HMC(1e-3, 3, sadapter = sadapter) #' ch <- mcmc(bnn, 10, 1000, sampler) #' } #' #' @export sampler.HMC <- function(l, path_len, sadapter = sadapter.DualAverage(1000), madapter = madapter.FixedMassMatrix()){ juliavar <- get_random_symbol() juliacode <- sprintf("HMC(Float32(%e), %i; sadapter = %s, madapter = %s)", l, path_len, sadapter$juliavar, madapter$juliavar) JuliaCall::julia_command(sprintf("%s = %s;", juliavar, juliacode)) out <- list(juliavar = juliavar, juliacode = juliacode, l = l, path_len = path_len, sadapter = sadapter, madapter = madapter) return(out) } #' Stochastic Gradient Nose-Hoover Thermostat as proposed in #' #' Proposed in Leimkuhler, B., & Shang, X. (2016). Adaptive thermostats for noisy #' gradient systems. SIAM Journal on Scientific Computing, 38(2), A712-A736. #' #' This is similar to SGNHT as proposed in #' Ding, N., Fang, Y., Babbush, R., Chen, C., Skeel, R. D., & Neven, H. (2014). #' Bayesian sampling using stochastic gradient thermostats. Advances in neural #' information processing systems, 27. #' #' @param l Stepsize #' @param sigmaA Diffusion factor #' @param xi Thermostat #' @param mu Free parameter of thermostat #' @param madapter Mass Adapter; Not used in original paper and thus #' has no theoretical backing #' #' @return a list with `juliavar`, `juliacode` and all arguments provided #' @examples #' \dontrun{ #' ## Needs previous call to `BayesFluxR_setup` which is time #' ## consuming and requires Julia and BayesFlux.jl #' BayesFluxR_setup(installJulia=TRUE, seed=123) #' net <- Chain(Dense(5, 1)) #' like <- likelihood.feedforward_normal(net, Gamma(2.0, 0.5)) #' prior <- prior.gaussian(net, 0.5) #' init <- initialise.allsame(Normal(0, 0.5), like, prior) #' x <- matrix(rnorm(5*100), nrow = 5) #' y <- rnorm(100) #' bnn <- BNN(x, y, like, prior, init) #' sampler <- sampler.SGNHTS(1e-3) #' ch <- mcmc(bnn, 10, 1000, sampler) #' } #' #' @export sampler.SGNHTS <- function(l, sigmaA = 1, xi = 1, mu = 1, madapter = madapter.FixedMassMatrix()){ JuliaCall::julia_source(system.file("Julia/ascii-translate.jl", package = "BayesFluxR")) juliavar <- get_random_symbol() juliacode <- sprintf("ascii_SGNHTS(Float32(%e), Float32(%e); xi = Float32(%e), mu = Float32(%e), madapter = %s)", l, sigmaA, xi, mu, madapter$juliavar) JuliaCall::julia_command(sprintf("%s = %s;", juliavar, juliacode)) out <- list(juliavar = juliavar, juliacode = juliacode, l = l, sigmaA = sigmaA, xi = xi, mu = mu, madapter = madapter) return(out) } #' Sample from a BNN using MCMC #' #' @param bnn A BNN obtained using \code{\link{BNN}} #' @param batchsize batchsize to use; Most samplers allow for batching. #' For some, theoretical justifications are missing (HMC) #' @param numsamples Number of mcmc samples #' @param sampler Sampler to use; See for example \code{\link{sampler.SGLD}} and #' all other samplers start with `sampler.` and are thus easy to identity. #' @param continue_sampling Do not start new sampling, but rather continue sampling #' For this, numsamples must be greater than the already sampled number. #' @param start_value Values to start from. By default these will be #' sampled using the initialiser in `bnn`. #' #' @return a list containing the `samples` and the `sampler` used. #' @examples #' \dontrun{ #' ## Needs previous call to `BayesFluxR_setup` which is time #' ## consuming and requires Julia and BayesFlux.jl #' BayesFluxR_setup(installJulia=TRUE, seed=123) #' net <- Chain(Dense(5, 1)) #' like <- likelihood.feedforward_normal(net, Gamma(2.0, 0.5)) #' prior <- prior.gaussian(net, 0.5) #' init <- initialise.allsame(Normal(0, 0.5), like, prior) #' x <- matrix(rnorm(5*100), nrow = 5) #' y <- rnorm(100) #' bnn <- BNN(x, y, like, prior, init) #' sampler <- sampler.SGNHTS(1e-3) #' ch <- mcmc(bnn, 10, 1000, sampler) #' } #' #' @export mcmc <- function(bnn, batchsize, numsamples, sampler = sampler.SGLD(stepsize_a = 1.0), continue_sampling = FALSE, start_value = NULL){ continue_sampling <- ifelse(continue_sampling, "true", "false") juliacode <- sprintf("ascii_mcmc(%s, %i, %i, %s; continue_sampling = %s)", bnn$juliavar, batchsize, numsamples, sampler$juliavar, continue_sampling) if (!is.null(start_value)){ sym.start_value <- get_random_symbol() JuliaCall::julia_assign(sym.start_value, start_value) JuliaCall::julia_command(sprintf("%s = Float32.(%s);", sym.start_value, sym.start_value)) juliacode <- sprintf("ascii_mcmc(%s, %i, %i, %s; continue_sampling = %s, start_value = %s)", bnn$juliavar, batchsize, numsamples, sampler$juliavar, continue_sampling, sym.start_value) } samples <- JuliaCall::julia_eval(sprintf("%s",juliacode)) return(list(samples = samples, sampler = sampler)) }
/scratch/gouwar.j/cran-all/cranData/BayesFluxR/R/mcmc.R
# If you want to implement more, check out the documentation for # Flux at https://fluxml.ai/Flux.jl/stable/training/optimisers/ # and follow the examples below. #' Standard gradient descent #' #' @param eta stepsize #' #' @return list containing #' \itemize{ #' \item `julivar` - julia variable holding the optimiser #' \item `juliacode` - string representation #' } #' @examples #' \dontrun{ #' ## Needs previous call to `BayesFluxR_setup` which is time #' ## consuming and requires Julia and BayesFlux.jl #' BayesFluxR_setup(installJulia=TRUE, seed=123) #' net <- Chain(Dense(5, 1)) #' like <- likelihood.feedforward_normal(net, Gamma(2.0, 0.5)) #' prior <- prior.gaussian(net, 0.5) #' init <- initialise.allsame(Normal(0, 0.5), like, prior) #' x <- matrix(rnorm(5*100), nrow = 5) #' y <- rnorm(100) #' bnn <- BNN(x, y, like, prior, init) #' find_mode(bnn, opt.Descent(1e-5), 10, 100) #' } #' #' @export opt.Descent <- function(eta = 0.1){ juliavar <- get_random_symbol() juliacode <- sprintf("Flux.Descent(%e)", eta) JuliaCall::julia_command(sprintf("%s = %s;", juliavar, juliacode)) out <- list(juliavar = juliavar, juliacode = juliacode) return(out) } #' ADAM optimiser #' #' @param eta stepsize #' @param beta momentum decays; must be a list of length 2 #' @param eps Flux does not document this #' #' @return see \code{\link{opt.Descent}} #' @examples #' \dontrun{ #' ## Needs previous call to `BayesFluxR_setup` which is time #' ## consuming and requires Julia and BayesFlux.jl #' BayesFluxR_setup(installJulia=TRUE, seed=123) #' net <- Chain(Dense(5, 1)) #' like <- likelihood.feedforward_normal(net, Gamma(2.0, 0.5)) #' prior <- prior.gaussian(net, 0.5) #' init <- initialise.allsame(Normal(0, 0.5), like, prior) #' x <- matrix(rnorm(5*100), nrow = 5) #' y <- rnorm(100) #' bnn <- BNN(x, y, like, prior, init) #' find_mode(bnn, opt.ADAM(), 10, 100) #' } #' #' @export opt.ADAM <- function(eta = 0.001, beta = c(0.9, 0.999), eps = 1e-8){ juliavar <- get_random_symbol() juliacode <- sprintf("Flux.ADAM(%e, (%e, %e), %e)", eta, beta[1], beta[2], eps) JuliaCall::julia_command(sprintf("%s = %s;", juliavar, juliacode)) out <- list(juliavar = juliavar, juliacode = juliacode) return(out) } #' RMSProp optimiser #' #' @param eta learning rate #' @param rho momentum #' @param eps not documented by Flux #' #' @return see \code{\link{opt.Descent}} #' @examples #' \dontrun{ #' ## Needs previous call to `BayesFluxR_setup` which is time #' ## consuming and requires Julia and BayesFlux.jl #' BayesFluxR_setup(installJulia=TRUE, seed=123) #' net <- Chain(Dense(5, 1)) #' like <- likelihood.feedforward_normal(net, Gamma(2.0, 0.5)) #' prior <- prior.gaussian(net, 0.5) #' init <- initialise.allsame(Normal(0, 0.5), like, prior) #' x <- matrix(rnorm(5*100), nrow = 5) #' y <- rnorm(100) #' bnn <- BNN(x, y, like, prior, init) #' find_mode(bnn, opt.RMSProp(), 10, 100) #' } #' #' @export opt.RMSProp <- function(eta = 0.001, rho = 0.9, eps = 1e-8){ juliavar <- get_random_symbol() juliacode <- sprintf("Flux.RMSProp(%e, %e, %e)", eta, rho, eps) JuliaCall::julia_command(sprintf("%s = %s;", juliavar, juliacode)) out <- list(juliavar = juliavar, juliacode = juliacode) return(out) } #' Find the MAP of a BNN using SGD #' #' @param bnn a BNN obtained using \code{\link{BNN}} #' @param optimiser an optimiser. These start with `opt.`. #' See for example \code{\link{opt.ADAM}} #' @param batchsize batch size #' @param epochs number of epochs to run for #' #' @return Returns a vector. Use \code{\link{posterior_predictive}} #' to obtain a prediction using this MAP estimate. #' @examples #' \dontrun{ #' ## Needs previous call to `BayesFluxR_setup` which is time #' ## consuming and requires Julia and BayesFlux.jl #' BayesFluxR_setup(installJulia=TRUE, seed=123) #' net <- Chain(Dense(5, 1)) #' like <- likelihood.feedforward_normal(net, Gamma(2.0, 0.5)) #' prior <- prior.gaussian(net, 0.5) #' init <- initialise.allsame(Normal(0, 0.5), like, prior) #' x <- matrix(rnorm(5*100), nrow = 5) #' y <- rnorm(100) #' bnn <- BNN(x, y, like, prior, init) #' find_mode(bnn, opt.RMSProp(), 10, 100) #' } #' #' @export find_mode <- function(bnn, optimiser, batchsize, epochs){ juliacode <- sprintf("find_mode(%s, %i, %i, FluxModeFinder(%s, %s); showprogress = true)", bnn$juliavar, batchsize, epochs, bnn$juliavar, optimiser$juliavar) return(JuliaCall::julia_eval(juliacode)) }
/scratch/gouwar.j/cran-all/cranData/BayesFluxR/R/mode-finding.R
#' Sample from the prior predictive of a Bayesian Neural Network #' #' @param bnn BNN obtained using \code{\link{BNN}} #' @param n Number of samples #' #' @return matrix of prior predictive samples; Columns are the different samples #' @examples #' \dontrun{ #' ## Needs previous call to `BayesFluxR_setup` which is time #' ## consuming and requires Julia and BayesFlux.jl #' BayesFluxR_setup(installJulia=TRUE, seed=123) #' net <- Chain(Dense(5, 1)) #' like <- likelihood.feedforward_normal(net, Gamma(2.0, 0.5)) #' prior <- prior.gaussian(net, 0.5) #' init <- initialise.allsame(Normal(0, 0.5), like, prior) #' x <- matrix(rnorm(5*100), nrow = 5) #' y <- rnorm(100) #' bnn <- BNN(x, y, like, prior, init) #' pp <- prior_predictive(bnn, n = 10) #' } #' #' @export prior_predictive <- function(bnn, n = 1){ if (!JuliaCall::julia_exists("prior_predict_feedforward")){ JuliaCall::julia_source(system.file("Julia/helpers-prior-predictive.jl", package = "BayesFluxR")) } if (ndims(bnn$x) == 2){ values <- JuliaCall::julia_eval(sprintf("reduce(hcat, sample_prior_predictive(%s, prior_predict_feedforward(%s), %i))", bnn$juliavar, bnn$juliavar, n)) return(values) } if (ndims(bnn$x) == 3){ values <- JuliaCall::julia_eval(sprintf("reduce(hcat, sample_prior_predictive(%s, prior_predict_seqtoone(%s), %i))", bnn$juliavar, bnn$juliavar, n)) return(values) } stop("Prior predictive not supported for your shape of x") } #' Draw from the posterior predictive distribution #' #' @param bnn a BNN obtained using \code{link{BNN}} #' @param posterior_samples a vector or matrix containing posterior #' samples. This can be obtained using \code{\link{mcmc}}, or \code{\link{bayes_by_backprop}} #' or \code{\link{find_mode}}. #' @param x input variables. If `NULL` (default), training values will be used. #' #' @return A matrix whose columns are the posterior predictive draws. #' @examples #' \dontrun{ #' ## Needs previous call to `BayesFluxR_setup` which is time #' ## consuming and requires Julia and BayesFlux.jl #' BayesFluxR_setup(installJulia=TRUE, seed=123) #' net <- Chain(Dense(5, 1)) #' like <- likelihood.feedforward_normal(net, Gamma(2.0, 0.5)) #' prior <- prior.gaussian(net, 0.5) #' init <- initialise.allsame(Normal(0, 0.5), like, prior) #' x <- matrix(rnorm(5*100), nrow = 5) #' y <- rnorm(100) #' bnn <- BNN(x, y, like, prior, init) #' sampler <- sampler.SGLD() #' ch <- mcmc(bnn, 10, 1000, sampler) #' pp <- posterior_predictive(bnn, ch$samples) #' } #' #' @export posterior_predictive <- function(bnn, posterior_samples, x = NULL){ if (is.null(x)){ x <- bnn$x } sym.x <- get_random_symbol() JuliaCall::julia_assign(sym.x, x) JuliaCall::julia_command(sprintf("%s = Float32.(%s);", sym.x, sym.x)) if (ndims(posterior_samples) == 3){ stop("Tensors not supported. Call function for each slice.") } if (ndims(posterior_samples) == 1){ posterior_samples <- matrix(posterior_samples, ncol = 1) } sym.theta <- get_random_symbol() JuliaCall::julia_assign(sym.theta, posterior_samples) JuliaCall::julia_command(sprintf("%s = Float32.(%s);", sym.theta, sym.theta)) values <- JuliaCall::julia_eval(sprintf("sample_posterior_predict(%s, %s; x = %s)", bnn$juliavar, sym.theta, sym.x)) return(values) }
/scratch/gouwar.j/cran-all/cranData/BayesFluxR/R/predict.R
#' Use an isotropic Gaussian prior #' #' Use a Multivariate Gaussian prior for all network parameters. #' Covariance matrix is set to be equal `sigma * I` with `I` being #' the identity matrix. Mean is zero. #' #' @param chain Chain obtained using \code{\link{Chain}} #' @param sigma Standard deviation of Gaussian prior #' #' @return a list containing the following #' \itemize{ #' \item `juliavar` the julia variable used to store the prior #' \item `juliacode` the julia code #' } #' @examples #' \dontrun{ #' ## Needs previous call to `BayesFluxR_setup` which is time #' ## consuming and requires Julia and BayesFlux.jl #' BayesFluxR_setup(installJulia=TRUE, seed=123) #' net <- Chain(Dense(5, 1)) #' like <- likelihood.feedforward_normal(net, Gamma(2.0, 0.5)) #' prior <- prior.gaussian(net, 0.5) #' init <- initialise.allsame(Normal(0, 0.5), like, prior) #' x <- matrix(rnorm(5*100), nrow = 5) #' y <- rnorm(100) #' bnn <- BNN(x, y, like, prior, init) #' sampler <- sampler.SGLD() #' ch <- mcmc(bnn, 10, 1000, sampler) #' } #' #' @export prior.gaussian <- function(chain, sigma){ juliacode <- sprintf("GaussianPrior(%s, Float32(%e))", chain$nc, sigma) juliavar <- get_random_symbol() JuliaCall::julia_command(sprintf("%s = %s;", juliavar, juliacode)) out <- list(juliavar = juliavar, juliacode = juliacode) return(out) } #' Scale Mixture of Gaussian Prior #' #' Uses a scale mixture of Gaussian for each network parameter. That is, #' the prior is given by #' \deqn{\pi_1 Normal(0, sigma1) + (1-\pi_1) Normal(0, sigma2)} #' #' @param chain Chain obtained using \code{\link{Chain}} #' @param sigma1 Standard deviation of first Gaussian #' @param sigma2 Standard deviation of second Gaussian #' @param pi1 Weight of first Gaussian #' #' @return a list containing the following #' \itemize{ #' \item `juliavar` the julia variable used to store the prior #' \item `juliacode` the julia code #' } #' @examples #' \dontrun{ #' ## Needs previous call to `BayesFluxR_setup` which is time #' ## consuming and requires Julia and BayesFlux.jl #' BayesFluxR_setup(installJulia=TRUE, seed=123) #' net <- Chain(Dense(5, 1)) #' like <- likelihood.feedforward_normal(net, Gamma(2.0, 0.5)) #' prior <- prior.mixturescale(net, 10, 0.1, 0.5) #' init <- initialise.allsame(Normal(0, 0.5), like, prior) #' x <- matrix(rnorm(5*100), nrow = 5) #' y <- rnorm(100) #' bnn <- BNN(x, y, like, prior, init) #' sampler <- sampler.SGLD() #' ch <- mcmc(bnn, 10, 1000, sampler) #' } #' #' @export prior.mixturescale <- function(chain, sigma1, sigma2, pi1){ juliacode <- sprintf("MixtureScalePrior(%s, Float32(%e), Float32(%e), Float32(%e))", chain$nc, sigma1, sigma2, pi1) juliavar <- get_random_symbol() JuliaCall::julia_command(sprintf("%s = %s;", juliavar, juliacode)) out <- list(juliavar = juliavar, juliacode = juliacode) return(out) }
/scratch/gouwar.j/cran-all/cranData/BayesFluxR/R/priors.R
# If we are in a GitHub Action, we need to install Julia test_setup <- function(...) { julia_path <- dirname(Sys.which("julia")[[1]]) if (julia_path != "" && Sys.getenv("JULIA_HOME") == ""){ cat(paste("Using", julia_path, "as JULIA_HOME\n")) BayesFluxR_setup(JULIA_HOME = julia_path, ...) return() } if (Sys.getenv("CI") != ""){ BayesFluxR_setup(installJulia = TRUE, env_path = ".", ...) } else { choice <- Sys.getenv("BayesFluxTestInstallJulia") if (choice == ""){ choice <- readline(prompt = "Install Julia for tests? Y/N: ") Sys.setenv("BayesFluxTestInstallJulia" = choice) } if (choice %in% c("Y", "y", "yes", "Yes")) { BayesFluxR_setup(installJulia = TRUE, env_path = ".", ...) } else { BayesFluxR_setup(installJulia = FALSE, env_path = ".", ...) } } }
/scratch/gouwar.j/cran-all/cranData/BayesFluxR/R/test-helpers.R
#' Creates a random string that is used as variable in julia get_random_symbol <- function() { nframe <- sys.nframe() caller <- "" if (nframe > 1){ caller <- deparse(sys.calls()[[nframe-1]]) caller <- strsplit(caller, "\\(")[[1]][1] caller <- gsub("\\.", "_", caller) caller <- paste0(caller, "_") } sym <- paste0(sample(letters, 5, replace = TRUE), collapse = "") paste0(caller, sym) } #' Embed a matrix of timeseries into a tensor #' #' This is used when working with recurrent networks, especially in #' the case of seq-to-one modelling. Creates overlapping subsequences #' of the data with length `len_seq`. Returned dimensions are seq_len x num_vars x num_subsequences. #' #' @param mat Matrix of time series #' @param len_seq subsequence length #' #' @return A tensor of dimension: len_seq x num_vars x num_subsequences #' @examples #' \dontrun{ #' ## Needs previous call to `BayesFluxR_setup` which is time #' ## consuming and requires Julia and BayesFlux.jl #' BayesFluxR_setup(installJulia=TRUE, seed=123) #' net <- Chain(RNN(5, 1)) #' like <- likelihood.seqtoone_normal(net, Gamma(2.0, 0.5)) #' prior <- prior.gaussian(net, 0.5) #' init <- initialise.allsame(Normal(0, 0.5), like, prior) #' data <- matrix(rnorm(5*1000), ncol = 5) #' # Choosing sequences of length 10 and predicting one period ahead #' tensor <- tensor_embed_mat(data, 10+1) #' x <- tensor[1:10, , , drop = FALSE] #' # Last value in each sequence is the target value #' y <- tensor[11,1,] #' bnn <- BNN(x, y, like, prior, init) #' BNN.totparams(bnn) #' } #' #' @export tensor_embed_mat <- function(mat, len_seq){ num_sequences = nrow(mat) - len_seq + 1 tensor <- array(rep(NA, len_seq*ncol(mat)*num_sequences), dim = c(len_seq, ncol(mat), num_sequences)) for (i in 1:num_sequences){ tensor[, , i] <- mat[i:(i + len_seq - 1), ] } return(tensor) } #' #' @param x some array ndims <- function(x){ if (is.array(x)) { return(length(dim(x))) } if (length(x) > 1) return(1) return(0) } #' Print a summary of a BNN #' #' @param object A BNN created using \code{\link{BNN}} #' @param ... Not used #' @export summary.BNN <- function(object, ...){ summary_n_independent <- NROW(object$x) cat("Number of independent variables:", summary_n_independent, "\n") summary_n_dependent <- NCOL(object$y) cat("Number of dependent variables:", summary_n_dependent, "\n") summary_n_observations <- NCOL(object$x) cat("Number of observations:", summary_n_observations, "\n") summary_like_name <- JuliaCall::julia_eval(sprintf("string(typeof(%s.like).name.name)", object$juliavar)) cat("Likelihood:", summary_like_name, "\n") summary_prior_name <- JuliaCall::julia_eval(sprintf("string(typeof(%s.prior).name.name)", object$juliavar)) cat("Prior:", summary_prior_name, "\n") summary_init_name <- JuliaCall::julia_eval(sprintf("string(typeof(%s.init).name.name)", object$juliavar)) cat("Initalisation method:", summary_init_name, "\n") summary_n_network_params <- JuliaCall::julia_eval(sprintf("%s.like.nc.num_params_network", object$juliavar)) cat("Number of network parameters:", summary_n_network_params, "\n") summary_n_total_params <- BNN.totparams(object) cat("Number of total parameters:", summary_n_total_params, "\n") code <- sprintf('"Chain(\n\t$(join(%s.like.nc(randn(Float32, %s.like.nc.num_params_network)).layers, ",\n\t"))\n)"', object$juliavar, object$juliavar) summary_network_structure <- JuliaCall::julia_eval(code) cat("Network Structure:\n", summary_network_structure, "\n") } #' Convert draws array to conform with `bayesplot` #' #' BayesFluxR returns draws in a matrix of dimension #' params x draws. This cannot be used with the `bayesplot` package #' which expects an array of dimensions draws x chains x params. #' #' @param ch Chain of draws obtained using \code{\link{mcmc}} #' @param param_names If `NULL`, the parameter names will be of the #' form `param_1`, `param_2`, etc. If `param_names` is a string, #' the parameter names will start with the string with the number #' of the parameter attached to it. If `param_names` is a vector, it #' has to provide a name for each paramter in the chain. #' @returns Returns an array of dimensions draws x chains x params. #' @examples #' \dontrun{ #' ## Needs previous call to `BayesFluxR_setup` which is time #' ## consuming and requires Julia and BayesFlux.jl #' BayesFluxR_setup(installJulia=TRUE, seed=123) #' net <- Chain(Dense(5, 1)) #' like <- likelihood.feedforward_normal(net, Gamma(2.0, 0.5)) #' prior <- prior.gaussian(net, 0.5) #' init <- initialise.allsame(Normal(0, 0.5), like, prior) #' x <- matrix(rnorm(5*100), nrow = 5) #' y <- rnorm(100) #' bnn <- BNN(x, y, like, prior, init) #' sampler <- sampler.SGLD() #' ch <- mcmc(bnn, 10, 1000, sampler) #' ch <- to_bayesplot(ch) #' library(bayesplot) #' mcmc_intervals(ch, pars = paste0("param_", 1:10)) #' } #' @export to_bayesplot <- function(ch, param_names = NULL) { if (is.null(param_names)) { param_names <- paste0("param_", 1:dim(ch)[1]) } else if (length(param_names) == 1) { param_names <- paste0(param_names, 1:dim(ch)[1]) } ch_array <- array(ch, dim = c(dim(ch), 1), dimnames = list("params" = param_names, "iterations" = NULL, "chains" = c("chain:1"))) ch_array <- aperm(ch_array, c(2, 3, 1)) return(ch_array) }
/scratch/gouwar.j/cran-all/cranData/BayesFluxR/R/utils.R
#' Use Bayes By Backprop to find Variational Approximation to BNN. #' #' This was proposed in Blundell, C., Cornebise, J., Kavukcuoglu, K., & Wierstra, #' D. (2015, June). Weight uncertainty in neural network. In International #' conference on machine learning (pp. 1613-1622). PMLR. #' #'@param bnn a BNN obtained using \code{\link{BNN}} #'@param batchsize batch size #'@param epochs number of epochs to run for #'@param mc_samples samples to use in each iteration for the MC approximation #'usually one is enough. #'@param opt An optimiser. These all start with `opt.`. See for example \code{\link{opt.ADAM}} #'@param n_samples_convergence At the end of each iteration convergence is checked using this #'many MC samples. #' #'@return a list containing #'\itemize{ #' \item `juliavar` - julia variable storing VI #' \item `juliacode` - julia representation of function call #' \item `params` - variational family parameters for each iteration #' \item `losses` - BBB loss in each iteration #'} #' @examples #' \dontrun{ #' ## Needs previous call to `BayesFluxR_setup` which is time #' ## consuming and requires Julia and BayesFlux.jl #' BayesFluxR_setup(installJulia=TRUE, seed=123) #' net <- Chain(RNN(5, 1)) #' like <- likelihood.seqtoone_normal(net, Gamma(2.0, 0.5)) #' prior <- prior.gaussian(net, 0.5) #' init <- initialise.allsame(Normal(0, 0.5), like, prior) #' data <- matrix(rnorm(10*1000), ncol = 10) #' # Choosing sequences of length 10 and predicting one period ahead #' tensor <- tensor_embed_mat(data, 10+1) #' x <- tensor[1:10, , , drop = FALSE] #' # Last value in each sequence is the target value #' y <- tensor[11,,] #' bnn <- BNN(x, y, like, prior, init) #' vi <- bayes_by_backprop(bnn, 100, 100) #' vi_samples <- vi.get_samples(vi, n = 1000) #' } #' #'@export bayes_by_backprop <- function(bnn, batchsize, epochs, mc_samples = 1, opt = opt.ADAM(), n_samples_convergence = 10){ juliacode <- sprintf("bbb(%s, %i, %i; mc_samples = %i, opt = %s, n_samples_convergence = %i)", bnn$juliavar, batchsize, epochs, mc_samples, opt$juliavar, n_samples_convergence) juliavar <- get_random_symbol() JuliaCall::julia_command(sprintf("%s = %s;", juliavar, juliacode)) params <- JuliaCall::julia_eval(sprintf("%s[2]", juliavar)) losses <- JuliaCall::julia_eval(sprintf("%s[3]", juliavar)) out <- list(juliavar = juliavar, juliacode = juliacode, params = params, losses = losses) return(out) } #' Draw samples form a variational family. #' #' @param vi obtained using \code{\link{bayes_by_backprop}} #' @param n number of samples #' #' @return a matrix whose columns are draws from the variational posterior #' @examples #' \dontrun{ #' ## Needs previous call to `BayesFluxR_setup` which is time #' ## consuming and requires Julia and BayesFlux.jl #' BayesFluxR_setup(installJulia=TRUE, seed=123) #' net <- Chain(RNN(5, 1)) #' like <- likelihood.seqtoone_normal(net, Gamma(2.0, 0.5)) #' prior <- prior.gaussian(net, 0.5) #' init <- initialise.allsame(Normal(0, 0.5), like, prior) #' data <- matrix(rnorm(10*1000), ncol = 10) #' # Choosing sequences of length 10 and predicting one period ahead #' tensor <- tensor_embed_mat(data, 10+1) #' x <- tensor[1:10, , , drop = FALSE] #' # Last value in each sequence is the target value #' y <- tensor[11,,] #' bnn <- BNN(x, y, like, prior, init) #' vi <- bayes_by_backprop(bnn, 100, 100) #' vi_samples <- vi.get_samples(vi, n = 1000) #' pp <- posterior_predictive(bnn, vi_samples) #' } #' #' @export vi.get_samples <- function(vi, n = 1){ samples <- JuliaCall::julia_eval(sprintf("rand(%s[1], %i)", vi$juliavar, n)) return(samples) }
/scratch/gouwar.j/cran-all/cranData/BayesFluxR/R/vi.R
DS.Finite.Bayes <- function(DS.GF.obj, y.0, n.0 = NULL, cred.interval = 0.90, iters = 25){ #Converter Function LP.post.conv <- function(theta.set, DS.GF.obj, y.0, n.0 = NULL, e.0 = NULL){ fam = DS.GF.obj$fam out <- list() lambda.i <- function(s.i, tau.2){s.i^2/(s.i^2+tau.2)} switch(fam, "Normal" = { prior.type = "Normal" se.0 <- n.0 post.mu.i <- lambda.i(se.0, DS.GF.obj$g.par[2]) * DS.GF.obj$g.par[1] + (1-lambda.i(se.0, DS.GF.obj$g.par[2]))* y.0 post.tau2.i <- (1-lambda.i(se.0, DS.GF.obj$g.par[2]))*se.0^2 #output is VARIANCE PEB.pos.den <- dnorm(theta.set, post.mu.i, sd = sqrt(post.tau2.i)) if(sum(DS.GF.obj$LP.par^2)==0){ post.fit <- data.frame(theta.vals = theta.set, parm.pos = PEB.pos.den) } else { unit.grid <- pnorm(theta.set, DS.GF.obj$g.par[1], sd = sqrt(DS.GF.obj$g.par[2])) wght.den <- weight.fun.univ(unit.grid, DS.GF.obj$g.par[1], DS.GF.obj$g.par[2], post.mu.i, post.tau2.i, family = fam) # in terms of u if(DS.GF.obj$LP.type == "L2"){ d.u <- 1 + gLP.basis(unit.grid,c(1,1), DS.GF.obj$m.val, con.prior = "Beta")%*%DS.GF.obj$LP.par } else { d.u <- exp(cbind(1,gLP.basis(unit.grid, c(1, 1), DS.GF.obj$m.val, con.prior = "Beta")) %*% DS.GF.obj$LP.par) } denom <- sintegral(unit.grid, d.u*wght.den)$int # in terms of u post.fit <- data.frame(theta.vals = theta.set, parm.pos = PEB.pos.den, ds.pos = PEB.pos.den * (d.u/denom)) } return(post.fit) }, "Binomial" = { prior.type = "Beta" post.alph.i <- y.0 + DS.GF.obj$g.par[1] post.beta.i <- n.0 - y.0 + DS.GF.obj$g.par[2] PEB.pos.den <- dbeta(theta.set,post.alph.i, post.beta.i) #in terms of theta if(sum(DS.GF.obj$LP.par^2)==0){ post.fit <- data.frame(theta.vals = theta.set, parm.pos = PEB.pos.den) } else { unit.grid <- pbeta(theta.set, DS.GF.obj$g.par[1], DS.GF.obj$g.par[2]) wght.den <- weight.fun.univ(unit.grid, DS.GF.obj$g.par[1], DS.GF.obj$g.par[2], post.alph.i, post.beta.i, family = fam) # in terms of u if(DS.GF.obj$LP.type == "L2"){ d.u <- 1 + gLP.basis(unit.grid, c(1,1), DS.GF.obj$m.val, con.prior = "Beta")%*%DS.GF.obj$LP.par } else { d.u <- exp(cbind(1,gLP.basis(unit.grid, c(1, 1), DS.GF.obj$m.val, con.prior = "Beta")) %*% DS.GF.obj$LP.par) } denom <- sintegral(unit.grid, d.u*wght.den)$int # in terms of u post.fit <- data.frame(theta.vals = theta.set, parm.pos = PEB.pos.den, ds.pos = PEB.pos.den * (d.u/denom)) } return(post.fit) }, "Poisson" = { prior.type = "Gamma" if(is.null(e.0) == TRUE){ post.alph.i <- y.0 + DS.GF.obj$g.par[1] post.beta.i <- DS.GF.obj$g.par[2]/(1+DS.GF.obj$g.par[2]) } else { post.alph.i <- y.0 + DS.GF.obj$g.par[1] post.beta.i <- DS.GF.obj$g.par[2]/(1 + e.0*DS.GF.obj$g.par[2]) } PEB.pos.den <- dgamma(theta.set,post.alph.i, scale = post.beta.i) #in terms of theta if(sum(DS.GF.obj$LP.par^2)==0){ post.fit <- data.frame(theta.vals = theta.set, parm.pos = PEB.pos.den) } else { unit.grid <- pgamma(theta.set, DS.GF.obj$g.par[1], scale = DS.GF.obj$g.par[2]) wght.den <- weight.fun.univ(unit.grid, DS.GF.obj$g.par[1], DS.GF.obj$g.par[2], post.alph.i, post.beta.i, family = fam) # in terms of u if(DS.GF.obj$LP.type == "L2"){ d.u <- 1 + gLP.basis(unit.grid, c(1,1), DS.GF.obj$m.val, con.prior = "Beta")%*%DS.GF.obj$LP.par } else { d.u <- exp(cbind(1,gLP.basis(unit.grid, c(1, 1), DS.GF.obj$m.val, con.prior = "Beta")) %*% DS.GF.obj$LP.par) } denom <- sintegral(unit.grid, d.u*wght.den)$int # in terms of u post.fit <- data.frame(theta.vals = theta.set, parm.pos = PEB.pos.den, ds.pos = PEB.pos.den * (d.u/denom)) } return(post.fit) } ) } #### out <- list() fam = DS.GF.obj$fam LP.type = DS.GF.obj$LP.type DS.objt.list <- list() #DS.post.list <- list() switch(fam, "Normal" = { out$study <- c(y.0, n.0) if(LP.type == "MaxEnt"){ #MaxEnt for(i in 1:iters){ L2.norm.thres <- 1.1*sqrt(sum((DS.GF.obj$LP.max.smt[1:DS.GF.obj$m.val]^2))) L2.norm <- L2.norm.thres + 1 while(L2.norm > L2.norm.thres){ par.g <- c(NA, NA) while (!is.finite(par.g[1]) == TRUE | !is.finite(par.g[2]) == TRUE) { new.df <- rPPD.ds(DS.GF.obj, 1, pred.type = "prior")$first.set possibleError <- tryCatch(par.g <- gMLE.nn(new.df$y,new.df$se)$estimate, error = function(e) e) er.check <- !inherits(possibleError, "error") if (er.check == TRUE) { par.g <- gMLE.nn(new.df$y, new.df$se)$estimate } else { par.g <- c(NA, NA) } } new.ds.me <- DS.prior(new.df, max.m = DS.GF.obj$m.val, g.par = par.g, family = "Normal", LP.type = "MaxEnt") L2.norm <- sqrt(sum((new.ds.me$LP.par)^2)) } DS.objt.list[[i]] <- new.ds.me #DS.post.list[[i]] <- DS.micro.inf.nnu(new.ds.me, y.0 = y.0, se.0 = n.0) } } else { #L2 for(i in 1:iters){ par.g <- c(NA,NA) while(!is.finite(par.g[1])==TRUE | !is.finite(par.g[2])==TRUE){ new.df <- rPPD.ds(DS.GF.obj,1, pred.type = "prior")$first.set possibleError <- tryCatch(par.g <- gMLE.nn(new.df$y, new.df$se)$estimate, error = function(e) e ) er.check <- !inherits(possibleError, "error") if(er.check == TRUE){ par.g <- gMLE.nn(new.df$y, new.df$se)$estimate } else { par.g <- c(NA, NA) } } new.ds.L2 <- DS.prior.nnu(new.df, max.m = DS.GF.obj$m.val, start.par = par.g) DS.objt.list[[i]] <- new.ds.L2 #DS.post.list[[i]] <-DS.micro.inf.nnu(new.ds.L2, y.0 = y.0, se.0 = n.0) } } }, "Binomial" = { out$study <- c(y.0, n.0) if(LP.type == "MaxEnt"){ #MaxEnt for(i in 1:iters){ L2.norm.thres <- 1.1*sqrt(sum((DS.GF.obj$LP.max.smt[1:DS.GF.obj$m.val]^2))) L2.norm <- L2.norm.thres + 1 while(L2.norm > L2.norm.thres){ par.g <- c(NA, NA) while (!is.finite(par.g[1]) == TRUE | !is.finite(par.g[2]) == TRUE) { new.df <- rPPD.ds(DS.GF.obj, 1, pred.type = "prior")$first.set possibleError <- tryCatch(par.g <- gMLE.bb(new.df$y,new.df$n)$estimate, error = function(e) e) er.check <- !inherits(possibleError, "error") if (er.check == TRUE) { par.g <- gMLE.bb(new.df$y, new.df$n)$estimate } else { par.g <- c(NA, NA) } } new.ds.me <- DS.prior(new.df, max.m = DS.GF.obj$m.val, g.par = par.g, family = "Binomial", LP.type = "MaxEnt") L2.norm <- sqrt(sum((new.ds.me$LP.par)^2)) } DS.objt.list[[i]] <- new.ds.me #DS.post.list[[i]] <- DS.micro.inf(new.ds.me, y.0 = y.0, n.0 = n.0) } } else { #L2 for(i in 1:iters){ par.g <- c(NA,NA) while(!is.finite(par.g[1])==TRUE | !is.finite(par.g[2])==TRUE){ new.df <- rPPD.ds(DS.GF.obj,1, pred.type = "prior")$first.set possibleError <- tryCatch(par.g <- gMLE.bb(new.df$y, new.df$n)$estimate, error = function(e) e ) er.check <- !inherits(possibleError, "error") if(er.check == TRUE){ par.g <- gMLE.bb(new.df$y, new.df$n)$estimate } else { par.g <- c(NA, NA) } } new.ds.L2 <- DS.prior.bbu(new.df, max.m = DS.GF.obj$m.val, start.par = par.g) DS.objt.list[[i]] <- new.ds.L2 #DS.post.list[[i]] <-DS.micro.inf(new.ds.L2, y.0 = y.0, n.0 = n.0) } } }, "Poisson" = { out$study <- y.0 if(LP.type == "MaxEnt"){ #MaxEnt for(i in 1:iters){ L2.norm.thres <- 1.1*sqrt(sum((DS.GF.obj$LP.max.smt[1:DS.GF.obj$m.val]^2))) L2.norm <- L2.norm.thres + 1 while(L2.norm > L2.norm.thres){ par.g <- c(NA, NA) while (!is.finite(par.g[1]) == TRUE | !is.finite(par.g[2]) == TRUE) { new.y <- rPPD.ds(DS.GF.obj, 1, pred.type = "prior")$first.set possibleError <- tryCatch(par.g <- gMLE.pg(new.y, start.par = DS.GF.obj$g.par), error = function(e) e) er.check <- !inherits(possibleError, "error") if (er.check == TRUE) { par.g <- gMLE.pg(new.y, start.par = DS.GF.obj$g.par) } else { par.g <- c(NA, NA) } } new.ds.me <- DS.prior(new.y, max.m = DS.GF.obj$m.val, g.par = par.g, family = "Poisson", LP.type = "MaxEnt") L2.norm <- sqrt(sum((new.ds.me$LP.par)^2)) } DS.objt.list[[i]] <- new.ds.me #DS.post.list[[i]] <- DS.micro.inf(new.ds.me, y.0 = y.0, n.0 = NULL) } } else { #L2 for(i in 1:iters){ par.g <- c(NA,NA) while(!is.finite(par.g[1])==TRUE | !is.finite(par.g[2])==TRUE){ new.y <- rPPD.ds(DS.GF.obj,1, pred.type = "prior")$first.set possibleError <- tryCatch(par.g <- gMLE.pg(new.y, start.par = DS.GF.obj$g.par), error = function(e) e ) er.check <- !inherits(possibleError, "error") if(er.check == TRUE){ par.g <- gMLE.pg(new.y, start.par = DS.GF.obj$g.par) } else { par.g <- c(NA, NA) } } new.ds.L2 <- DS.prior.pgu(new.y, max.m = DS.GF.obj$m.val, start.par = par.g) DS.objt.list[[i]] <- new.ds.L2 #DS.post.list[[i]] <-DS.micro.inf(new.ds.L2, y.0 = y.0, n.0 = NULL) } } } ) #build finite prior finite.prior <- matrix(0, nrow = length(DS.objt.list), ncol = length(DS.GF.obj$prior.fit$theta.vals)) for(i in 1:length(DS.objt.list)){ if(sum(DS.objt.list[[i]]$LP.par^2) == 0){ finite.prior[i,] <- DS.objt.list[[i]]$prior.fit$parm.prior } else { finite.prior[i,] <- DS.objt.list[[i]]$prior.fit$ds.prior } } if(sum(DS.GF.obj$LP.par^2) == 0){ out$prior.fit <- data.frame(theta.vals = DS.GF.obj$prior.fit$theta.vals, parm.prior = DS.GF.obj$prior.fit$parm.prior, finite.prior = colMeans(finite.prior) ) } else { out$prior.fit <- data.frame(theta.vals = DS.GF.obj$prior.fit$theta.vals, parm.prior = DS.GF.obj$prior.fit$parm.prior, ds.prior = DS.GF.obj$prior.fit$ds.prior, finite.prior = colMeans(finite.prior) ) } #build posterior post.base <- DS.micro.inf(DS.GF.obj, y.0= y.0, n.0 = n.0) theta.post <- post.base$post.fit$theta.vals test.post <- lapply(DS.objt.list, function(x) LP.post.conv(theta.post, x, y.0 = y.0, n.0 = n.0) ) finite.post <- matrix(0, nrow = length(DS.objt.list), ncol = length(post.base$post.fit$theta.vals)) for(i in 1:length(DS.objt.list)){ if(dim(test.post[[i]])[2] == 2){ finite.post[i,] <- test.post[[i]]$parm.pos } else { finite.post[i,] <- test.post[[i]]$ds.pos } } finite.post[which(finite.post < 0)] <- 0.00001 if(dim(post.base$post.fit)[2] == 2){ out$post.fit <- data.frame(theta.vals = post.base$post.fit$theta.vals, parm.post = post.base$post.fit$parm.pos, finite.post = colMeans(finite.post)) } else { out$post.fit <- data.frame(theta.vals = post.base$post.fit$theta.vals, parm.post = post.base$post.fit$parm.pos, ds.post = post.base$post.fit$ds.pos, finite.post = colMeans(finite.post)) } out$post.vec <- c(post.base$post.vec[1], DS_MN = sintegral(out$post.fit$theta.vals, out$post.fit$theta.vals*out$post.fit$finite.post)$int, post.base$post.vec[3], DS_MD = out$post.fit$theta.vals[which.max(out$post.fit$finite.post)]) #credible interval dens.vec <- NULL for(i in 2:length(post.base$post.fit$theta.vals)){ dens.vec[i] <- sintegral(post.base$post.fit$theta.vals[1:i], out$post.fit$finite.post[1:i])$int } top.CI <- which.min(abs( dens.vec - (cred.interval + (1-cred.interval)/2) ))+1 bot.CI <- which.min(abs( dens.vec - (1-cred.interval)/2)) out$interval <- post.base$post.fit$theta.vals[c(bot.CI, top.CI)] class(out) <- "DS_FB_obj" return(out) }
/scratch/gouwar.j/cran-all/cranData/BayesGOF/R/DS.Finite.Bayes.R
DS.entropy <- function(DS.GF.obj){ ########################## # INPUT: A DS object with LP.type = "L2" # OUTPUT: ent: entropy out <- list() #Check for parametric if(sum(DS.GF.obj$LP.par^2) == 0){ a <- min(DS.GF.obj$prior.fit$theta.vals) b <- max(DS.GF.obj$prior.fit$theta.vals) out$qLP <- 0 out$ent <- sintegral(DS.GF.obj$prior.fit$theta.vals, (DS.GF.obj$prior.fit$parm.prior - 1/(b-a))^2)$int } else { #Check for Max Entropy if(DS.GF.obj$LP.type == "L2"){out$qLP <- sum(DS.GF.obj$LP.par^2)} #Check for Normal; want to adjust domain such that it fits DS not parametric if(DS.GF.obj$fam == "Normal"){ dens.diff <- abs(diff(DS.GF.obj$prior.fit$ds.prior)) diff.ind <- which(dens.diff > 0) a.ind <- max(1, min(diff.ind[-c(1,length(diff.ind))])-1) b.ind <- min(length(DS.GF.obj$prior.fit$theta.vals), max(diff.ind[-c(1,length(diff.ind))])+1) a <- DS.GF.obj$prior.fit$theta.vals[a.ind] b <- DS.GF.obj$prior.fit$theta.vals[b.ind] } else { a <- min(DS.GF.obj$prior.fit$theta.vals) b <- max(DS.GF.obj$prior.fit$theta.vals) } out$ent <- sintegral(DS.GF.obj$prior.fit$theta.vals, (DS.GF.obj$prior.fit$ds.prior - 1/(b-a))^2)$int } names(out$ent) <- NULL return(out) }
/scratch/gouwar.j/cran-all/cranData/BayesGOF/R/DS.entropy.R
DS.macro.inf <- function(DS.GF.obj, num.modes =1, method = c("mean","mode"), iters = 25, exposure = NULL){ fam = DS.GF.obj$fam switch(fam, "Normal" = { DS.macro.inf.nnu(DS.GF.obj, num.modes , iters , method, pred.type = "prior") }, "Binomial" = { DS.macro.inf.bbu(DS.GF.obj, num.modes , iters , method, pred.type = "prior") }, "Poisson" = { if(is.null(exposure) == TRUE){ DS.macro.inf.pgu(DS.GF.obj, num.modes , iters , method, pred.type = "prior") } else { DS.macro.inf.pge(DS.GF.obj, num.modes, iters, exposure = exposure, method, pred.type = "prior") } } ) }
/scratch/gouwar.j/cran-all/cranData/BayesGOF/R/DS.macro.inf.R
DS.macro.inf.bbu <- function(DS.GF.obj, num.modes =1 , iters = 25, method = c("mean","mode"), pred.type = c("posterior","prior")){ # INPUTS # DS.GF.obj AutoBayes-DataCorrect object # num.modes For mode inference: number of modes expected # method mean finds the bootstrap mean and sd (parameteric) # mode finds the bootstrap mode and sd (DS) # OUTPUTS # model.modes modes of the DC prior generated by object # mode.sd standard deviation of modes (generated through simulation) # prior.fit dataframe of prior information for plotting # boot.modes/means bootstrap mode or mean for simulation switch(DS.GF.obj$LP.type, "L2" = { method = match.arg(method) switch(method, "mode" = { out <- list() modes.mat <- matrix(0, nrow = iters, ncol = num.modes) if(sum(DS.GF.obj$LP.par^2) == 0){ m.new = 0 out$model.modes <- Local.Mode(DS.GF.obj$prior.fit$theta.vals, DS.GF.obj$prior.fit$parm.prior) } else { m.new = length(DS.GF.obj$LP.par) out$model.modes <- Local.Mode(DS.GF.obj$prior.fit$theta.vals, DS.GF.obj$prior.fit$ds.prior) } for(i in 1:iters){ len.mode = num.modes+1 while(len.mode != num.modes){ par.g <- c(NA,NA) while(!is.finite(par.g[1])==TRUE | !is.finite(par.g[2])==TRUE){ ifelse(pred.type == "posterior", new.df <- rPPD.ds(DS.GF.obj,1,pred.type = "posterior")$first.set, new.df <- rPPD.ds(DS.GF.obj,1, pred.type = "prior")$first.set) possibleError <- tryCatch(par.g <- gMLE.bb(new.df$y, new.df$n)$estimate, error = function(e) e ) er.check <- !inherits(possibleError, "error") if(er.check == TRUE){ par.g <- gMLE.bb(new.df$y, new.df$n)$estimate } else { par.g <- c(NA, NA) } } new.LPc <- DS.prior.bbu(new.df, max.m = m.new, start.par = par.g) if(sum(new.LPc$LP.par^2) == 0){ modes.new <- Local.Mode(new.LPc$prior.fit$theta.vals, new.LPc$prior.fit$parm.prior) } else { modes.new <- Local.Mode(new.LPc$prior.fit$theta.vals, new.LPc$prior.fit$ds.prior) } len.mode <- length(modes.new) } modes.mat[i,] <- modes.new } out$boot.modes <- modes.mat out$mode.sd <- apply(modes.mat,2,sd) out$prior.fit <- DS.GF.obj$prior.fit class(out) <- "DS_GF_macro_mode" return(out) }, "mean" = { out <- list() if(sum(DS.GF.obj$LP.par^2) == 0){ m.new = 0 out$model.mean <- DS.GF.obj$g.par[1]/(DS.GF.obj$g.par[1]+DS.GF.obj$g.par[2]) } else { m.new = length(DS.GF.obj$LP.par) out$model.mean <- sintegral(DS.GF.obj$prior.fit$theta.vals, DS.GF.obj$prior.fit$theta.vals*DS.GF.obj$prior.fit$ds.prior)$int } par.mean.vec <- NULL for(i in 1:iters){ par.g <- c(NA,NA) while(!is.finite(par.g[1])==TRUE | !is.finite(par.g[2])==TRUE){ ifelse(pred.type == "posterior", new.df <- rPPD.ds(DS.GF.obj,1,pred.type = "posterior")$first.set, new.df <- rPPD.ds(DS.GF.obj,1, pred.type = "prior")$first.set) possibleError <- tryCatch(par.g <- gMLE.bb(new.df$y, new.df$n)$estimate, error = function(e) e ) er.check <- !inherits(possibleError, "error") if(er.check == TRUE){ par.g <- gMLE.bb(new.df$y, new.df$n)$estimate } else { par.g <- c(NA, NA) } } new.LPc <- DS.prior.bbu(new.df, max.m = m.new, start.par = par.g) if(sum(new.LPc$LP.par^2) == 0){ par.mean.vec[i] <- par.g[1]/(par.g[1]+par.g[2]) } else { par.mean.vec[i] <- sintegral(new.LPc$prior.fit$theta.vals, new.LPc$prior.fit$theta.vals*new.LPc$prior.fit$ds.prior)$int } } out$boot.mean <- par.mean.vec out$mean.sd <- sd(par.mean.vec) out$prior.fit <- DS.GF.obj$prior.fit class(out) <- "DS_GF_macro_mean" return(out) } ) }, "MaxEnt" = { method = match.arg(method) switch(method, "mode" = { out <- list() modes.mat <- matrix(0, nrow = iters, ncol = num.modes) if(sum(DS.GF.obj$LP.par^2) == 0){ m.new = 0 out$model.modes <- Local.Mode(DS.GF.obj$prior.fit$theta.vals, DS.GF.obj$prior.fit$parm.prior) } else { m.new = length(DS.GF.obj$LP.par) out$model.modes <- Local.Mode(DS.GF.obj$prior.fit$theta.vals, DS.GF.obj$prior.fit$ds.prior) } for(i in 1:iters){ len.mode = num.modes+1 while(len.mode != num.modes){ L2.norm.thres <- 1.1*sqrt(sum((DS.GF.obj$LP.max.smt[1:DS.GF.obj$m.val]^2))) L2.norm <- L2.norm.thres + 1 while(L2.norm > L2.norm.thres){ par.g <- c(NA,NA) while(!is.finite(par.g[1])==TRUE | !is.finite(par.g[2])==TRUE){ ifelse(pred.type == "posterior", new.df <- rPPD.ds(DS.GF.obj,1,pred.type = "posterior")$first.set, new.df <- rPPD.ds(DS.GF.obj,1, pred.type = "prior")$first.set) possibleError <- tryCatch(par.g <- gMLE.bb(new.df$y, new.df$n)$estimate, error = function(e) e ) er.check <- !inherits(possibleError, "error") if(er.check == TRUE){ par.g <- gMLE.bb(new.df$y, new.df$n)$estimate } else { par.g <- c(NA, NA) } } new.LPc <- DS.prior.bbu(new.df, max.m = m.new, start.par = par.g) L2.norm <- sqrt(sum((new.LPc$LP.par)^2)) } if(sum(new.LPc$LP.par^2) == 0){ modes.new <- new.LPc$prior.fit$theta.vals[which.max(new.LPc$prior.fit$parm.prior)] } else { new.LP.ME <- maxent.obj.convert(new.LPc) modes.new <- Local.Mode(new.LP.ME$prior.fit$theta.vals, new.LP.ME$prior.fit$ds.prior) } len.mode <- length(modes.new) } modes.mat[i,] <- modes.new } out$boot.modes <- modes.mat out$mode.sd <- apply(modes.mat,2,sd) out$prior.fit <- DS.GF.obj$prior.fit class(out) <- "DS_GF_macro_mode" return(out) }, "mean" = { out <- list() if(sum(DS.GF.obj$LP.par^2) == 0){ m.new = 0 out$model.mean <- DS.GF.obj$g.par[1]/(DS.GF.obj$g.par[1]+DS.GF.obj$g.par[2]) } else { m.new = length(DS.GF.obj$LP.par) out$model.mean <- sintegral(DS.GF.obj$prior.fit$theta.vals, DS.GF.obj$prior.fit$theta.vals*DS.GF.obj$prior.fit$ds.prior)$int } par.mean.vec <- NULL for(i in 1:iters){ L2.norm.thres <- 1.1*sqrt(sum((DS.GF.obj$LP.max.smt[1:DS.GF.obj$m.val]^2))) L2.norm <- L2.norm.thres + 1 while(L2.norm > L2.norm.thres){ par.g <- c(NA,NA) while(!is.finite(par.g[1])==TRUE | !is.finite(par.g[2])==TRUE){ ifelse(pred.type == "posterior", new.df <- rPPD.ds(DS.GF.obj,1,pred.type = "posterior")$first.set, new.df <- rPPD.ds(DS.GF.obj,1, pred.type = "prior")$first.set) possibleError <- tryCatch(par.g <- gMLE.bb(new.df$y, new.df$n)$estimate, error = function(e) e ) er.check <- !inherits(possibleError, "error") if(er.check == TRUE){ par.g <- gMLE.bb(new.df$y, new.df$n)$estimate } else { par.g <- c(NA, NA) } } new.LPc <- DS.prior.bbu(new.df, max.m = m.new, start.par = par.g) L2.norm <- sqrt(sum((new.LPc$LP.par)^2)) } if(sum(new.LPc$LP.par^2) == 0){ par.mean.vec[i] <- par.g[1]/(par.g[1]+par.g[2]) } else { new.LP.ME <- maxent.obj.convert(new.LPc) par.mean.vec[i] <- sintegral(new.LP.ME$prior.fit$theta.vals, new.LP.ME$prior.fit$theta.vals*new.LP.ME$prior.fit$ds.prior)$int } } out$boot.mean <- par.mean.vec out$mean.sd <- sd(par.mean.vec) out$prior.fit <- DS.GF.obj$prior.fit class(out) <- "DS_GF_macro_mean" return(out) } ) } ) }
/scratch/gouwar.j/cran-all/cranData/BayesGOF/R/DS.macro.inf.bbu.R
DS.macro.inf.nnu <- function(DS.GF.obj, num.modes =1 , iters = 25, method = c("mean","mode"), pred.type = c("posterior","prior")){ # INPUTS # DS.GF.obj AutoBayes-DataCorrect object # num.modes For mode inference: number of modes expected # method mean finds the bootstrap mean and sd (parameteric) # mode finds the bootstrap mode and sd (DS) # OUTPUTS # model.modes modes of the DC prior generated by object # mode.sd standard deviation of modes (generated through simulation) # prior.fit dataframe of prior information for plotting # boot.modes/means bootstrap mode or mean for simulation lambda.i <- function(s.i, tau.2){s.i^2/(s.i^2+tau.2)} switch(DS.GF.obj$LP.type, "L2" = { method = match.arg(method) switch(method, "mode" = { out <- list() modes.mat <- matrix(0, nrow = iters, ncol = num.modes) if(sum(DS.GF.obj$LP.par^2) == 0){ m.new = 0 out$model.modes <- Local.Mode(DS.GF.obj$prior.fit$theta.vals, DS.GF.obj$prior.fit$parm.prior) } else { m.new = length(DS.GF.obj$LP.par) out$model.modes <- Local.Mode(DS.GF.obj$prior.fit$theta.vals, DS.GF.obj$prior.fit$ds.prior) } for(i in 1:iters){ len.mode = num.modes+1 while(len.mode != num.modes){ par.g <- c(NA,NA) while(!is.finite(par.g[1])==TRUE | !is.finite(par.g[2])==TRUE){ ifelse(pred.type == "posterior", new.df <- rPPD.ds(DS.GF.obj,1,pred.type = "posterior")$first.set, new.df <- rPPD.ds(DS.GF.obj,1, pred.type = "prior")$first.set) possibleError <- tryCatch(par.g <- gMLE.nn(new.df$y, new.df$se, fixed = FALSE, method = "DL")$estimate, error = function(e) e ) er.check <- !inherits(possibleError, "error") if(er.check == TRUE){ par.g <- gMLE.nn(new.df$y, new.df$se, fixed = FALSE, method = "DL")$estimate } else { par.g <- c(NA, NA) } } new.LPc <- DS.prior.nnu(new.df, max.m = m.new, start.par = par.g) if(sum(new.LPc$LP.par^2) == 0){ modes.new <- Local.Mode(new.LPc$prior.fit$theta.vals, new.LPc$prior.fit$parm.prior) } else { modes.new <- Local.Mode(new.LPc$prior.fit$theta.vals, new.LPc$prior.fit$ds.prior) } len.mode <- length(modes.new) } modes.mat[i,] <- modes.new } out$boot.modes <- modes.mat out$mode.sd <- apply(modes.mat,2,sd) out$prior.fit <- DS.GF.obj$prior.fit class(out) <- "DS_GF_macro_mode" return(out) }, "mean" = { out <- list() if(sum(DS.GF.obj$LP.par^2) == 0){ m.new = 0 out$model.mean <- DS.GF.obj$g.par[1] } else { m.new = length(DS.GF.obj$LP.par) out$model.mean <- sintegral(DS.GF.obj$prior.fit$theta.vals, DS.GF.obj$prior.fit$theta.vals*DS.GF.obj$prior.fit$ds.prior)$int } par.mean.vec <- NULL for(i in 1:iters){ par.g <- c(NA,NA) while(!is.finite(par.g[1])==TRUE | !is.finite(par.g[2])==TRUE){ ifelse(pred.type == "posterior", new.df <- rPPD.ds(DS.GF.obj,1,pred.type = "posterior")$first.set, new.df <- rPPD.ds(DS.GF.obj,1, pred.type = "prior")$first.set) possibleError <- tryCatch(par.g <- gMLE.nn(new.df$y, new.df$se, fixed = FALSE, method = "DL")$estimate, error = function(e) e ) er.check <- !inherits(possibleError, "error") if(er.check == TRUE){ par.g <- gMLE.nn(new.df$y, new.df$se, fixed = FALSE, method = "DL")$estimate } else { par.g <- c(NA, NA) } } new.LPc <- DS.prior.nnu(new.df, max.m = m.new, start.par = par.g) if(sum(new.LPc$LP.par^2) == 0){ par.mean.vec[i] <- par.g[1] } else { par.mean.vec[i] <- sintegral(new.LPc$prior.fit$theta.vals, new.LPc$prior.fit$theta.vals*new.LPc$prior.fit$ds.prior)$int } } out$boot.mean <- par.mean.vec out$mean.sd <- sd(par.mean.vec) out$prior.fit <- DS.GF.obj$prior.fit class(out) <- "DS_GF_macro_mean" return(out) } ) }, "MaxEnt" = { method = match.arg(method) switch(method, "mode" = { out <- list() modes.mat <- matrix(0, nrow = iters, ncol = num.modes) if(sum(DS.GF.obj$LP.par[-1]^2) == 0){ m.new = 0 out$model.modes <- Local.Mode(DS.GF.obj$prior.fit$theta.vals, DS.GF.obj$prior.fit$parm.prior) } else { m.new = length(DS.GF.obj$LP.par[-1]) out$model.modes <- Local.Mode(DS.GF.obj$prior.fit$theta.vals, DS.GF.obj$prior.fit$ds.prior) } for(i in 1:iters){ len.mode = num.modes+1 while(len.mode != num.modes){ L2.norm.thres <- 1.1*sqrt(sum((DS.GF.obj$LP.max.smt[1:DS.GF.obj$m.val]^2))) L2.norm <- L2.norm.thres + 1 while(L2.norm > L2.norm.thres){ par.g <- c(NA,NA) while(!is.finite(par.g[1])==TRUE | !is.finite(par.g[2])==TRUE){ ifelse(pred.type == "posterior", new.df <- rPPD.ds(DS.GF.obj,1,pred.type = "posterior")$first.set, new.df <- rPPD.ds(DS.GF.obj,1, pred.type = "prior")$first.set) possibleError <- tryCatch(par.g <- gMLE.nn(new.df$y, new.df$se, fixed = FALSE, method = "DL")$estimate, error = function(e) e ) er.check <- !inherits(possibleError, "error") if(er.check == TRUE){ par.g <- gMLE.nn(new.df$y, new.df$se, fixed = FALSE, method = "DL")$estimate } else { par.g <- c(NA, NA) } } new.LPc <- DS.prior.nnu(new.df, max.m = m.new, start.par = par.g) L2.norm <- sqrt(sum((new.LPc$LP.par)^2)) } if(sum(new.LPc$LP.par^2) == 0){ modes.new <- new.LPc$prior.fit$theta.vals[which.max(new.LPc$prior.fit$parm.prior)] } else { new.LP.ME <- maxent.obj.convert(new.LPc) modes.new <- Local.Mode(new.LP.ME$prior.fit$theta.vals, new.LP.ME$prior.fit$ds.prior) } len.mode <- length(modes.new) } modes.mat[i,] <- modes.new } out$boot.modes <- modes.mat out$mode.sd <- apply(modes.mat,2,sd) out$prior.fit <- DS.GF.obj$prior.fit class(out) <- "DS_GF_macro_mode" return(out) }, "mean" = { out <- list() if(sum(DS.GF.obj$LP.par^2) == 0){ out$model.mean <- DS.GF.obj$g.par[1] m.new = 0 } else { out$model.mean <- sintegral(DS.GF.obj$prior.fit$theta.vals, DS.GF.obj$prior.fit$theta.vals*DS.GF.obj$prior.fit$ds.prior)$int m.new = length(DS.GF.obj$LP.par) } par.mean.vec <- NULL for(i in 1:iters){ L2.norm.thres <- 1.1*sqrt(sum((DS.GF.obj$LP.max.smt[1:DS.GF.obj$m.val]^2))) L2.norm <- L2.norm.thres + 1 while(L2.norm > L2.norm.thres){ par.g <- c(NA,NA) while(!is.finite(par.g[1])==TRUE | !is.finite(par.g[2])==TRUE){ ifelse(pred.type == "posterior", new.df <- rPPD.ds(DS.GF.obj,1,pred.type = "posterior")$first.set, new.df <- rPPD.ds(DS.GF.obj,1, pred.type = "prior")$first.set) possibleError <- tryCatch(par.g <- gMLE.nn(new.df$y, new.df$se, fixed = FALSE, method = "DL")$estimate, error = function(e) e ) er.check <- !inherits(possibleError, "error") if(er.check == TRUE){ par.g <- gMLE.nn(new.df$y, new.df$se, fixed = FALSE, method = "DL")$estimate } else { par.g <- c(NA, NA) } } new.LPc <- DS.prior.nnu(new.df, max.m = m.new, start.par = par.g) L2.norm <- sqrt(sum((new.LPc$LP.par)^2)) } if(sum(new.LPc$LP.par^2) == 0){ par.mean.vec[i] <- par.g[1] } else { new.LP.ME <- maxent.obj.convert(new.LPc) par.mean.vec[i] <- sintegral(new.LP.ME$prior.fit$theta.vals, new.LP.ME$prior.fit$theta.vals*new.LP.ME$prior.fit$ds.prior)$int } } out$boot.mean <- par.mean.vec out$mean.sd <- sd(par.mean.vec) out$prior.fit <- DS.GF.obj$prior.fit class(out) <- "DS_GF_macro_mean" return(out) } ) } ) }
/scratch/gouwar.j/cran-all/cranData/BayesGOF/R/DS.macro.inf.nnu.R
DS.macro.inf.pge <- function(DS.GF.obj, num.modes = 1, exposure, iters = 25, method = c("mean","mode"), pred.type = c("posterior","prior") ){ # INPUTS # DS.GF.obj AutoBayes-DataCorrect object # num.modes For mode inference: number of modes expected # method mean finds the bootstrap mean and sd (parameteric) # mode finds the bootstrap mode and sd (DS) # OUTPUTS # model.modes modes of the DC prior generated by object # mode.sd standard deviation of modes (generated through simulation) # prior.fit dataframe of prior information for plotting # boot.modes/means bootstrap mode or mean for simulation switch(DS.GF.obj$LP.type, "L2" = { method = match.arg(method) switch(method, "mode" = { out <- list() modes.mat <- matrix(0, nrow = iters, ncol = num.modes) if(sum(DS.GF.obj$LP.par^2) == 0){ m.new = 0 out$model.modes <- Local.Mode(DS.GF.obj$prior.fit$theta.vals, DS.GF.obj$prior.fit$parm.prior) if(out$model.modes[1] == DS.GF.obj$prior.fit$theta.vals[1]) out$model.modes <- out$model.modes[-1] } else { m.new = length(DS.GF.obj$LP.par) out$model.modes <- Local.Mode(DS.GF.obj$prior.fit$theta.vals, DS.GF.obj$prior.fit$ds.prior) if(out$model.modes[1] == DS.GF.obj$prior.fit$theta.vals[1]){ out$model.modes <- out$model.modes[-1]} } for(i in 1:iters){ len.mode = num.modes+1 while(len.mode != num.modes){ par.g <- c(NA,NA) while(!is.finite(par.g[1])==TRUE | !is.finite(par.g[2])==TRUE){ ifelse(pred.type == "posterior", new.df <- rPPD.ds(DS.GF.obj,1,pred.type = "posterior", exposure = exposure)$first.set, new.df <- rPPD.ds(DS.GF.obj,1, pred.type = "prior", exposure = exposure)$first.set) possibleError <- tryCatch(par.g <- gMLE.pg(new.df, exposure = exposure, start.par = DS.GF.obj$g.par), error = function(e) e ) er.check <- !inherits(possibleError, "error") if(er.check == TRUE){ par.g <- gMLE.pg(new.df, exposure = exposure, start.par = DS.GF.obj$g.par) } else { par.g <- c(NA, NA) } } new.LPc <- DS.prior.pgu(new.df/exposure, max.m = m.new, start.par = par.g) if(sum(new.LPc$LP.par^2) == 0){ modes.new <- Local.Mode(new.LPc$prior.fit$theta.vals, new.LPc$prior.fit$parm.prior) } else { modes.new <- Local.Mode(new.LPc$prior.fit$theta.vals, new.LPc$prior.fit$ds.prior) } len.mode <- length(modes.new) } modes.mat[i,] <- modes.new } out$boot.modes <- modes.mat out$mode.sd <- apply(modes.mat,2,sd) out$prior.fit <- DS.GF.obj$prior.fit class(out) <- "DS_GF_macro_mode" return(out) }, "mean" = { out <- list() if(sum(DS.GF.obj$LP.par^2) == 0){ m.new = 0 out$model.mean <- DS.GF.obj$g.par[1]*DS.GF.obj$g.par[2] } else { m.new = length(DS.GF.obj$LP.par) out$model.mean <- sintegral(DS.GF.obj$prior.fit$theta.vals, DS.GF.obj$prior.fit$theta.vals*DS.GF.obj$prior.fit$ds.prior)$int } par.mean.vec <- NULL for(i in 1:iters){ par.g <- c(NA,NA) while(!is.finite(par.g[1])==TRUE | !is.finite(par.g[2])==TRUE){ ifelse(pred.type == "posterior", new.df <- rPPD.ds(DS.GF.obj,1,pred.type = "posterior", exposure = exposure)$first.set, new.df <- rPPD.ds(DS.GF.obj,1, pred.type = "prior", exposure = exposure)$first.set) possibleError <- tryCatch(par.g <- gMLE.pg(new.df, exposure = exposure, start.par = DS.GF.obj$g.par), error = function(e) e ) er.check <- !inherits(possibleError, "error") if(er.check == TRUE){ par.g <- gMLE.pg(new.df, exposure = exposure, start.par = DS.GF.obj$g.par) } else { par.g <- c(NA, NA) } } new.LPc <- DS.prior.pgu(new.df/exposure, max.m = m.new, start.par = par.g) if(sum(new.LPc$LP.par^2) == 0){ par.mean.vec[i] <- par.g[1]*par.g[2] } else { par.mean.vec[i] <- sintegral(new.LPc$prior.fit$theta.vals, new.LPc$prior.fit$theta.vals*new.LPc$prior.fit$ds.prior)$int } } if(sum(DS.GF.obj$LP.par^2) == 0){ out$model.mean <- DS.GF.obj$g.par[1]*DS.GF.obj$g.par[2] } else { out$model.mean <- sintegral(DS.GF.obj$prior.fit$theta.vals, DS.GF.obj$prior.fit$theta.vals*DS.GF.obj$prior.fit$ds.prior)$int } out$boot.mean <- par.mean.vec out$mean.sd <- sd(par.mean.vec) out$prior.fit <- DS.GF.obj$prior.fit class(out) <- "DS_GF_macro_mean" return(out) } ) }, "MaxEnt" = { method = match.arg(method) switch(method, "mode" = { out <- list() modes.mat <- matrix(0, nrow = iters, ncol = num.modes) #needed to add a check so that it does not account for the first value if(sum(DS.GF.obj$LP.par^2) == 0){ m.new = 0 out$model.modes <- Local.Mode(DS.GF.obj$prior.fit$theta.vals, DS.GF.obj$prior.fit$parm.prior) if(out$model.modes[1] == DS.GF.obj$prior.fit$theta.vals[1]) out$model.modes <- out$model.modes[-1] } else { m.new = length(DS.GF.obj$LP.par) out$model.modes <- Local.Mode(DS.GF.obj$prior.fit$theta.vals, DS.GF.obj$prior.fit$ds.prior) if(out$model.modes[1] == DS.GF.obj$prior.fit$theta.vals[1]){ out$model.modes <- out$model.modes[-1]} } for(i in 1:iters){ len.mode = num.modes+1 while(len.mode != num.modes){ L2.norm.thres <- 1.1*sqrt(sum((DS.GF.obj$LP.max.smt[1:DS.GF.obj$m.val]^2))) L2.norm <- L2.norm.thres + 1 while(L2.norm > L2.norm.thres){ par.g <- c(NA,NA) while(!is.finite(par.g[1])==TRUE | !is.finite(par.g[2])==TRUE){ ifelse(pred.type == "posterior", new.df <- rPPD.ds(DS.GF.obj,1,pred.type = "posterior", exposure = exposure)$first.set, new.df <- rPPD.ds(DS.GF.obj,1, pred.type = "prior", exposure = exposure)$first.set) possibleError <- tryCatch(par.g <- gMLE.pg(new.df, exposure = exposure, start.par = DS.GF.obj$g.par), error = function(e) e ) er.check <- !inherits(possibleError, "error") if(er.check == TRUE){ par.g <- gMLE.pg(new.df, exposure = exposure, start.par = DS.GF.obj$g.par) } else { par.g <- c(NA, NA) } } new.LPc <- DS.prior.pgu(new.df/exposure, max.m = m.new, start.par = par.g) L2.norm <- sqrt(sum((new.LPc$LP.par)^2)) } if(sum(new.LPc$LP.par^2) == 0){ modes.new <- new.LPc$prior.fit$theta.vals[which.max(new.LPc$prior.fit$parm.prior)] } else { new.LP.ME <- maxent.obj.convert(new.LPc) modes.new <- Local.Mode(new.LP.ME$prior.fit$theta.vals, new.LP.ME$prior.fit$ds.prior) } len.mode <- length(modes.new) } modes.mat[i,] <- modes.new } out$boot.modes <- modes.mat out$mode.sd <- apply(modes.mat,2,sd) out$prior.fit <- DS.GF.obj$prior.fit class(out) <- "DS_GF_macro_mode" return(out) }, "mean" = { out <- list() if(sum(DS.GF.obj$LP.par^2) == 0){ m.new = 0 out$model.mean <- DS.GF.obj$g.par[1]*DS.GF.obj$g.par[2] } else { m.new = length(DS.GF.obj$LP.par) out$model.mean <- sintegral(DS.GF.obj$prior.fit$theta.vals, DS.GF.obj$prior.fit$theta.vals*DS.GF.obj$prior.fit$ds.prior)$int } par.mean.vec <- NULL for(i in 1:iters){ L2.norm.thres <- 1.1*sqrt(sum((DS.GF.obj$LP.max.smt[1:DS.GF.obj$m.val]^2))) L2.norm <- L2.norm.thres + 1 while(L2.norm > L2.norm.thres){ par.g <- c(NA,NA) while(!is.finite(par.g[1])==TRUE | !is.finite(par.g[2])==TRUE){ ifelse(pred.type == "posterior", new.df <- rPPD.ds(DS.GF.obj,1,pred.type = "posterior", exposure = exposure)$first.set, new.df <- rPPD.ds(DS.GF.obj,1, pred.type = "prior", exposure = exposure)$first.set) possibleError <- tryCatch(par.g <- gMLE.pg(new.df, exposure = exposure, start.par = DS.GF.obj$g.par), error = function(e) e ) er.check <- !inherits(possibleError, "error") if(er.check == TRUE){ par.g <- gMLE.pg(new.df, exposure = exposure, start.par = DS.GF.obj$g.par) } else { par.g <- c(NA, NA) } } new.LPc <- DS.prior.pgu(new.df/exposure, max.m = m.new, start.par = par.g) L2.norm <- sqrt(sum((new.LPc$LP.par)^2)) } if(sum(new.LPc$LP.par^2) == 0){ par.mean.vec[i] <- par.g[1]*par.g[2] } else { new.LP.ME <- maxent.obj.convert(new.LPc) par.mean.vec[i] <- sintegral(new.LP.ME$prior.fit$theta.vals, new.LP.ME$prior.fit$theta.vals*new.LP.ME$prior.fit$ds.prior)$int } } out$boot.mean <- par.mean.vec out$mean.sd <- sd(par.mean.vec) out$prior.fit <- DS.GF.obj$prior.fit class(out) <- "DS_GF_macro_mean" return(out) } ) } ) }
/scratch/gouwar.j/cran-all/cranData/BayesGOF/R/DS.macro.inf.pge.R
DS.macro.inf.pgu <- function(DS.GF.obj, num.modes =1 , iters = 25, method = c("mean","mode"), pred.type = c("posterior","prior")){ # INPUTS # DS.GF.obj AutoBayes-DataCorrect object # num.modes For mode inference: number of modes expected # method mean finds the bootstrap mean and sd (parameteric) # mode finds the bootstrap mode and sd (DS) # OUTPUTS # model.modes modes of the DC prior generated by object # mode.sd standard deviation of modes (generated through simulation) # prior.fit dataframe of prior information for plotting # boot.modes/means bootstrap mode or mean for simulation switch(DS.GF.obj$LP.type, "L2" = { method = match.arg(method) switch(method, "mode" = { out <- list() modes.mat <- matrix(0, nrow = iters, ncol = num.modes) #needed to add a check so that it does not account for the first value if(sum(DS.GF.obj$LP.par^2) == 0){ m.new = 0 out$model.modes <- Local.Mode(DS.GF.obj$prior.fit$theta.vals, DS.GF.obj$prior.fit$parm.prior) if(out$model.modes[1] == DS.GF.obj$prior.fit$theta.vals[1]) out$model.modes <- out$model.modes[-1] } else { m.new = length(DS.GF.obj$LP.par) out$model.modes <- Local.Mode(DS.GF.obj$prior.fit$theta.vals, DS.GF.obj$prior.fit$ds.prior) if(out$model.modes[1] == DS.GF.obj$prior.fit$theta.vals[1]){ out$model.modes <- out$model.modes[-1]} } for(i in 1:iters){ len.mode = num.modes+1 while(len.mode != num.modes){ par.g <- c(NA,NA) while(!is.finite(par.g[1])==TRUE | !is.finite(par.g[2])==TRUE){ ifelse(pred.type == "posterior", y.new <- rPPD.ds(DS.GF.obj,1,pred.type = "posterior")$first.set, y.new <- rPPD.ds(DS.GF.obj,1, pred.type = "prior")$first.set) possibleError <- tryCatch(par.g <- gMLE.pg(y.new, start.par = DS.GF.obj$g.par), error = function(e) e ) er.check <- !inherits(possibleError, "error") if(er.check == TRUE){ par.g <- gMLE.pg(y.new, start.par = DS.GF.obj$g.par) } else { par.g <- c(NA, NA) } } new.LPc <- DS.prior.pgu(y.new, max.m = m.new, start.par = par.g) if(sum(new.LPc$LP.par^2) == 0){ modes.new <- Local.Mode(new.LPc$prior.fit$theta.vals, new.LPc$prior.fit$parm.prior) } else { modes.new <- Local.Mode(new.LPc$prior.fit$theta.vals, new.LPc$prior.fit$ds.prior) } len.mode <- length(modes.new) } modes.mat[i,] <- modes.new } out$boot.modes <- modes.mat out$mode.sd <- apply(modes.mat,2,sd) out$prior.fit <- DS.GF.obj$prior.fit class(out) <- "DS_GF_macro_mode" return(out) }, "mean" = { out <- list() if(sum(DS.GF.obj$LP.par^2) == 0){ m.new = 0 out$model.mean <- DS.GF.obj$g.par[1]*DS.GF.obj$g.par[2] } else { m.new = length(DS.GF.obj$LP.par) out$model.mean <- sintegral(DS.GF.obj$prior.fit$theta.vals, DS.GF.obj$prior.fit$theta.vals*DS.GF.obj$prior.fit$ds.prior)$int } par.mean.vec <- NULL for(i in 1:iters){ par.g <- c(NA,NA) while(!is.finite(par.g[1])==TRUE | !is.finite(par.g[2])==TRUE){ ifelse(pred.type == "posterior", y.new <- rPPD.ds(DS.GF.obj,1,pred.type = "posterior")$first.set, y.new <- rPPD.ds(DS.GF.obj,1, pred.type = "prior")$first.set) possibleError <- tryCatch(par.g <- gMLE.pg(y.new, start.par = DS.GF.obj$g.par), error = function(e) e ) er.check <- !inherits(possibleError, "error") if(er.check == TRUE){ par.g <- gMLE.pg(y.new, start.par = DS.GF.obj$g.par) } else { par.g <- c(NA, NA) } } new.LPc <- DS.prior.pgu(y.new, max.m = m.new, start.par = par.g) if(sum(new.LPc$LP.par^2) == 0){ par.mean.vec[i] <- par.g[1]*par.g[2] } else { par.mean.vec[i] <- sintegral(new.LPc$prior.fit$theta.vals, new.LPc$prior.fit$theta.vals*new.LPc$prior.fit$ds.prior)$int } } out$boot.mean <- par.mean.vec out$mean.sd <- sd(par.mean.vec) out$prior.fit <- DS.GF.obj$prior.fit class(out) <- "DS_GF_macro_mean" return(out) } ) }, "MaxEnt" = { method = match.arg(method) switch(method, "mode" = { out <- list() modes.mat <- matrix(0, nrow = iters, ncol = num.modes) #needed to add a check so that it does not account for the first value if(sum(DS.GF.obj$LP.par^2) == 0){ m.new = 0 out$model.modes <- Local.Mode(DS.GF.obj$prior.fit$theta.vals, DS.GF.obj$prior.fit$parm.prior) if(out$model.modes[1] == DS.GF.obj$prior.fit$theta.vals[1]) out$model.modes <- out$model.modes[-1] } else { m.new = length(DS.GF.obj$LP.par) out$model.modes <- Local.Mode(DS.GF.obj$prior.fit$theta.vals, DS.GF.obj$prior.fit$ds.prior) if(out$model.modes[1] == DS.GF.obj$prior.fit$theta.vals[1]){ out$model.modes <- out$model.modes[-1]} } for(i in 1:iters){ len.mode = num.modes+1 while(len.mode != num.modes){ L2.norm.thres <- 1.1*sqrt(sum((DS.GF.obj$LP.max.smt[1:DS.GF.obj$m.val]^2))) L2.norm <- L2.norm.thres + 1 while(L2.norm > L2.norm.thres){ par.g <- c(NA,NA) while(!is.finite(par.g[1])==TRUE | !is.finite(par.g[2])==TRUE){ ifelse(pred.type == "posterior", y.new <- rPPD.ds(DS.GF.obj,1,pred.type = "posterior")$first.set, y.new <- rPPD.ds(DS.GF.obj,1, pred.type = "prior")$first.set) possibleError <- tryCatch(par.g <- gMLE.pg(y.new, start.par = DS.GF.obj$g.par), error = function(e) e ) er.check <- !inherits(possibleError, "error") if(er.check == TRUE){ par.g <- gMLE.pg(y.new, start.par = DS.GF.obj$g.par) } else { par.g <- c(NA, NA) } } new.LPc <- DS.prior.pgu(y.new, max.m = m.new, start.par = par.g) L2.norm <- sqrt(sum((new.LPc$LP.par)^2)) } if(sum(new.LPc$LP.par^2) == 0){ modes.new <- new.LPc$prior.fit$theta.vals[which.max(new.LPc$prior.fit$parm.prior)] } else { new.LP.ME <- maxent.obj.convert(new.LPc) modes.new <- Local.Mode(new.LP.ME$prior.fit$theta.vals, new.LP.ME$prior.fit$ds.prior) } len.mode <- length(modes.new) } modes.mat[i,] <- modes.new } out$boot.modes <- modes.mat out$mode.sd <- apply(modes.mat,2,sd) out$prior.fit <- DS.GF.obj$prior.fit class(out) <- "DS_GF_macro_mode" return(out) }, "mean" = { out <- list() if(sum(DS.GF.obj$LP.par^2) == 0){ m.new = 0 out$model.mean <- DS.GF.obj$g.par[1]*DS.GF.obj$g.par[2] } else { m.new = length(DS.GF.obj$LP.par) out$model.mean <- sintegral(DS.GF.obj$prior.fit$theta.vals, DS.GF.obj$prior.fit$theta.vals*DS.GF.obj$prior.fit$ds.prior)$int } par.mean.vec <- NULL for(i in 1:iters){ L2.norm.thres <- 1.1*sqrt(sum((DS.GF.obj$LP.max.smt[1:DS.GF.obj$m.val]^2))) L2.norm <- L2.norm.thres + 1 while(L2.norm > L2.norm.thres){ par.g <- c(NA,NA) while(!is.finite(par.g[1])==TRUE | !is.finite(par.g[2])==TRUE){ ifelse(pred.type == "posterior", y.new <- rPPD.ds(DS.GF.obj,1,pred.type = "posterior")$first.set, y.new <- rPPD.ds(DS.GF.obj,1, pred.type = "prior")$first.set) possibleError <- tryCatch(par.g <- gMLE.pg(y.new, start.par = DS.GF.obj$g.par), error = function(e) e ) er.check <- !inherits(possibleError, "error") if(er.check == TRUE){ par.g <- gMLE.pg(y.new, start.par = DS.GF.obj$g.par) } else { par.g <- c(NA, NA) } } new.LPc <- DS.prior.pgu(y.new, max.m = m.new, start.par = par.g) L2.norm <- sqrt(sum((new.LPc$LP.par)^2)) } if(sum(new.LPc$LP.par^2) == 0){ par.mean.vec[i] <- par.g[1]*par.g[2] } else { new.LP.ME <- maxent.obj.convert(new.LPc) par.mean.vec[i] <- sintegral(new.LP.ME$prior.fit$theta.vals, new.LP.ME$prior.fit$theta.vals*new.LP.ME$prior.fit$ds.prior)$int } } out$boot.mean <- par.mean.vec out$mean.sd <- sd(par.mean.vec) out$prior.fit <- DS.GF.obj$prior.fit class(out) <- "DS_GF_macro_mean" return(out) } ) } ) }
/scratch/gouwar.j/cran-all/cranData/BayesGOF/R/DS.macro.inf.pgu.R
DS.micro.inf <- function(DS.GF.obj, y.0, n.0 = NULL, e.0 = NULL){ fam = DS.GF.obj$fam switch(fam, "Normal" = { DS.micro.inf.nnu(DS.GF.obj, y.0 = y.0, se.0 = n.0) }, "Binomial" = { DS.micro.inf.bbu(DS.GF.obj, y.0 = y.0, n.0 = n.0) }, "Poisson" = { if(is.null(e.0) == TRUE){ DS.micro.inf.pgu(DS.GF.obj, y.0 = y.0) } else { DS.micro.inf.pge(DS.GF.obj, y.0 = y.0, e.0 = e.0) } } ) }
/scratch/gouwar.j/cran-all/cranData/BayesGOF/R/DS.micro.inf.R
DS.micro.inf.bbu <- function(DS.GF.obj, y.0, n.0){ fam <- "Binomial" out <- list() ##### PEB Posterior and Family Calculations post.alph.i <- y.0 + DS.GF.obj$g.par[1] post.beta.i <- n.0 - y.0 + DS.GF.obj$g.par[2] ###Set up conversion based on d(u) theta.conv <- qbeta(DS.GF.obj$UF.data$UF.x, DS.GF.obj$g.par[1], DS.GF.obj$g.par[2]) PEB.pos.den <- dbeta(theta.conv,post.alph.i, post.beta.i) #in terms of theta out$PEB.mode <- theta.conv[which.max(PEB.pos.den)] out$PEB.mean <- post.alph.i /( post.alph.i + post.beta.i) if(sum(DS.GF.obj$LP.par^2)==0){ out$DS.mean <- out$PEB.mean out$DS.mode <- out$PEB.mode out$post.vec <- c(out$PEB.mean, out$DS.mean, out$PEB.mode, out$DS.mode) out$post.fit <- data.frame(theta.vals = theta.conv, parm.pos = PEB.pos.den) out$study <- c(y.0, n.0) } else { wght.den <- weight.fun.univ(DS.GF.obj$UF.data$UF.x, DS.GF.obj$g.par[1], DS.GF.obj$g.par[2], post.alph.i, post.beta.i, family = fam) # in terms of u ##### LP posterior calculations denom <- sintegral(DS.GF.obj$UF.data$UF.x, DS.GF.obj$UF.data$UF.y*wght.den)$int # in terms of u LP.pos.den <- PEB.pos.den * (DS.GF.obj$UF.data$UF.y/denom) #in terms of theta out$post.fit <- data.frame(theta.vals = theta.conv, parm.pos = PEB.pos.den, ds.pos = LP.pos.den) out$DS.mean <- sintegral(DS.GF.obj$UF.data$UF.x, theta.conv*DS.GF.obj$UF.data$UF.y*wght.den)$int / denom #in terms of u out$DS.mode <- out$post.fit$theta.vals[which.max(out$post.fit$ds.pos)] out$post.vec <- c(out$PEB.mean, out$DS.mean, out$PEB.mode, out$DS.mode) out$study <- c(y.0, n.0) } class(out) <- "DS_GF_micro" names(out$post.vec) <- c("PEB_MN", "DS_MN", "PEB_MD", "DS_MD") names(out$PEB.mean) <- NULL; names(out$PEB.mode) <- NULL; names(out$DS.mean) <- NULL; names(out$DS.mode) <- NULL return(out) }
/scratch/gouwar.j/cran-all/cranData/BayesGOF/R/DS.micro.inf.bbu.R
DS.micro.inf.nnu <- function(DS.GF.obj, y.0, se.0){ fam <- "Normal" out <- list() lambda.i <- function(s.i, tau.2){s.i^2/(s.i^2+tau.2)} ###Find Posterior Values post.mu.i <- lambda.i(se.0, DS.GF.obj$g.par[2]) * DS.GF.obj$g.par[1] + (1-lambda.i(se.0, DS.GF.obj$g.par[2]))* y.0 post.tau2.i <- (1-lambda.i(se.0, DS.GF.obj$g.par[2]))*se.0^2 #output is VARIANCE ###Set up conversion based on d(u) theta.conv <- qnorm(DS.GF.obj$UF.data$UF.x, DS.GF.obj$g.par[1], sd = sqrt(DS.GF.obj$g.par[2])) PEB.pos.den <- dnorm(theta.conv, post.mu.i, sd = sqrt(post.tau2.i)) #in terms of theta out$PEB.mode <- theta.conv[which.max(PEB.pos.den)] out$PEB.mean <- post.mu.i if(sum(DS.GF.obj$LP.par^2)==0){ out$DS.mean <- out$PEB.mean out$DS.mode <- out$PEB.mode out$post.vec <- c(out$PEB.mean, out$DS.mean, out$PEB.mode, out$DS.mode) out$post.fit <- data.frame(theta.vals = theta.conv, parm.pos = PEB.pos.den) out$study <- c(y.0, se.0) } else { wght.den <- weight.fun.univ(DS.GF.obj$UF.data$UF.x, DS.GF.obj$g.par[1], DS.GF.obj$g.par[2], post.mu.i, post.tau2.i, family = fam) # in terms of u ##### LP posterior calculations denom <- sintegral(DS.GF.obj$UF.data$UF.x, DS.GF.obj$UF.data$UF.y*wght.den)$int # in terms of u LP.pos.den <- PEB.pos.den * (DS.GF.obj$UF.data$UF.y/denom) #in terms of theta out$post.fit <- data.frame(theta.vals = theta.conv, parm.pos = PEB.pos.den, ds.pos = LP.pos.den) out$DS.mean <- sintegral(DS.GF.obj$UF.data$UF.x, theta.conv*DS.GF.obj$UF.data$UF.y*wght.den)$int / denom #in terms of u out$DS.mode <- out$post.fit$theta.vals[which.max(out$post.fit$ds.pos)] out$post.vec <- c(out$PEB.mean, out$DS.mean, out$PEB.mode, out$DS.mode) out$study <- c(y.0, se.0) } class(out) <- "DS_GF_micro" names(out$post.vec) <- c("PEB_MN", "DS_MN", "PEB_MD", "DS_MD") names(out$PEB.mean) <- NULL; names(out$PEB.mode) <- NULL; names(out$DS.mean) <- NULL; names(out$DS.mode) <- NULL return(out) }
/scratch/gouwar.j/cran-all/cranData/BayesGOF/R/DS.micro.inf.nnu.R