Skip to content

Instantly share code, notes, and snippets.

@Hampei
Created May 3, 2017 14:52
Show Gist options
  • Save Hampei/d75d064938e4ae6521e680c0d83646a7 to your computer and use it in GitHub Desktop.
Save Hampei/d75d064938e4ae6521e680c0d83646a7 to your computer and use it in GitHub Desktop.
recursive list apply for R
#' Recursive list apply, given a bunch of vectors and a function, creates lists of lists with the elements as keys
#' and values determined by fn.
#' @param ... vectors to loop over
#' @param fn function to execute for each leaf
#' @examples
#' grip:::rsapply(c('a', 'b'), c('f', 'g'), fn=function(x,y) c(x, y))
#' #> list(a=list(f=c('a', 'f'), g=c('a', 'g')), b=list(f=c('b', 'f'), g=c('b', 'g')))
rsapply <- function(..., fn) {
.rsapply <- function(el=NULL, ..., args=c(), fn) {
if(is.null(el)) return(do.call(fn, as.list(args)))
result <- list()
for(x in el) {
result[[x]] <- rsapply(..., args=c(args, x), fn=fn)
}
result
}
.rsapply(..., fn=fn)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment