1#' Transpose a list.
2#'
3#' Transpose turns a list-of-lists "inside-out"; it turns a pair of lists into a
4#' list of pairs, or a list of pairs into pair of lists. For example,
5#' if you had a list of length n where each component had values `a` and
6#' `b`, `transpose()` would make a list with elements `a` and
7#' `b` that contained lists of length n. It's called transpose because
8#' \code{x[[1]][[2]]} is equivalent to \code{transpose(x)[[2]][[1]]}.
9#'
10#' Note that `transpose()` is its own inverse, much like the
11#' transpose operation on a matrix. You can get back the original
12#' input by transposing it twice.
13#'
14#' @param .l A list of vectors to transpose. The first element is used as the
15#'   template; you'll get a warning if a subsequent element has a different
16#'   length.
17#' @param .names For efficiency, `transpose()` bases the return structure on
18#'   the first component of `.l` by default. Specify `.names` to override this.
19#' @return A list with indexing transposed compared to `.l`.
20#' @export
21#' @examples
22#' x <- rerun(5, x = runif(1), y = runif(5))
23#' x %>% str()
24#' x %>% transpose() %>% str()
25#' # Back to where we started
26#' x %>% transpose() %>% transpose() %>% str()
27#'
28#' # transpose() is useful in conjunction with safely() & quietly()
29#' x <- list("a", 1, 2)
30#' y <- x %>% map(safely(log))
31#' y %>% str()
32#' y %>% transpose() %>% str()
33#'
34#' # Use simplify_all() to reduce to atomic vectors where possible
35#' x <- list(list(a = 1, b = 2), list(a = 3, b = 4), list(a = 5, b = 6))
36#' x %>% transpose()
37#' x %>% transpose() %>% simplify_all()
38#'
39#' # Provide explicit component names to prevent loss of those that don't
40#' # appear in first component
41#' ll <- list(
42#'   list(x = 1, y = "one"),
43#'   list(z = "deux", x = 2)
44#' )
45#' ll %>% transpose()
46#' nms <- ll %>% map(names) %>% reduce(union)
47#' ll %>% transpose(.names = nms)
48transpose <- function(.l, .names = NULL) {
49  .Call(transpose_impl, .l, .names)
50}
51