0

I have a dataframe with 187 pairs of items across two variables, some of which are repeated. I want to create a new dataframe that pairs each item in the first variable with each item in the second (including repetitions), essentially creating a DF with 187*187 items. So I want every item in variable A to co-occur with every item in variable B. Each item will therefore be repeated 187 times.

I think I need to use a for-loop but I'm not sure how to approach it.

As an example, take the data mydf:

 library(tibble)
 mydf <- tribble(~GroupA, ~GroupB,
            "A", "X",
            "B", "Y", 
            "C", "Z")

I want to create something that looks like this:

 GroupA    GroupB
 A          X
 A          Y
 A          Z
 B          X 
 B          Y
 B          Z
 C          X
 C          Y
 C          Z

Is there a simple way of doing this?

Catherine Laing
  • 475
  • 6
  • 18
  • 1
    Take a look at `?expand.grid` or `?tidyr::crossing` – MrFlick Oct 25 '19 at 15:09
  • Hi Catherine,@MrFlick meant something like this as_tibble(expand.grid(c("A","B","C"),c("X","Y","Z"))) – StupidWolf Oct 25 '19 at 15:11
  • Or just `expand.grid(mydf)` – nghauran Oct 25 '19 at 15:13
  • `expand.grid` doesn't work here because I have repeated items in my dataframe, which I need to keep (I've edited my question to explain this). Basically, each row of Variable A needs to be paired with each row of variable B, regardless of its content. – Catherine Laing Oct 25 '19 at 15:36

0 Answers0