我们可以从每个列表中提取"total" 元素,并只选择其中包含 7 的那些元素。
lst[sapply(lst, "[[", "total") == 7]
#[[1]]
#[[1]]$total
#[1] 7
#[[1]][[2]]
#[1] 2
#[[1]][[3]]
#[1] 2
#[[2]]
#[[2]]$total
#[1] 7
#[[2]][[2]]
#[1] 2
#[[2]][[3]]
#[1] 2
或者我们也可以使用Filter
Filter(function(x) x[["total"]] == 7, lst)
使用purrr我们可以使用keep/discard
library(purrr)
keep(lst, ~.[["total"]] == 7)
discard(lst, ~.[["total"]] != 7)
或map_lgl
lst[map_lgl(lst, ~.[["total"]] == 7)]
数据
假设您的列表名为 lst,如下所示
lst <- list(list(total = 100, 1, 2), list(total = 7, 2, 2),
list(total = 7, 2, 2), list(total = 71, 2, 2))