[英]Setting range for function (Error with replacement has length zero in R )
我在生成“替換錯誤的長度為零”時遇到問題。 是這部分代碼引起的。
j <- rev(new_data_basic)
deltak <- function(t){
j[t]}
我想根據 t 的索引位置獲取 j 的一個元素。 但是,實現不能處理數據長度之外的值,例如 t = 25,它不起作用。
例如,如果我將我的代碼更改為:
deltak <- function(t){
0.06 - 0.001*t}
它工作得很好,因為它沒有范圍限制。
以下是我的完整示例代碼:
new_data_basic <- c(0.02981, 0.02973, 0.02957, 0.02930, 0.02888, 0.02834, 0.02783, 0.02745, 0.02725, 0.02724, 0.02744, 0.02775, 0.02809, 0.02845, 0.02878, 0.02910, 0.02939, 0.02966, 0.02990, 0.03012)
S <- 20000
j <- rev(new_data_basic)
deltak <- function(t){
j[t]}
h <- 0.05
k <- seq(0,20,h)
n <- length(k)
Vt <- rep(1,n)
Vt[n] <- 60000
# need to write the mu function next
mu <- function(x,t){
A <- .00022
B <- 2.7*10^(-6)
c <- 1.124
mutemp <- A + B*c^(x+t)
out <- ifelse(t<=2, 0.9^(2-t)*mutemp,mutemp)
out}
# express the initial reserve as a function of premium rate P
V0 <- function(P) {
m <- n
while (m>which(k==10)) {
m <- m-1
num <- Vt[m+1] - h*P
den <- h*deltak(k[m]) + 1
Vt[m] <- num/den
}
m <- which(k==10)
while (m>1) {
m <- m-1
num <- Vt[m+1] - h*P + h*S*mu(40,k[m])
den <- h*deltak(k[m]) + h*mu(40,k[m]) + 1
Vt[m] <- num/den
}
Vt[1]}
# the following solves for P such that initial reserve V0=0
P <- uniroot(V0,c(0,60000))$root
我該如何處理這個限制?
問題是小於 1 的數字的deltak()
是未定義的。 當您執行deltak(k[m])
時,R 在幕后所做的是使用floor(m)
來索引k
。 所以當m=21
> deltak(k[21])
# [1] 0.0299
其中k[21]
等於 1。但是,當k[22]
為 1.05 時,會得到相同的結果。
> k[22]
# [1] 1.05
> deltak(k[22])
# [1] 0.0299
當m < 21
則k[m]
< 1
> k[20]
# [1] 0.95
> deltak(k[20])
# numeric(0)
問題是k
序列低於 1。您可以從 1 開始k
序列嗎?
new_data_basic <- c(0.02981, 0.02973, 0.02957, 0.02930, 0.02888, 0.02834, 0.02783, 0.02745, 0.02725, 0.02724, 0.02744, 0.02775, 0.02809, 0.02845, 0.02878, 0.02910, 0.02939, 0.02966, 0.02990, 0.03012)
S <- 20000
j <- rev(new_data_basic)
deltak <- function(t){
j[t]}
h <- 0.05
k <- seq(1,20,h)
n <- length(k)
Vt <- rep(1,n)
Vt[n] <- 60000
# need to write the mu function next
mu <- function(x,t){
A <- .00022
B <- 2.7*10^(-6)
c <- 1.124
mutemp <- A + B*c^(x+t)
out <- ifelse(t<=2, 0.9^(2-t)*mutemp,mutemp)
out}
# express the initial reserve as a function of premium rate P
V0 <- function(P) {
m <- n
while (m>which(k==10)) {
m <- m-1
num <- Vt[m+1] - h*P
den <- h*deltak(k[m]) + 1
Vt[m] <- num/den
}
m <- which(k==10)
while (m>1) {
m <- m-1
num <- Vt[m+1] - h*P + h*S*mu(40,k[m])
den <- h*deltak(k[m]) + h*mu(40,k[m]) + 1
Vt[m] <- num/den
}
Vt[1]}
# the following solves for P such that initial reserve V0=0
P <- uniroot(V0,c(0,60000))$root
P
#> [1] 2385.192
由reprex 包(v2.0.1) 創建於 2022-12-22
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.