递归地使用输出作为函数的输入

标签 r

编辑:这是一个持续的再平衡投资组合问题。

有谁知道递归调用用什么函数吗?

设 s=库存;

设c=现金;

设X_0=初始财富;

让 r = 是一个随机向量,看起来像 (1,-0.5,-0.5,1,-.5,1,1,1-0.5,...) #获得 1 或 0.5 的几率各为 50% .

X_0 = s+c

X_1 = 1/2*x_0*(1+r) + 1/2*x_0

X_2 = 1/2*x_1*(1+r) + 1/2*x_1 #把这个方程中的x_0改成x_1,就这样

X_3 = 1/2*x_2*(1+r) + 1/2*x_2
.... 等等,

R 中是否有函数将上一步的输入作为这一步的输入?

打电话吗?申请?记起?我想不通!

提前致谢!

最佳答案

它是为高阶函数Reduce 量身定做的工作。这是代码

calc_wealth <- function(x, r){
  return(0.5*x*(1 + r) + 0.5*x)
}

x0 <- 10 
set.seed(1234) 
r  <- sample(c(-0.5, 1), size = 5, replace = TRUE, prob = c(0.5, 0.5))

wealth <- Reduce('calc_wealth', r, init = x0, accumulate = TRUE)

> r
[1]  1.0 -0.5 -0.5 -0.5 -0.5
> wealth
[1] 10.000000 15.000000 11.250000  8.437500  6.328125  4.746094

这里是从帮助文件中提取的 Reduce 的相应文档。

Reduce(f, x, init, right = FALSE, accumulate = FALSE)

Reduce uses a binary function to successively combine the elements of a given vector and a possibly given initial value. If init is given, Reduce logically adds it to the start (when proceeding left to right) or the end of x, respectively. If this possibly augmented vector v has n > 1 elements, Reduce successively applies f to the elements of v from left to right or right to left, respectively. I.e., a left reduce computes l_1 = f(v_1, v_2), l_2 = f(l_1, v_3), etc., and returns l_{n-1} = f(l_{n-2}, v_n),

关于递归地使用输出作为函数的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8468733/

相关文章:

c++ - 在 cpp 程序中使用 Zeroin.c

r - 在 R 中将 fread 与 foreach 和 doParallel 结合使用

r - 如何根据一个因素的水平从数据框中删除列?

R devtools::install_github ("jzsbioinfo/APRD") utils::download.file(url,path,method=method,quiet=quiet,

r - 为什么使用 as.factor() 而不仅仅是 factor()

r - 为什么这个 geom_polygon 只包含整数而不包含小数?

r - 在 R 中,将函数向量传递给另一个函数并按名称引用每个传递的函数

r - 使用 dplyr 在许多列上过滤多个条件

r - 根据 R 中下一个有序组值获取每组的下一个值

ruby - 可扩展依赖缓存