Paste All Combinations of a Vector in R

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="")

Paste all combinations of a vector in R

Try combn

 combn(vec,2, FUN=paste, collapse='')
#[1] "AB" "AC" "BC"

Loop trough vector elements... and make new vector

no for-loops needed here.

sapply(combn(X, m = 2, simplify = FALSE), paste0, collapse = "-")
#"A-B" "A-C" "B-C"

How to create all the combinations in a vector using R

Something like this could work:

unlist(sapply(1:4, function(x) apply(combn(1:4, x), 2, paste, collapse = '')))

First we get the combinations using combn and then we paste the outputs together. Finally, unlist gives us a vector with the output we need.

Output:

[1] "1"    "2"    "3"    "4"    "12"   "13"   "14"   "23"   "24"   "34"   "123"  "124" 
"134" "234" "1234"


Related Topics



Leave a reply



Submit