Cartesian product data frame

后端 未结 7 2082
臣服心动
臣服心动 2020-11-29 18:47

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)
相关标签:
7条回答
  • 2020-11-29 19:46

    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='_'))
    
    0 讨论(0)
提交回复
热议问题