编辑:这是一个持续的再平衡投资组合问题。
有谁知道递归调用用什么函数吗?
设 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/