【问题标题】:purrr map2(x,y, fun),but for each element of X, do all elements of ypurrr map2(x,y, fun),但是对于 X 的每个元素,做 y 的所有元素
【发布时间】:2023-03-19 23:54:01
【问题描述】:

来自:https://www.rdocumentation.org/packages/purrr/versions/0.2.2/topics/map2 我们看到:

x <- list(1, 10, 100)
y <- list(1, 2, 3)
map2(x, y, ~ .x + .y)

生成

2, 12, 103

但如果需要的是:

2, 3, 4, 11, 12, 13, 101, 102, 103

即:为每个x[i]添加y[*]的所有成员

for 循环看起来很简单,但是……我显然在 purrr 中遗漏了一些明显的东西。

【问题讨论】:

    标签: r purrr


    【解决方案1】:

    map2 在这里不起作用,因为它在两个列表/向量之间并行迭代,例如 Mapmapply。相反,您正在寻找 cross2,它执行两个列表的交叉连接。三个选项:

    library(purrr)
    
    x <- list(1, 10, 100)
    y <- list(1, 2, 3)
    
    cross2(y, x) %>% invoke_map_dbl(sum, .)
    #> [1]   2   3   4  11  12  13 101 102 103
    
    cross2(y, x) %>% map_dbl(~sum(unlist(.x)))
    #> [1]   2   3   4  11  12  13 101 102 103
    
    cross2(y, x) %>% simplify_all() %>% map_dbl(sum)
    #> [1]   2   3   4  11  12  13 101 102 103
    

    如果您的列表只是数字,另一个选择是outer

    outer(unlist(x), unlist(y), `+`)
    #>      [,1] [,2] [,3]
    #> [1,]    2    3    4
    #> [2,]   11   12   13
    #> [3,]  101  102  103
    

    【讨论】:

      猜你喜欢
      • 2016-08-17
      • 1970-01-01
      • 2022-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-12
      • 2019-12-29
      相关资源
      最近更新 更多