0

我正在尝试编写一个使用内置函数的 for 循环,在每次运行时更改其参数之一的值。

内置函数是来自 msm 包的 qmatrix.mns(多阶段马尔可夫模型)。它计算不同阶段之间的转换率。它的主要论点是:多阶段马尔可夫模型(msm.Full)和协变量(在列表中提供)。

我写了以下函数(它有效):

transRate<-function(grossTon,held, cpue){
  estim<-data.frame(matrix(rep(0,21),7,3))  
  for(i in 1:3){  
    qMatrix<-qmatrix.msm(msm.Full,  ci="normal", covariates=list(grossTon=grossTon,    held=held, cpue=cpue,period=i))

          estim[i]<-qMatrix$estimates[c(5,2,10,7,13,14,15)]# extracts transition rates that I'm interested in
          rownames(estim)<-c("q12","q21","q23","q32","q14","q24","q34")
          colnames(estim)<-c("period 1", "period 2","period 3")
        }

          return(estim)                     
    }                    

    transRate(grossTon=10,held=10,cpue=0.5)

结果是:

    period1     period2     period3
q12 0.011523315 0.01100657  0.01051299
q21 0.006939337 0.00528312  0.004022193
q23 0.161752987 0.079884    0.039451841
q32 0.016379169 0.01661803  0.01686038
q14 1.134517831 1.13026321  1.126024543
q24 0.426243172 0.78585263  1.448854529
q34 0.240552571 0.74682982  2.318639844

这很容易,因为协变量“周期”有 3 个可能的值:1、2、3,但是当我尝试使用协变量“grossTon”时情况有所不同,其潜在值在 10 到 120 之间。我想要的是GrossTon 的值为 10、20、30、...、120。

请看看我做了什么:

transRate<-function(held, cpue, period){
estim<-data.frame(matrix(rep(0,84),7,12)) 
grossT<-c(10,20,30,40,50,60,70,80,90,100,110,120)
  for(i in grossT){  #I guess the problem is here
    qMatrix<-qmatrix.msm(msm.Full,  ci="normal", covariates=list(grossTon=i, held=held, cpue=cpue,period=period))
    estim[i]<-qMatrix$estimates[c(5,2,10,7,13,14,15)]
    rownames(estim)<-c("q12","q21","q23","q32","q14","q24","q34")
    colnames(estim)<-c("10","20","30","40","50","60","70","80","90","100","110","120")

   }
    return(estim)                     
}                    

transRate(held=10,cpue=0.5,period=1)

我期待的是以下输出:

    10  20  30  40  50  60  70  80  90  100 110 120
q12                                             
q21                                             
q23                                             
q32                                             
q14                                             
q24                                             
q34 

提前非常感谢。

4

1 回答 1

2

您可以在任何所需的向量上运行循环。因此:

for (i in seq(10,120,by=10)) 

是解决它的一种方法。在一般情况下,您可以这样做

for (i in c(10,15,23,50,100,273))

或您需要的任何值。

于 2013-01-15T12:32:05.040 回答