我希望使用optim
最小化函数,如下所示:
yield <- function(data, par) {
with(data, par[1] + (par[2] + par[3]/par[4])*(1-exp(-par[4]*maturity))/(par[4]*maturity) - (par[3]*exp(-par[4]*maturity)/par[4]))
}
min.RSS <- function(data, par) {
sum((data$price - 100*exp(-data$maturity*yield(data, par)))^2)
}
result <- optim(par = theta, min.RSS, data = data))
参数par[1]
和par[4]
必须是非负数,而其他两个不受约束。是否可以在optim
函数中包含这些约束?
由于
答案 0 :(得分:0)
让@BondedDust的建议非常明确:
yield <- function(data, par) {
with(data, par[1] + (par[2] + par[3]/par[4])*(1-exp(-par[4]*maturity))/(par[4]*maturity) - (par[3]*exp(-par[4]*maturity)/par[4]))
}
# the function being optimized
min.RSS <- function(data, par) {
# EXPONENETIATE PARAMTERS 1 AND 4 TO MAKE THEM POSITIVE.
par[1] <- exp(par[1])
par[4] <- exp(par[4])
sum((data$price - 100*exp(-data$maturity*yield(data, par)))^2)
}
PAR <- theta
# LOG TRANSFRORM THE INITIAL VALUES FOR PARAMTERS 1 AND 4
PAR[1] <- log(PAR[1])
PAR[4] <- log(PAR[4])
# CALL optim()
result <- optim(par = PAR,
min.RSS,
data = data))
# THE BEST SET OF PARAMETERS
par <- result$par
# again, exponenetiate paramters 1 and 4 to make them positive.
par[1] <- log(par[1])
par[4] <- log(par[4])