Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In R, how to get the results of combn() from a matrix into a vector without losing data?

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading