File: Expand.R

package info (click to toggle)
r-cran-lava 1.8.1%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,816 kB
  • sloc: sh: 13; makefile: 2
file content (39 lines) | stat: -rw-r--r-- 1,195 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
##' Create a Data Frame from All Combinations of Factors
##'
##' Simple wrapper of the 'expand.grid' function.  If x is a table
##' then a data frame is returned with one row pr individual
##' observation.
##' @title Create a Data Frame from All Combinations of Factors
##' @param _data Data.frame
##' @param ... vectors, factors or a list containing these
##' @author Klaus K. Holst
##' @export
##' @aliases Expand
##' @examples
##' dd <- Expand(iris, Sepal.Length=2:8, Species=c("virginica","setosa"))
##' summary(dd)
##'
##' T <- with(warpbreaks, table(wool, tension))
##' Expand(T)
Expand <- function(`_data`, ...) {
    if (missing(`_data`)) {
        return(expand.grid(...))
    }
    if (inherits(`_data`, "table")) {
        M <- as.data.frame(`_data`)
        idx <- rep(seq(nrow(M)), M[, ncol(M)])
        return(M[idx, -ncol(M), drop=FALSE])
    }
    if (!inherits(`_data`, "data.frame")) {
        return(expand.grid(`_data`, ...))
    }
    dots <- list(...)
    nn <- names(dots)
    for (n in nn) {
        y <- dots[[n]]
        if (is.factor(`_data`[1, n])) {
            dots[[n]] <- factor(y, levels=levels(`_data`[1, n]))
        }
    }
    do.call("expand.grid", dots)
}