1

Lets say I have two vectors:

x <- c("A", "B")
y <- c("C")

I would then like to find and collect all combinations of x and y in the following manner:

DesiredOutput <- list(c('A', 'C'), c('B', 'C'))

I have tried using expand.grid in combination with split as follows:

xy.df <- expand.grid(x, y)
xy.list <- split(xy.df, 1:nrow(xy.df))

However, this does not produce the desired output as for instance xy.list[[1]][1] is no longer a character. And if I try to simply do as.character(xy.list[[1]][1]) then this returns a "1". So, what can I do instead?

Miski123
  • 135
  • 5
  • Does this question help? https://stackoverflow.com/questions/38221588/combinations-by-group-in-r – Peter Dec 10 '22 at 08:53

1 Answers1

0

Adapting the answer in stackoverflow.com/questions/38221588/combinations-by-group-in-r you could try:

library(dplyr)
library(tidyr)

  
  df1 <- data.frame(x, y) |> 
    pivot_longer(everything()) |> 
    distinct() |> 
    group_by(name)
    
    as.data.frame(t(combn(df1$value, 2)))
#>   V1 V2
#> 1  A  C
#> 2  A  B
#> 3  C  B

Created on 2022-12-10 with reprex v2.0.2

Peter
  • 11,500
  • 5
  • 21
  • 31