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

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

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

I want to receive

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

How can i do this?

Thank you

+8
source share
4 answers

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 features to reproduce. :)

Alternatively, we can designate

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

Without knowledge of length.

Additional changes!

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

Gets the order you need.

+13
source

Try the following:

 x <- c("a", "b") y <- c("c", "d") do.call(paste0, expand.grid(x, y)) # [1] "ac" "bc" "ad" "bd" 

It is probably slower than outer when x and y are long, but on the other hand, it allows the following generalization:

 z <- c("e", "f") do.call(paste0, expand.grid(x, y, z)) # [1] "ace" "bce" "ade" "bde" "acf" "bcf" "adf" "bdf" 
+12
source

Other (less useful) spell:

 levels(interaction(x,y,sep="")) # [1] "ac" "bc" "ad" "bd" 
+9
source

It can also be used.

 comb <- function(x,y) { x1 <- rep(x, each=length(y)) y1 <- rep(y, times=length(x)) paste0(x1,y1) } comb(2:4, 5:7) 
0
source

All Articles