Home > Back-end >  Apply a function to each combination of two lists elements
Apply a function to each combination of two lists elements

Time:11-17

I want to 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

Now trying to combine both in one (not getting required output anyhow).

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

Wondering how to get output for all four combinations?

CodePudding user response:

Or another option with pmap and crossing

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

If we need a data.frame/tibble, use the pmap code within the mutate to return as a new column

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

NOTE: If we don't need the other columns, use transmute instead of mutate or specify .keep = "used" in mutate

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

CodePudding user response:

You could use 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)
    }
  )

to get

[[1]]
[1] 1.644854

[[2]]
[1] 2.644854

[[3]]
[1] 3.289707

[[4]]
[1] 4.289707

CodePudding user response:

A data.table-based solution, without using any purrr function:

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

Another tidyverse-based solution, without using any purrr function:

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
  • Related