简体   繁体   English

跨两个嵌套列表列应用数学函数

[英]Apply mathematical function across two nested list-columns

I have a question regarding the purrr map function.我有一个关于 purrr 地图功能的问题。

I would like to apply a mathematical function across two nested list-columns within a tibble.我想在一个小标题中的两个嵌套列表列中应用数学函数。 I would like to convertthe column to a numeric vector to perform my calculations.我想将列转换为数值向量来执行我的计算。

But i keep receiving the error: Error in mutate_impl(.data, dots) : Evaluation error: non-numeric argument to mathematical function.但我一直收到错误: mutate_impl(.data, dots) 中的错误:评估错误:数学函数的非数字参数。

I have tried applying the custom function using purrr :: map2 but it throws an error.我曾尝试使用 purrr :: map2 应用自定义函数,但它引发错误。 Would lapply do the trick? lapply 能解决问题吗? Please see below.请参阅下文。

mape <- function(actual,pred){
  mape <- mean(abs(ifelse(actual==0,
                          ifelse(pred==0,0,abs(1 - pred)*100),((actual - pred)/actual*100))))
  return (mape)
}

mape_score <- mape_lab %>% mutate(mape_score=map2(data[],pred_lab[],mape))

> mape_lab
# A tibble: 30 x 3
   Location     pred_lab   data             
   <fct>        <list>     <list>           
 1 Balsthal     <dbl [12]> <tibble [12 x 1]>
 2 Balsthal     <dbl [12]> <tibble [12 x 1]>
 3 Balsthal     <dbl [12]> <tibble [12 x 1]>
 4 Bettlach     <dbl [12]> <tibble [12 x 1]>
 5 Bettlach     <dbl [12]> <tibble [12 x 1]>
 6 Bettlach     <dbl [12]> <tibble [12 x 1]>
 7 Oberdorf Bio <dbl [12]> <tibble [12 x 1]>
 8 Oberdorf Bio <dbl [12]> <tibble [12 x 1]>
 9 Oberdorf Bio <dbl [12]> <tibble [12 x 1]>
10 Grenchen     <dbl [12]> <tibble [12 x 1]>

Expected Outcome:预期结果:

> mape_lab
# A tibble: 30 x 3
   Location     pred_lab   data              mape_score
   <fct>        <list>     <list>            <num>
 1 Balsthal     <dbl [12]> <tibble [12 x 1]>  1244
 2 Balsthal     <dbl [12]> <tibble [12 x 1]>  32545
 3 Balsthal     <dbl [12]> <tibble [12 x 1]>  54554
 4 Bettlach     <dbl [12]> <tibble [12 x 1]>  .....
 5 Bettlach     <dbl [12]> <tibble [12 x 1]>
 6 Bettlach     <dbl [12]> <tibble [12 x 1]>
 7 Oberdorf Bio <dbl [12]> <tibble [12 x 1]>
 8 Oberdorf Bio <dbl [12]> <tibble [12 x 1]>
 9 Oberdorf Bio <dbl [12]> <tibble [12 x 1]>
10 Grenchen     <dbl [12]> <tibble [12 x 1]>

While asking question please add a reproducible example .在提出问题时,请添加一个可重现的示例

As far your question is concerned, the main issue is data is tibble and pred_lab is numeric vector.至于你的问题而言,主要的问题是datatibblepred_lab是数值向量。 You can flatten the data since it has only one column and then apply mape .您可以将data flatten ,因为它只有一列,然后应用mape

library(tidyverse)
mape_lab %>% mutate(mape_score = map2_dbl(data %>% flatten, pred_lab, mape))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM