如何在非标准评估中使用pmap?

时间:2019-03-28 13:50:54

标签: r purrr

我想将pmap用于非标准评估。

我已经尝试了一个小例子,但是没有用。

library(tidyverse)
library(magrittr)
#> 
#> Attachement du package : 'magrittr'
#> The following object is masked from 'package:purrr':
#> 
#>     set_names
#> The following object is masked from 'package:tidyr':
#> 
#>     extract

df <- tibble(
  x = 1:3 + 0.1,
  y = 3:1 - 0.1
)
test_func <- function(x, y){
    x + y
}
# Work:
df %>%
  mutate(
  test = pmap_dbl(
    list(x = x, y = y),
    test_func)
  )
#> # A tibble: 3 x 3
#>       x     y  test
#>   <dbl> <dbl> <dbl>
#> 1   1.1   2.9     4
#> 2   2.1   1.9     4
#> 3   3.1   0.9     4

# NSE does not work:
df %>%
  mutate(
  test = pmap_dbl(
    list(x = x, y = y),
    ~test_func(x = x, y = y))
  )
#> Error: Evaluation error: Result 1 is not a length 1 atomic vector.

reprex package(v0.2.0.9000)于2019-03-28创建。

我希望NSE的输出与pmap的“正常”输出相同。

1 个答案:

答案 0 :(得分:0)

嗯,实际上文档非常清楚。

我需要通过将自变量称为..1..2..3等来评估自变量...

参数的顺序显然很重要,因为未评估列表的名称(但我想这么做!)。

因此,对于一个更详细的示例,它给出:

library(tidyverse)
library(magrittr)
#> 
#> Attachement du package : 'magrittr'
#> The following object is masked from 'package:purrr':
#> 
#>     set_names
#> The following object is masked from 'package:tidyr':
#> 
#>     extract

df <- tibble(
  x = 1:3 + 0.1,
  y = 3:1 - 0.1,
  z = c("a", "b", "c")
)
test_func <- function(x, y, cond, ...){
  if (cond == "a") {
    x + y
  } else {
   NA 
  }
}
# Work:
df %>%
  mutate(
  test = pmap_dbl(
    list(x = x, y = y, cond = z),
    test_func)
  )
#> # A tibble: 3 x 4
#>       x     y z      test
#>   <dbl> <dbl> <chr> <dbl>
#> 1   1.1   2.9 a         4
#> 2   2.1   1.9 b        NA
#> 3   3.1   0.9 c        NA

# NSE does work as well:
df %>%
  mutate(
  test = pmap_dbl(
    list(x, y, z),
    ~test_func(x = ..1, y = ..2, cond = ..3))
  )
#> # A tibble: 3 x 4
#>       x     y z      test
#>   <dbl> <dbl> <chr> <dbl>
#> 1   1.1   2.9 a         4
#> 2   2.1   1.9 b        NA
#> 3   3.1   0.9 c        NA

# But the order of the arguments matters, the names of the list are apparently
# not evaluated: 
df %>%
  mutate(
  test = pmap_dbl(
    list(..3 = x, ..2 = y, ..1 = z),
    ~test_func(x = ..3, y = ..2, cond = ..1))
  )
#> # A tibble: 3 x 4
#>       x     y z      test
#>   <dbl> <dbl> <chr> <dbl>
#> 1   1.1   2.9 a        NA
#> 2   2.1   1.9 b        NA
#> 3   3.1   0.9 c        NA

reprex package(v0.2.0.9000)于2019-03-28创建。