通过改变向量内的值来优化R.

时间:2017-04-23 04:08:34

标签: r loops optimization constraints

我是R的新手,想用R来解决一个简单的问题。

我正在尝试优化概率加权消费,最终余额为零。初始金额为1。有人可以帮忙吗?我得到了一些尝试使用optim的初始代码,但没有成功。

ret <- rnorm(n = 4)
prob <- seq(0.9,0.4,by = 0.1)
money <- rep(NA,4)


consumption <- function(consumption){
    consumption[3] <- 1 - (consumption[1]+consumption[2])
    money[1] <- 1
    for (i in 2:4){
        money[i] <- (money[i-1] - consumption[i-1])*(1+ret[i])
    }
    #we have to make sure money[4] = 0, i don't know where to put this.
    money[4] = 0
    return(-consumption%*%t(prob))
}
optim(consumption,c(0.1,0.1,0.8))

0 个答案:

没有答案