Lists

Indexing a list in a chain of pipes

Suppose we have a list, l, containing three lowercase characters

l <- list("a", "b", "c")

l
[[1]]
[1] "a"

[[2]]
[1] "b"

[[3]]
[1] "c"

To index an element of the list, we can use double square brackets

l[[1]]
[1] "a"

If we want to index the same element as part of a chain of pipes, the new pipe operator (|>) won’t cut it

l |> `[[`(1)
Error: function '[[' not supported in RHS call of a pipe (<text>:1:6)

The old pipe (%>%) still works, but requires loading dplyr and doesn’t look very elegant

library(dplyr)
l %>% `[[`(1)
[1] "a"

Instead, we can use getElement(). Supply the list as the first argument, and the index as the second

getElement(l, 1)
[1] "a"

Here’s an example of indexing the first element and making it upper case

l |>
  getElement(1) |>
  toupper()
[1] "A"