From b9ae1d8be30807e5685d0899478a5f08fcdbe937 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benno=20Pu=CC=88tz?= Date: Fri, 11 Aug 2017 18:20:51 +0200 Subject: [PATCH] initial checkin (v0.3) --- vcomb.R | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 vcomb.R diff --git a/vcomb.R b/vcomb.R new file mode 100644 index 0000000..6ecbe44 --- /dev/null +++ b/vcomb.R @@ -0,0 +1,42 @@ +##' combine all possible pairs of vectors \code{v1} and \code{v2} +##' using function \code{myfun} +##' +##' In essence, this is a generalized version of \code{\link[base]{outer}} +##' allowing non-scalar return values for \code{myfun}. +##' +##' Possible extensions: +##' \enumerate{ +##' \item reformat the output to be matrix-like (see outer) +##' \item use a list of index pairs with \code{lapply} to allow +##' irregular return values +##' \item shuffle the order of elements (incompatible with (1)) +##' } +##' @title vector combine +##' @param v1 first vector +##' @param v2 second vector +##' @param myfun function to combine the element pairs from the two vectors +##' @param ... not used +##' @return vector (or matrix, array) of combinations +##' @author Benno Puetz \email{puetz@@mpipsykl.mpg.de} +##' @examples +##' a <- 1:3 +##' b <- 5:9 +##' vcomb(a, b) +vcomb <- function(v1, v2, myfun = c, ...){ + mat <- matrix(as.numeric(unlist(strsplit(outer(seq_along(v1), + seq_along(v2), + FUN = function(a, b){ + paste(a, b, + sep = '.') + }), + '.', + fixed = TRUE) + )), + ncol = 2, + byrow = TRUE) + combine.vectors <- function(rv) { + retval <- myfun(v1[rv[1]], v2[rv[2]]) + return(retval) + } + return(apply(mat, 1, combine.vectors)) +}