我在 R 中有一个大约 10,000 个元素长的列表。假设我只想选择元素 5、7 和 9。我不确定在没有 for 循环的情况下如何做到这一点。
我想做一些类似
mylist[[c(5,7,9]]
的事情,但这行不通。我也尝试过 lapply
功能,但也无法正常工作。
mylist[c(5,7,9)]
应该这样做。
您希望子列表作为结果列表的子列表返回;你不使用
[[]]
(或者更确切地说,该功能是 [[
) - 正如 Dason 在评论中提到的, [[
抓取元素。
Glen_b 的答案是正确的。以下是一些示例,说明如何将其与管道、
lapply
和map()
等函数以及在具有列表列的数据框中使用:
带管道:
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
使用
map()
、lapply()
等
y = list(as.list(letters), as.list(LETTERS))
map(y, \(x) x[nums])
lapply(y, \(x) x[nums])
数据框中的列表类型列:
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)