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?
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'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"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With