How to Cross-Paste All Combinations of Two Vectors (Each-To-Each)

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.

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"

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

Rowbinding all combinations of two vectors for each variation in a third vector

Maybe this helps

out <- rbind(rep(down, each = length(cat)), rep(up, each = length(cat)))
colnames(out) <- rep(c(cat), length.out = ncol(out))
row.names(out) <- c('down', 'up')

-output

> out
east north south west east north south west east north south west east north south west east north south west east north south west east north south west east
down 0 0 0 0 25 25 25 25 50 50 50 50 100 100 100 100 250 250 250 250 500 500 500 500 1000 1000 1000 1000 1500
up 25 25 25 25 50 50 50 50 100 100 100 100 250 250 250 250 500 500 500 500 1000 1000 1000 1000 1500 1500 1500 1500 3000
north south west east north south west
down 1500 1500 1500 3000 3000 3000 3000
up 3000 3000 3000 1000000 1000000 1000000 1000000

Create list from two vectors with every combo of each

Since you have data.table as a package, you can use the CJ() cross join function:

CJ(cycles, thedates)

It would be a lot faster than expand.grid:

expand.grid(cycles, thedates)

I also think having a bunch of lists isn't helpful but you could split it as @Reeza provided to match your output.



Related Topics



Leave a reply



Submit