Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R language cross-product combination of two string arrays

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?

like image 921
user2854008 Avatar asked Apr 30 '15 05:04

user2854008


2 Answers

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)))
like image 81
akrun Avatar answered Jan 03 '23 21:01

akrun


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"))
like image 24
sdgfsdh Avatar answered Jan 03 '23 23:01

sdgfsdh