Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cross-paste all combinations of two vectors (each-to-each)?

Tags:

r

I need to paste all combinations of elements from two character vectors, "each" to "each": instead of

> paste0(c("a", "b"), c("c", "d"))
[1] "ac" "bd"

I want to get

[1] "ac" "ad" "bc" "bd"

How do I do that?

Thanks.

like image 335
sds Avatar asked Jun 17 '13 18:06

sds


2 Answers

Try this:

x <- c("a", "b")
y <- c("c", "d")

do.call(paste0, expand.grid(x, y))
# [1] "ac" "bc" "ad" "bd"

It is likely to be slower than outer when x and y are long, but on the other hand it allows the following generalisation:

z <- c("e", "f")

do.call(paste0, expand.grid(x, y, z))
# [1] "ace" "bce" "ade" "bde" "acf" "bcf" "adf" "bdf"
like image 160
Julius Vainora Avatar answered Oct 01 '22 18:10

Julius Vainora


You can also do:

outer(c("a", "b"), c("c", "d"), FUN = "paste0")[1:4]
[1] "ac" "bc" "ad" "bd"

Both do.call and outer are valuable functions to play with. :)

Alternately, we can assign

x <- outer(c("a", "b"), c("c", "d"), FUN = "paste0")
dim(x) <- NULL
x
[1] "ac" "bc" "ad" "bd"

Without knowing the length.

More edits!

x <- outer(c("a", "b"), c("c", "d"), FUN = "paste0")
y <- t(x)
dim(y) <- NULL
y
[1] "ac" "ad" "bc" "bd"

Gets you the desired order, too.

like image 32
Adam Hyland Avatar answered Oct 01 '22 16:10

Adam Hyland