2

I know that combn() can give me all the unique combinations across a vector. However, it gives me a matrix output, and I want it as a vector. Wrapping the output in as.vector() makes every value individual, losing the purpose of running combn() in the first place. Imagine my dataset was c("a", "b", "c"), how can I use combn() (or some other function), to get a vector where my output would be:

my_data <- c("a", "b", "c")

#natural output with combn()

#output with combn()
combn(my_data, 2, simplify = TRUE)

#output with as.vector() wrapped
as.vector(combn(my_data, 2, simplify = TRUE))

#desired output
answer <- c("ab", "ac", "bc") #I don't care about order

J.Sabree
  • 2,280
  • 19
  • 48

2 Answers2

3

You can paste each column of the result together using apply

my_data <- c("a", "b", "c")

apply(combn(my_data, 2), 2, paste, collapse = "")
#> [1] "ab" "ac" "bc"

Created on 2023-01-25 with reprex v2.0.2

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
3

We can use combn as

combn(my_data, 2, FUN = paste, collapse = "")
[1] "ab" "ac" "bc"
akrun
  • 874,273
  • 37
  • 540
  • 662
  • I didn't know you could do that! Is there a way to set paste's sep argument to a space? When I try paste(., sep = " "), I get an error. – J.Sabree Jan 25 '23 at 20:15
  • 1
    @J.Sabree you need a lambda expression for that `combn(my_data, 2, FUN = function(x) paste(x, collapse = ""))` – akrun Jan 25 '23 at 20:16