Cartesian product data frame

后端 未结 7 2144
臣服心动
臣服心动 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:26

    Here's a way to do both, using Ramnath's suggestion of expand.grid:

    f <- function(x,y,z) paste(x,y,z,sep="+")
    d <- expand.grid(x=A, y=B, z=C)
    d$D <- do.call(f, d)
    

    Note that do.call works on d "as-is" because a data.frame is a list. But do.call expects the column names of d to match the argument names of f.

提交回复
热议问题