I have three or more independent variables represented as R vectors, like so:
A <- c(1,2,3)
B <- factor(c(\'x\',\'y\'))
C <- c(0.1,0.5)
I can never remember that standard function expand.grid
. So here's another version.
crossproduct <- function(...,FUN='data.frame') {
args <- list(...)
n1 <- names(args)
n2 <- sapply(match.call()[1+1:length(args)], as.character)
nn <- if (is.null(n1)) n2 else ifelse(n1!='',n1,n2)
dims <- sapply(args,length)
dimtot <- prod(dims)
reps <- rev(cumprod(c(1,rev(dims))))[-1]
cols <- lapply(1:length(dims), function(j)
args[[j]][1+((1:dimtot-1) %/% reps[j]) %% dims[j]])
names(cols) <- nn
do.call(match.fun(FUN),cols)
}
A <- c(1,2,3)
B <- factor(c('x','y'))
C <- c(.1,.5)
crossproduct(A,B,C)
crossproduct(A,B,C, FUN=function(...) paste(...,sep='_'))