使用基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)发布于 2020-04-08 17:24:27
双循环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)发布于 2020-04-08 17:27:36
一种选择可以是:
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"发布于 2020-04-08 17:26:14
或者使用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')https://stackoverflow.com/questions/61106324
复制相似问题