list_transpose: Transpose a list

View source: R/list-transpose.R

list_transposeR Documentation

Transpose a list


list_transpose() turns a list-of-lists "inside-out". For instance it turns a pair of lists into a list of pairs, or a list of pairs into a pair of lists. For example, if you had a list of length n where each component had values a and b, list_transpose() would make a list with elements a and b that contained lists of length n.

It's called transpose because x[["a"]][["b"]] is equivalent to list_transpose(x)[["b"]][["a"]], i.e. transposing a list flips the order of indices in a similar way to transposing a matrix.


  template = NULL,
  simplify = NA,
  ptype = NULL,
  default = NULL



A list of vectors to transpose.


These dots are for future extensions and must be empty.


A "template" that describes the output list. Can either be a character vector (where elements are extracted by name), or an integer vector (where elements are extracted by position). Defaults to the names of the first element of x, or if they're not present, the integer indices.


Should the result be simplified?

  • TRUE: simplify or die trying.

  • NA: simplify if possible.

  • FALSE: never try to simplify, always leaving as a list.

Alternatively, a named list specifying the simplification by output element.


An optional vector prototype used to control the simplification. Alternatively, a named list specifying the prototype by output element.


A default value to use if a value is absent or NULL. Alternatively, a named list specifying the default by output element.


# list_transpose() is useful in conjunction with safely()
x <- list("a", 1, 2)
y <- x |> map(safely(log))
y |> str()
# Put all the errors and results together
y |> list_transpose() |> str()
# Supply a default result to further simplify
y |> list_transpose(default = list(result = NA)) |> str()

# list_transpose() will try to simplify by default:
x <- list(list(a = 1, b = 2), list(a = 3, b = 4), list(a = 5, b = 6))
x |> list_transpose()
# this makes list_tranpose() not completely symmetric
x |> list_transpose() |> list_transpose()

# use simplify = FALSE to always return lists:
x |> list_transpose(simplify = FALSE) |> str()
x |>
  list_transpose(simplify = FALSE) |>
  list_transpose(simplify = FALSE) |> str()

# Provide an explicit template if you know which elements you want to extract
ll <- list(
  list(x = 1, y = "one"),
  list(z = "deux", x = 2)
ll |> list_transpose()
ll |> list_transpose(template = c("x", "y", "z"))
ll |> list_transpose(template = 1)

# And specify a default if you want to simplify
ll |> list_transpose(template = c("x", "y", "z"), default = NA)

purrr documentation built on Aug. 10, 2023, 9:08 a.m.