Pascal
Pascal

Reputation: 583

How to expand.grid on vectors sets rather than single elements

So, I have the following four vectors

a1 <- c(11, 12)
a2 <- c(21, 22)

b1 <- c(31, 32)
b2 <- c(41, 42)

and what I want to have in the end is a data frame that looks like

  p1 p2 p3 p4
1 11 12 31 32
2 21 22 31 32
3 11 12 41 42
4 21 22 41 42

i.e. every possible combination of the two a vectors with the two b vectors.

What I did is

ab <-  expand.grid(list(a1, a2), list(b1,b2))
ab.new <- ab %>% separate(Var1, c("p1", "p2"), sep = ",") 
             %>% separate(Var2, c("p3", "p4"), sep = ",")

and what I end up with is

    p1   p2   p3   p4
1 c(11  12) c(31  32)
2 c(21  22) c(31  32)
3 c(11  12) c(41  42)
4 c(21  22) c(41  42)

What are those c(s doing in there and how to get them out? Or, what did I do wrong in using %>%?

Upvotes: 4

Views: 871

Answers (2)

chinsoon12
chinsoon12

Reputation: 25225

using only base to create a general function which expand.grid on sets of vectors:

permu.sets <- function(listoflist) {
    #assumes that each list within listoflist contains vectors of equal lengths
    temp <- expand.grid(listoflist)  
    do.call(cbind, lapply(temp, function(x) do.call(rbind, x)))
} #permu.sets

a1 <- c(11, 12)
a2 <- c(21, 22)
b1 <- c(31, 32)
b2 <- c(41, 42)
permu.sets(list(list(a1, a2), list(b1,b2)))

diff from @akrun answer is how to handle results from expand.grid without requiring dimensions being explicitly passed

Upvotes: 0

akrun
akrun

Reputation: 887158

We could try

do.call(cbind,lapply(expand.grid(list(a1, a2), list(b1,b2)),
               function(x) matrix(do.call(c, x), 4, 2, byrow=TRUE)))
#     [,1] [,2] [,3] [,4]
#[1,]   11   12   31   32
#[2,]   21   22   31   32
#[3,]   11   12   41   42
#[4,]   21   22   41   42

Upvotes: 3

Related Questions