R/summary.R

Defines functions summary.simulation

Documented in summary.simulation

#' Print summary of simulations.
#'
#' \code{summary.simulation} calculates a summary of a given variable across all,
#' or a portion of, the simulations.
#'
#' @param sim A list of class 'simulation' generated by the function
#'   \code{simulate}.
#' @param outcome A string with the variable name across which to generate the
#'   summaries.
#' @param params If NULL, the function will return a summary across all
#'   generated simulation parameters. A character vector can also be included
#'   here, in which case the function will return summaries for only the
#'   selected parameter names. Finally, users can input a list, with the names
#'   of the elements corresponding to parameter names, and the values of each
#'   element providing a vector with the parameter values to be included in the
#'   summary. In all cases, the summary will collapse across all parameters or
#'   parameter values that are excluded from \code{params}.
#' @param func The function to be used to generate the summary (e.g., mean, sum).
#' @param ... Any other arguments to be passed to func.
#' @return Returns a data frame with one row per set of unique simulation tests.
#' @seealso \code{\link{simulate}}
#' @examples
#' # will calculate the mean for all 'sig' values in all simulations where N=200,
#' # and all simulations where N=300
#' summary(power_sim, 'sig', params=list(N=c(200, 300)))
#' @export
summary.simulation <- function(sim, outcome, params=NULL, func=mean, ...) {
    if (is.null(params)) {
        grid <- sim$tests
    } else if (is.list(params)) {
        paramNames <- names(params)
        grid <- sim$tests

        # it is assumed that each list element has a vector with the values to
        # be included for that parameter; so we loop through each parameter and
        # pare down the grid to only include those values
        for (p in 1:length(params)) {
            grid <- grid[grid[, paramNames[p]] %in% params[[p]], , drop=FALSE]
        }

        grid <- unique(grid[, paramNames, drop=FALSE])
    } else if (is.vector(params)) {
        grid <- unique(sim$tests[, params, drop=FALSE])
    }

    if (nrow(grid) > 0) {
        results <- grid
        # loop through each combination of tests
        for (i in 1:nrow(grid)) {
            data <- sim$results

            # loop through each parameter value individually and filter down data
            for (p in 1:ncol(grid)) {
                paramName <- paste0(names(sim$tests)[p], '.test')
                data <- data[data[, paramName] == sim$tests[i, p], ]
            }

            results[i, as.character(substitute(func))] <- func(data[, outcome], ...)
        }
    } else {
        results <- func(sim$results[, outcome], ...)
    }
    return(results)
}
jeff-hughes/simulateR documentation built on May 19, 2019, 1:45 a.m.