Glen_b's answer is the correct one. Below are some examples of how you can use it with pipes, functions like lapply
and map()
, and within a dataframe with list columns:
With pipes:
library(tidyverse)
x <- as.list(letters)
nums <- c(5, 7, 9)
x[nums] # Glen's answer
nums |> x[i = _] # using the native pipe
nums %>% {x[.]} # using magrittr's pipe
# nums %>% x[i = .] is equivalent
Using map()
, lapply()
etc.
y = list(as.list(letters), as.list(LETTERS))
map(y, \(x) x[nums]) # lambda function \(x) x[nums] is equivalent to ~ .x[nums] or function(x){x[nums]}
lapply(y, \(x) x[nums])
With list-type columns in dataframes:
df <- tibble(
x = list(x)) # we need to put x within another list, as tibble() will unnest x otherwise
df |>
mutate(z = map(x, \(x) x[nums])) |>
pull(z)