Dataframe with combinatorial data and conditions

I am looking for how to transform a dataframe with combinatorial data and conditions in r.

To be clear, this is my first dataframe :

| x1 A |
| x1 B |
| x1 C |
| x2 A |
| x2 B |

And I would like this :

| x1 A B |
| x1 A C |
| x1 B C |
| x2 A B |

I have started to write code but I am not familiar with the required loops. Indeed, I managed to write the part for one condition(let's say "X1") but I don't know how to create the whole table.

This is where I am :

# Initiate data frame :
a <- c('x1','A')
b <- c('x1','B')
c <- c('x1','C')
d <- c('x2','D')
matrix <- matrix(c(a,b,c,d),nrow=4,ncol=2,byrow=T)
colnames(matrix) <- c("Patent","Class")

# Combine :
temp <- matrix %>%
  filter(Patent == 'x1') %>%
  select (Class)
temp <- as.vector(t(temp))
temp2 <- t(combn(temp,2))
temp2

# Associate condition :

vector <- rep("x1",nrow(temp2))
vector
temp3 <- cbind(vector,temp2)
temp3

Would something like this work? Keep in mind that you get an error if there is only one item per x group.

library(tidyverse)

df <- tribble(
    ~Patent, ~Class,
    "x1", "A",
    "x1", "B",
    "x1", "C",
    "x1", "D",
    "x2", "A",
    "x2", "B"
)

generate_comb <- function(gr_df) {
    v <- gr_df$Class
    comb_mat <- t(combn(v, 2))
    colnames(comb_mat) <- c("Class1", "Class2")
    as_tibble(comb_mat)
}

df %>%
    group_by(Patent) %>%
    do(generate_comb(.)) %>%
    ungroup()

#> # A tibble: 7 x 3
#>   Patent Class1 Class2
#>   <chr>  <chr>  <chr> 
#> 1 x1     A      B     
#> 2 x1     A      C     
#> 3 x1     A      D     
#> 4 x1     B      C     
#> 5 x1     B      D     
#> 6 x1     C      D     
#> 7 x2     A      B

Created on 2019-02-19 by the reprex package (v0.2.1)

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.