R/06_pmapx.R

#' pmap with directly accessible column names
#'
#' @inheritParams purrr::pmap
#'
#' @export
pmapx <- function(.l, .f, ..., .t = c("lst","lgl","int","dbl","chr","dfr","dfc"))
{
  # check .t and match type to the correct value
  .t = match.arg(.t)
  type = c(lst = "list",dfr = "list", dfc = "list", chr = "character",
           lgl = "logical", int = "integer",dbl = "double")[.t]

  .f <- purrr::as_mapper(.f, ...)
  body(.f) <- substitute(with(list(...),b), list(b = body(.f)))

  if (is.data.frame(.l)) {
    .l <- as.list(.l)
  }

  # call pmap with right type and reformat if relevant
  res <- .Call(purrr:::pmap_impl, environment(), ".l", ".f", type)
  if (.t == "dfr") res <- dplyr::bind_rows(res, .id = .id)
  else if (.t == "dfc") res <- dplyr::bind_cols(res)
  if (.invis) invisible(res) else res
}
moodymudskipper/tidyx documentation built on May 17, 2019, 10:39 a.m.