首页 > 解决方案 > 如何以 tibble 作为返回值对嵌套数据运行/编写映射函数?

问题描述

我想自己编写两个函数并将这些函数应用于嵌套数据。

第一个函数的任务是访问嵌套数据(名称:GROSS)的数据,使用这些值作为输入,用它们计算并将它们写回与 GROSS 列相同的结构中。结果将存储在一个新列(名称 TEST01)中。

第二个函数应该从 GROSS 中减去 TEST01 的值。

我的问题是函数一次只能写回一个值(对吗?),因此我使用 LIST 作为输出。所以碰巧我在列表中有一个列表作为结果,而不是列表中的小标题。如何调整结果?

这是一个例子:

library(tidyverse)
library(purrr)

df <- as_tibble(matrix(c("A1000", 2016, 2016, 1000, 800, 200, 
"A1000", 2016, 2017, 50, 100, -50, "A1000", 2016, 2018, 0, -40, 40, 
"A1001", 2016, 2016, 500, 0, 500, "A1002", 2017, 2017, 2000,0, 2000, 
"A1002", 2017, 2018, 0, -3000, -3000), nrow = 6, byrow = TRUE, 
dimnames = list(NULL, c("Contract", "Year", "AccoutingYear", "Income", "Costs", "Result"))))%>% 

mutate(Contract = as.factor(Contract), 
       Income   = as.numeric(Income), 
       Costs    = as.numeric(Costs),
       Result   = as.numeric(Result)) %>%

nest(GROSS = c(AccoutingYear, Income, Costs, Result))

T_FUN <- function(df, Quota = 0.4, Provision = 0.2) {
return(list(
            AccoutingYear = df$AccoutingYear, 
            Income    = as.numeric(df$Income * Quota),
            Costs     = as.numeric(df$Costs  * Quota), 
            Provision = as.numeric(df$Income * Quota * Provision)))
}

df %>% mutate(TEST01 = map(.x = GROSS, Quota = 0.3, Provision = 0.25,.f = T_FUN))

对于第二个功能,我对方法没有任何想法。

有谁知道可能的解决方案?提前谢谢了。托拜厄斯

标签: rfunctiontidyversepurrr

解决方案


T_FUN返回一个小标题而不是一个列表没有问题。确切地弄清楚你想要完成什么有点困难,但听起来你正在寻找一种方法来并行迭代两个数据帧列表。一种方法是使用map2from purrr。你可以尝试这样的事情:

T_FUN <- function(df, Quota = 0.4, Provision = 0.2) {
  return(tibble(
    AccountingYear = df$AccountingYear,
    Income = as.numeric(df$Income * Quota),
    Costs = as.numeric(df$Costs * Quota),
    Provision = as.numeric(df$Income * Quota * Provision)
  ))
}

R_FUN <- function(df1, df2) {
  inner_join(df1, df2, by = "AccountingYear") %>% 
    summarise(
      AccountingYear,
      Income = Income.x - Income.y,
      Costs = Costs.x - Costs.y,
      Provision = Result - Provision
    )
}

df %>% 
  mutate(
    TEST01 = map(.x = GROSS, Quota = 0.3, Provision = 0.25, .f = T_FUN),
    RESU01 = map2(GROSS, TEST01, R_FUN)
  ) %>% 
  pull(RESU01)

#> [[1]]
#> # A tibble: 3 x 4
#>   AccountingYear Income Costs Provision
#>   <chr>           <dbl> <dbl>     <dbl>
#> 1 2016              700   560     125  
#> 2 2017               35    70     -53.8
#> 3 2018                0   -28      40  
#> 
#> [[2]]
#> # A tibble: 1 x 4
#>   AccountingYear Income Costs Provision
#>   <chr>           <dbl> <dbl>     <dbl>
#> 1 2016              350     0      462.
#> 
#> [[3]]
#> # A tibble: 2 x 4
#>   AccountingYear Income Costs Provision
#>   <chr>           <dbl> <dbl>     <dbl>
#> 1 2017             1400     0      1850
#> 2 2018                0 -2100     -3000

reprex 包于 2021-05-25 创建(v1.0.0)


推荐阅读