使用基数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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句