9

suppose I have two arrays a and b:

a=seq(2013,2015)
b=c('-03-31','-06-30')

I would like to combine each element in a with each in b. The result should be an array which looks like:

"2013-03-31" "2013-06-30" "2014-03-31" "2014-06-30" "2015-03-31" "2015-06-30"

How do I do this?

Mike Wise
  • 22,131
  • 8
  • 81
  • 104
user2854008
  • 1,161
  • 4
  • 17
  • 23
  • 1
    I don't understand why this post is voted -3. Anyone who voted can explain? The answer for akrun is what I am looking for, thanks akrun. – user2854008 Apr 30 '15 at 05:48
  • For example If I google a keyword "r every combination of two vectors", I get http://stackoverflow.com/questions/16143700/pasting-two-vectors-with-combinations-of-all-vectors-elements which is basically what you asked. – akrun Apr 30 '15 at 05:53
  • 1
    still seems bad form to downvote without a comment as to why – Mike Wise Apr 30 '15 at 05:54
  • @akrun, I think you might be right. – user2854008 Apr 30 '15 at 06:02

2 Answers2

16

You can try

c(outer(a, b, FUN=paste0))
#[1] "2013-03-31" "2014-03-31" "2015-03-31" "2013-06-30" "2014-06-30"
#[6] "2015-06-30"

Or

do.call(paste0,expand.grid(a,b))

Or

sprintf('%s%s', rep(a, length(b)), rep(b, length(a)))
akrun
  • 874,273
  • 37
  • 540
  • 662
1

akrun's examples work well if you want a character vector as your result, but they do not make it easy to work with each side of the pair.

This function will give you a list containing the cross-product of two sets:

cross <- function(x, y = x) {

    result <- list()

    for (a in unique(x)) {

        for (b in unique(y)) {

            result <- append(result, list(list(left = a, right = b)))
        }
    }

    result
}

Example:

cross(c(1, 2, 3), c("a", "b", "c"))
sdgfsdh
  • 33,689
  • 26
  • 132
  • 245