How can I get a vector of combinations in R?

Viewed 44

my data set looks like this (in the real dataset they're like 12 observations)

ID    String
1      BDH
2      BDHV
3      PA
4      PmA

And I want all combinations, but taking it into account that 1,2 = 2,1

So the desired dataset looks like this:

ID   String
1      BDH
2      BDHV
3      PA
4      PmA
12     BDH;BDHV
123    BDH;BDHV;PA
1234   BDH;BDHV;PA;PmA
23     BDHV;PA
234    BDHV;PA;PmA
34     PA;PmA

How can I do this using R?

I think I got to use paste(, sep=";") for the String variable, but still don't know how to make the combinations.

1 Answers

We can use combn

out <- do.call(rbind, lapply(df1$ID, function(i) 
 data.frame(ID = combn(df1$ID, i, function(x) paste(x, collapse="")), 
  String = combn(df1$String, i, function(x) paste(x, collapse=";")))))

-output

out
#     ID          String
#1     1             BDH
#2     2            BDHV
#3     3              PA
#4     4             PmA
#5    12        BDH;BDHV
#6    13          BDH;PA
#7    14         BDH;PmA
#8    23         BDHV;PA
#9    24        BDHV;PmA
#10   34          PA;PmA
#11  123     BDH;BDHV;PA
#12  124    BDH;BDHV;PmA
#13  134      BDH;PA;PmA
#14  234     BDHV;PA;PmA
#15 1234 BDH;BDHV;PA;PmA
Related