R 在嵌套列表上使用 mapply

R use mapply on nested list

使用 base R,我想在嵌套列表上使用 mapply 函数。例如,在下面的代码中,我试图从嵌套列表的每个元素中删除字母 "a"。我想用一行代码替换最后两行。

mylist <- list(
    list(c("a", "b", "c"), c("d", "e", "f")),
    list(c("a", "v", "w"), c("x", "y"), c("c", "b", "a"))
)

mylist

not_a <- lapply(mylist, lapply, `!=`, "a")

not_a

mylist[[1]] <- mapply(`[`, mylist[[1]], not_a[[1]], SIMPLIFY = FALSE)

mylist[[2]] <- mapply(`[`, mylist[[2]], not_a[[2]], SIMPLIFY = FALSE)

双循环 Map/mapply 将完成问题的要求。

Map(function(i) mapply(`[`, mylist[[i]], not_a[[i]], SIMPLIFY = FALSE), seq_along(mylist))

更简单:

Map(function(x, y) Map(`[`, x, y), mylist, not_a)

或使用map2

library(purrr)
map2(mylist, not_a, ~ map2(.x, .y, `[`))

或使用 map_depth(如果 OP 只对最终结果感兴趣)

map_depth(mylist, 2,  ~ .x[.x != 'a'])
#[[1]]
#[[1]][[1]]
#[1] "b" "c"

#[[1]][[2]]
#[1] "d" "e" "f"


#[[2]]
#[[2]][[1]]
#[1] "v" "w"

#[[2]][[2]]
#[1] "x" "y"

#[[2]][[3]]
#[1] "c" "b"

或更紧凑

map_depth(mylist, 2, setdiff, 'a')

一个选项可以是:

rapply(mylist, how = "replace", function(x) x[x != "a"])

[[1]]
[[1]][[1]]
[1] "b" "c"

[[1]][[2]]
[1] "d" "e" "f"


[[2]]
[[2]][[1]]
[1] "v" "w"

[[2]][[2]]
[1] "x" "y"

[[2]][[3]]
[1] "c" "b"