【问题标题】:Purrr map multiple functions and two inputsPurrr 映射多个功能和两个输入
【发布时间】:2021-11-08 17:49:50
【问题描述】:

我正在尝试使用purrr 将多个函数映射到两个输入。下面给出了一个示例,但理想情况下,我想将其扩展到更多功能。尝试执行此操作时,我收到一个错误,即找不到输入,但是,即使我尝试在函数列表中命名输入,这也不能解决问题。

library(yardstick)
library(tidyverse)

funcs <- list(accuracy = yardstick::accuracy_vec,
              recall = yardstick::recall_vec)

n <- 1000
x <- as.factor(rbinom(n, 1, 0.5))
y <- as.factor(rbinom(n, 1, 0.5))

df <- tibble(true = rep(list(y), 3),
             preds = rep(list(x), 3))

df
#> # A tibble: 3 x 2
#>   true          preds        
#>   <list>        <list>       
#> 1 <int [1,000]> <int [1,000]>
#> 2 <int [1,000]> <int [1,000]>
#> 3 <int [1,000]> <int [1,000]>

df %>% map2_df(.x = true, .y = preds, .f = funcs)
#> Error in map2(.x, .y, .f, ...): object 'true' not found

funcs <- list(accuracy = ~yardstick::accuracy_vec(truth = .x, estimate = .y),
              recall = ~yardstick::recall_vec(truth = .x, estimate = .y))

df %>% map2_df(.x = true, .y = preds, .f = funcs)
#> Error in map2(.x, .y, .f, ...): object 'true' not found

理想情况下,我会得到这样的结果:

# A tibble: 3 x 4
  true          preds         accuracy recall
  <list>        <list>           <dbl>  <dbl>
1 <int [1,000]> <int [1,000]>      0.7    0.8
2 <int [1,000]> <int [1,000]>      0.7    0.8
3 <int [1,000]> <int [1,000]>      0.7    0.8

非常感谢任何帮助,TIA

【问题讨论】:

    标签: r dplyr tidyverse purrr


    【解决方案1】:

    当我将数值传递给函数accuracy_vecrecall_vec 时出现错误。我明白了

    错误:truth 应该是一个因素,但提供了一个整数..

    所以我将数据更改为因子。

    library(tidyverse)
    
    n <- 1000
    x <- rbinom(n, 1, 0.5)
    y <- rbinom(n, 1, 0.5)
    
    df <- tibble(true = rep(list(factor(y)), 3),
                 preds = rep(list(factor(x)), 3))
    

    其次,管道将左侧(LHS)的值作为第一个参数传递给右侧的函数。所以当你使用df %&gt;% map2_df(.x = true, .y = preds, .f = funcs)时,df是被隐式传递的。

    您可以编写一个自定义函数来返回一个小标题。

    funcs <- function(.x, .y) {
      tibble(accuracy = yardstick::accuracy_vec(truth = .x, estimate = .y), 
             recall =   yardstick::recall_vec(truth = .x, estimate = .y))
    }
    

    然后使用map2_df 得到一个数据帧作为输出。

    map2_df(df$true, df$preds, funcs)
    

    【讨论】:

      【解决方案2】:

      您可以使用嵌套地图:

      df %>% 
        mutate(map2_dfr(true, preds, ~map_dfc(funcs, do.call, list(.x, .y))))
      

      【讨论】:

        猜你喜欢
        • 2016-10-30
        • 2018-12-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-26
        • 2021-10-28
        • 2020-07-18
        • 1970-01-01
        相关资源
        最近更新 更多