将函数应用于两个列表元素的每个组合

Apply a function to each combination of two lists elements

我想对两个列表元素的每个组合应用一个函数。

library(tidyverse)

map(
    .x = c(0, 1)
  , .f = function(x) {
    qnorm(p = 0.05, mean = x, sd = 1, lower.tail = FALSE)
  }
)

[[1]]
[1] 1.644854

[[2]]
[1] 2.644854


map(
    .x = c(0, 1)
  , .f = function(x) {
    qnorm(p = 0.05, mean = x, sd = 2, lower.tail = FALSE)
  }
)


[[1]]
[1] 3.289707

[[2]]
[1] 4.289707

现在尝试将两者合二为一(无论如何都没有得到所需的输出)。

map2(
    .x = c(0, 1)
  , .y = c(1, 2)
  , .f = function(x, y) {
    qnorm(p = 0.05, mean = x, sd = y, lower.tail = FALSE)
  }
)

[[1]]
[1] 1.644854

[[2]]
[1] 4.289707

想知道如何获得所有四种组合的输出?

您可以使用 expand.grid:

library(purrr)

df1 <- expand.grid(0:1, 1:2) 

map2(
  .x = df1$Var1,
  .y = df1$Var2,
  .f = function(x, y) {
    qnorm(p = 0.05, mean = x, sd = y, lower.tail = FALSE)
    }
  )

获得

[[1]]
[1] 1.644854

[[2]]
[1] 2.644854

[[3]]
[1] 3.289707

[[4]]
[1] 4.289707

pmapcrossing

的另一个选项
library(tidyr)
library(purrr)
library(dplyr)
crossing(v1 = 0:1, v2 = 1:2)  %>% 
   pmap_dbl(~ qnorm(p = 0.05, mean = ..1, sd = ..2, lower.tail = FALSE))
[1] 1.644854 3.289707 2.644854 4.289707

如果我们需要一个数据。frame/tibble,使用mutate到return中的pmap代码作为新列

crossing(v1 = 0:1, v2 = 1:2) %>%
    mutate(new =  pmap_dbl(., ~ qnorm(p = 0.05, 
       mean = ..1, sd = ..2, lower.tail = FALSE)))
# A tibble: 4 × 3
     v1    v2   new
  <int> <int> <dbl>
1     0     1  1.64
2     0     2  3.29
3     1     1  2.64
4     1     2  4.29

注意:如果我们不需要其他列,请使用 transmute 而不是 mutate 或在 mutate

中指定 .keep = "used"
crossing(v1 = 0:1, v2 = 1:2) %>%
    mutate(new =  pmap_dbl(., ~ qnorm(p = 0.05, 
        mean = ..1, sd = ..2, lower.tail = FALSE)), .keep = "used")
# A tibble: 4 × 1
    new
  <dbl>
1  1.64
2  3.29
3  2.64
4  4.29

基于data.table的解决方案,不使用任何purrr函数:

library(data.table)
library(magrittr)

setDT(CJ(x = 0:1, y = 1:2))[,
  res := qnorm(p = 0.05, mean = x, sd = y, lower.tail = FALSE)] %>% print

#>    x y      res
#> 1: 0 1 1.644854
#> 2: 0 2 3.289707
#> 3: 1 1 2.644854
#> 4: 1 2 4.289707

另一种基于tidyverse的解决方案,不使用任何purrr函数:

library(tidyverse)

data.frame(x = 0:1, y = 1:2) %>% 
  expand(x,y) %>% 
  mutate(res = qnorm(p = 0.05, mean = x, sd = y, lower.tail = FALSE))

#> # A tibble: 4 × 3
#>       x     y   res
#>   <int> <int> <dbl>
#> 1     0     1  1.64
#> 2     0     2  3.29
#> 3     1     1  2.64
#> 4     1     2  4.29