将具有多个参数的函数映射到数据框的多个列

时间:2019-10-02 17:46:34

标签: r functional-programming purrr

我有这样的功能

adstock <- function(x, rate) {

  adstocked_variable <- x 

  for (i in 1:(length(x)-1) ) {
    adstocked_variable[i+1] <-  x[i + 1] + (rate * adstocked_variable[i])
  }
  adstocked_variable
}

还有这样的费率向量:

rates <- seq(0.00, 1, 0.25)

如何将adstock函数映射到mtcars的每一列,对费率向量中的每个数字一次?

我希望输出看起来像这样:

$mpg
   mpg_0.00 mpg_0.25  mpg_0.5
1      21.0 21.00000 21.00000
2      21.0 26.25000 31.50000
3      22.8 29.36250 38.55000
4      21.4 28.74062 40.67500
5      18.7 25.88516 39.03750
6      18.1 24.57129 37.61875
7      14.3 20.44282 33.10938
8      24.4 29.51071 40.95469

$cyl
   cyl_0.00  cyl_0.25   cyl_0.5
1         6  6.000000  6.000000
2         6  7.500000  9.000000
3         4  5.875000  8.500000
4         6  7.468750 10.250000
5         8  9.867188 13.125000
6         6  8.466797 12.562500
7         8 10.116699 14.281250
8         4  6.529175 11.140625

我尝试了以下成功的变体

library(tidyverse)

mtcars %>% 
  map(~adstock(., rates))

1 个答案:

答案 0 :(得分:0)

这是一个主意。

library(purrr)

imap(mtcars, ~map_dfc(rates, function(x){
  dat <- data.frame(adstock(.x, x))
 }) %>% 
   set_names(paste(.y, rates, sep = "_"))
)
# $mpg
#    mpg_0 mpg_0.25  mpg_0.5 mpg_0.75 mpg_1
# 1   21.0 21.00000 21.00000 21.00000  21.0
# 2   21.0 26.25000 31.50000 36.75000  42.0
# 3   22.8 29.36250 38.55000 50.36250  64.8
# 4   21.4 28.74062 40.67500 59.17187  86.2
# 5   18.7 25.88516 39.03750 63.07891 104.9
# 6   18.1 24.57129 37.61875 65.40918 123.0
# 7   14.3 20.44282 33.10938 63.35688 137.3
# 8   24.4 29.51071 40.95469 71.91766 161.7
# 9   22.8 30.17768 43.27734 76.73825 184.5
# 10  19.2 26.74442 40.83867 76.75369 203.7
# 11  17.8 24.48610 38.21934 75.36526 221.5
# 12  16.4 22.52153 35.50967 72.92395 237.9
# 13  17.3 22.93038 35.05483 71.99296 255.2
# 14  15.2 20.93260 32.72742 69.19472 270.4
# 15  10.4 15.63315 26.76371 62.29604 280.8
# 16  10.4 14.30829 23.78185 57.12203 291.2
# 17  14.7 18.27707 26.59093 57.54152 305.9
# 18  32.4 36.96927 45.69546 75.55614 338.3
# 19  30.4 39.64232 53.24773 87.06711 368.7
# 20  33.9 43.81058 60.52387 99.20033 402.6
# 21  21.5 32.45264 51.76193 95.90025 424.1
# 22  15.5 23.61316 41.38097 87.42519 439.6
# 23  15.2 21.10329 35.89048 80.76889 454.8
# 24  13.3 18.57582 31.24524 73.87667 468.1
# 25  19.2 23.84396 34.82262 74.60750 487.3
# 26  27.3 33.26099 44.71131 83.25563 514.6
# 27  26.0 34.31525 48.35566 88.44172 540.6
# 28  30.4 38.97881 54.57783 96.73129 571.0
# 29  15.8 25.54470 43.08891 88.34847 586.8
# 30  19.7 26.08618 41.24446 85.96135 606.5
# 31  15.0 21.52154 35.62223 79.47101 621.5
# 32  21.4 26.78039 39.21111 81.00326 642.9

#  ...