【问题标题】:R use mapply on nested listR在嵌套列表上使用mapply
【发布时间】:2020-04-08 17:18:44
【问题描述】:

使用基础 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)

【问题讨论】:

    标签: r nested mapply


    【解决方案1】:

    一个选项可能是:

    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"
    

    【讨论】:

      【解决方案2】:

      或使用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')
      

      【讨论】:

        【解决方案3】:

        双循环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)
        

        【讨论】:

          猜你喜欢
          • 2021-03-31
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-05-11
          • 1970-01-01
          • 1970-01-01
          • 2023-03-06
          相关资源
          最近更新 更多