我试图使用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
发布于 2021-09-13 12:42:58
您可以使用嵌套映射:
df %>%
mutate(map2_dfr(true, preds, ~map_dfc(funcs, do.call, list(.x, .y))))发布于 2021-09-13 12:52:45
当我将数值传递给函数accuracy_vec和recall_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))第二,管道将左手边的值作为第一个参数传递给右边的函数.因此,当您使用df %>% map2_df(.x = true, .y = preds, .f = funcs)时,df将被隐式传递。
您可以编写一个自定义函数来返回tibble。
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)https://stackoverflow.com/questions/69162624
复制相似问题