Hi,
I would like to ask that do you know a way to use a loop based recursion with pmap.
(I would like to draw a Solow diagram). Codes enclosed.
library(tidyverse)
K_way <- function(K0 = 100, s, d, A, L, alpha = .3) {
K <- c(K0)
for (i in 2:length(s)) { # loop
Y <- A[i-1]*(K[i-1]^alpha*L[i-1]^(1-alpha))
K[i] <- K[i-1]*(1-d[i]) + s[i]*Y
}
return(K)
}
df <- tibble(t = 1:100) %>%
mutate(
s = .3, n = .05, d = .1, g = ifelse(t < 30, .03, .01),
) %>%
mutate(
A = cumprod(1 + g),
L = 100*cumprod(1 + n),
)
K_way(100, df$s, df$d, df$A, df$L, .3) # numric vector w appropriate length
#> [1] 100.0000 121.9736 145.9455 172.0316 200.3779 231.1589
#> [7] 264.5774 300.8641 340.2786 383.1105 429.6815 480.3471
#> [13] 535.4993 595.5695 661.0320 732.4070 810.2657 895.2341
#> [19] 987.9985 1089.3106 1199.9942 1320.9518 1453.1714 1597.7355
#> [25] 1755.8296 1928.7519 2117.9241 2324.9033 2551.3946 2799.2654
#> [31] 3059.8574 3334.0502 3622.7977 3927.1286 4248.1483 4587.0404
#> [37] 4945.0701 5323.5874 5724.0314 6147.9348 6596.9292 7072.7508
#> [43] 7577.2466 8112.3815 8680.2450 9283.0600 9923.1903 10603.1507
#> [49] 11325.6158 12093.4312 12909.6240 13777.4151 14700.2315 15681.7202
#> [55] 16725.7620 17836.4875 19018.2927 20275.8570 21614.1613 23038.5079
#> [61] 24554.5415 26168.2716 27886.0961 29714.8268 31661.7165 33734.4879
#> [67] 35941.3636 38291.0995 40793.0190 43457.0503 46293.7657 49314.4235
#> [73] 52531.0128 55956.3009 59603.8843 63488.2423 67624.7948 72029.9634
#> [79] 76721.2366 81717.2390 87037.8057 92704.0608 98738.5011 105165.0859
#> [85] 112009.3315 119298.4132 127061.2726 135328.7329 144133.6212 153510.8988
#> [91] 163497.7999 174133.9798 185461.6720 197525.8561 210374.4364 224058.4320
#> [97] 238632.1795 254153.5487 270684.1725 288289.6915
df %>%
mutate(
K = pmap_dbl(list(100, s, d, A, L, .3), K_way)
# causing an error since the function is evaluated rowwise
)
#> Error: Problem with `mutate()` column `K`.
#> i `K = pmap_dbl(list(100, s, d, A, L, 0.3), K_way)`.
#> x replacement has length zero
Created on 2021-09-18 by the reprex package (v2.0.1)