什么是purrr :: map相当于:
for (i in 1:4) {
for (j in 1:6) {
print(paste(i, j, sep = "-"))
}
}
Run Code Online (Sandbox Code Playgroud)
要么
lapply(1:4, function(i)
lapply(1:6, function(j)
print(paste(i, j, sep = "-"))))
Run Code Online (Sandbox Code Playgroud)
从概念上讲,我没有得到的是如何引用内部映射函数中的外部循环.
map(1:4, ~ map(1:6, ~ print(paste(.x, ????, sep = "-")))
Run Code Online (Sandbox Code Playgroud)
r2e*_*ans 19
当尝试像这样嵌套时,函数formula(~)的使用有点受限,因为完全不清楚map你试图引用哪个级别.(嗯,这是不对的.我很清楚它是从里到外引用的,因为它们都使用相同的命名法,外部变量被内部变量掩盖了.)
我认为你最好的方法是不使用公式方法,而是使用立即/匿名(或预定义)函数:
library(purrr)
str(map(1:2, function(x) map(1:3, function(y) paste(x, y, sep = "-"))))
# List of 2
# $ :List of 3
# ..$ : chr "1-1"
# ..$ : chr "1-2"
# ..$ : chr "1-3"
# $ :List of 3
# ..$ : chr "2-1"
# ..$ : chr "2-2"
# ..$ : chr "2-3"
Run Code Online (Sandbox Code Playgroud)
Moo*_*per 12
正如@ r2evans指出的那样,.x你第一次通话就被掩盖了.但是你可以创建一个lambda函数,它需要两个参数.x和.y,并指定以前.x到新.y通过...的说法.
我会使用walk而不是map在这种情况下你只对副作用(印刷)感兴趣
walk(1:4,~ walk(1:6, ~ print(paste(.x, .y, sep = "-")),.y=.x))
Run Code Online (Sandbox Code Playgroud)
另一个选择是用于expand.grid布局组合,然后迭代那些pwalk(或pmap在其他情况下)
purrr::pwalk(expand.grid(1:4,1:6),~print(paste(.x, .y, sep = "-")))
Run Code Online (Sandbox Code Playgroud)
两种情况下的输出:
[1] "1-1"
[1] "2-1"
[1] "3-1"
[1] "4-1"
[1] "5-1"
[1] "6-1"
[1] "1-2"
[1] "2-2"
[1] "3-2"
[1] "4-2"
[1] "5-2"
[1] "6-2"
[1] "1-3"
[1] "2-3"
[1] "3-3"
[1] "4-3"
[1] "5-3"
[1] "6-3"
[1] "1-4"
[1] "2-4"
[1] "3-4"
[1] "4-4"
[1] "5-4"
[1] "6-4"
Run Code Online (Sandbox Code Playgroud)
现在刚刚经历过这个。
walk(1:4,~ walk(1:6, ~ print(paste(.x, .y, sep = "-")),.y=.x))
[1] "1-1"
[1] "2-1"
[1] "3-1"
[1] "4-1"
[1] "5-1"
[1] "6-1"
[1] "1-2"
Run Code Online (Sandbox Code Playgroud)
和
purrr::pwalk(expand.grid(1:4,1:6),~print(paste(.x, .y, sep = "-")))
[1] "1-1"
[1] "2-1"
[1] "3-1"
[1] "4-1"
[1] "1-2"
Run Code Online (Sandbox Code Playgroud)
但为了完全匹配您的嵌套 for 循环,它会摆弄并且这有效。
for (i in 1:4) {
for (j in 1:6) {
print(paste(i, j, sep = "-"))
}
}
[1] "1-1"
[1] "1-2"
[1] "1-3"
[1] "1-4"
[1] "1-5"
[1] "1-6"
[1] "2-1"
purrr::pwalk(expand.grid(1:6,1:4),~print(paste(.y, .x, sep = "-")))
[1] "1-1"
[1] "1-2"
[1] "1-3"
[1] "1-4"
[1] "1-5"
[1] "1-6"
[1] "2-1"
#or even a map of this
walk(1:4,~ walk(1:6, ~ print(paste(.y, .x, sep = "-")),.y=.x))
Run Code Online (Sandbox Code Playgroud)
我还没有弄清楚为什么是.y=.x在最后。