Lucas
Lucas

Reputation: 1177

R. Create dataframe with conditional combinations of elements from vector

I have a vector with around 600 unique elements: A, B, C, D, E, F, G, H, I, etc. Using R, I would like to get a dataframe with 4 columns, where each row has all possible combinations of 4 elements under the following conditions:

  1. "A" goes always in column 1.

  2. Column 2 has B or C.

  3. Columns 3 and 4 have pairs of the remaining elements (pair X, Y is considered equal to pair Y, X). I expect to get something like:

    1 2 3 4
    A B D E
    A B F G
    A B H I
    A C D E
    A C F G
    A C H I

Upvotes: 0

Views: 74

Answers (1)

Marcelo Avila
Marcelo Avila

Reputation: 2374

A possible solution using combn(), expand.grid() and tidyr::separate based on @akrun's comment.

library(magrittr)
library(tidyr)

vec_a <- LETTERS[1]
vec_b <- LETTERS[2:3]
vec_c <- LETTERS[4:26]
vec_d <- combn(vec_c, 2, FUN = paste, collapse = " ")

res <- expand.grid(vec_a, vec_b, vec_d) %>% 
  tidyr::separate(Var3, c("Var3","Var4"), " ")

head(res, 25)
#>    Var1 Var2 Var3 Var4
#> 1     A    B    D    E
#> 2     A    C    D    E
#> 3     A    B    D    F
#> 4     A    C    D    F
#> 5     A    B    D    G
#> 6     A    C    D    G
#> 7     A    B    D    H
#> 8     A    C    D    H
#> 9     A    B    D    I
#> 10    A    C    D    I
#> 11    A    B    D    J
#> 12    A    C    D    J
#> 13    A    B    D    K
#> 14    A    C    D    K
#> 15    A    B    D    L
#> 16    A    C    D    L
#> 17    A    B    D    M
#> 18    A    C    D    M
#> 19    A    B    D    N
#> 20    A    C    D    N
#> 21    A    B    D    O
#> 22    A    C    D    O
#> 23    A    B    D    P
#> 24    A    C    D    P
#> 25    A    B    D    Q

Upvotes: 1

Related Questions