[英]Apply a function to each combination of two lists elements
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?想知道如何获得所有四种组合的输出?
You could use expand.grid
:您可以使用
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
Or another option with pmap
and crossing
或者使用
pmap
和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如果我们需要 data.frame/tibble,请使用
mutate
的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
NOTE: If we don't need the other columns, use transmute
instead of mutate
or specify .keep = "used"
in mutate
注意:如果我们不需要其他列,使用
transmute
,而不是mutate
或指定.keep = "used"
在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
Another tidyverse
-based solution, without using any purrr
function:另一个基于
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.