Pasting Two Vectors With Combinations of All Vectors' Elements

Pasting two vectors with combinations of all vectors' elements

You can use this, but there may be a simpler solution :

R> apply(expand.grid(vars, vis), 1, paste, collapse=".")
[1] "SR.1" "PL.1" "SR.2" "PL.2" "SR.3" "PL.3"

expand.grid gives back a data.frame which when used with apply, apply will convert it to a matrix. This is just unnecessary (and inefficient on large data). outer gives a matrix and also takes function argument. It'll be much efficient on huge data as well.

Using outer:

as.vector(outer(vars, vis, paste, sep="."))
# [1] "SR.1" "PL.1" "SR.2" "PL.2" "SR.3" "PL.3"

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

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.

Paste all combinations of two separate vectors in R

Another approach:

df1 <- c("a","b","c")
df2 <- c("1","2","3")

apply(expand.grid(df1, df2), 1, paste, collapse="")

Concatenate unique combinations of elements in a character vector into new vector of strings in R

Try combn

> sprintf("_%s_", combn(vec, 2, paste0, collapse = "_"))
[1] "_X1_X2_" "_X1_X3_" "_X1_X4_" "_X1_X5_" "_X2_X3_" "_X2_X4_" "_X2_X5_"
[8] "_X3_X4_" "_X3_X5_" "_X4_X5_"

> paste0("_", combn(vec, 2, paste0, collapse = "_"), "_")
[1] "_X1_X2_" "_X1_X3_" "_X1_X4_" "_X1_X5_" "_X2_X3_" "_X2_X4_" "_X2_X5_"
[8] "_X3_X4_" "_X3_X5_" "_X4_X5_"

Matrix of combinations of two vectors

We can use outer

out <- outer(x, y, FUN = paste0)
dimnames(out) <- list(x, y)

All Possible Pairs between Two Vectors in R Without Replacement

It seems a permutation problem, which might be solved like below

> library(pracma)

> paste0(v1, t(perms(v2)))
[1] "AZ" "BY" "CX" "AZ" "BX" "CY" "AY" "BZ" "CX" "AY" "BX" "CZ" "AX" "BY" "CZ"
[16] "AX" "BZ" "CY"

or

out <- data.frame(
Var1 = v1,
Var2 = c(t(perms(v2))),
Match = ceiling(seq(factorial(length(v2)) * length(v2)) / length(v1))
)

which gives

> out
Var1 Var2 Match
1 A Z 1
2 B Y 1
3 C X 1
4 A Z 2
5 B X 2
6 C Y 2
7 A Y 3
8 B Z 3
9 C X 3
10 A Y 4
11 B X 4
12 C Z 4
13 A X 5
14 B Y 5
15 C Z 5
16 A X 6
17 B Z 6
18 C Y 6


Related Topics



Leave a reply



Submit