1

我正在模拟标记重新捕获数据。在下面的简短示例中,我有一个矩阵,其中包含 3 个采样周期(列)内的 10 个个体(行)。我有一个矩阵跟踪它们是活着 (1) 还是死了 (0),它们是否存在于研究区域 (1) 或不存在 (0),以及我试图填写的矩阵,它说明它们是否存在每个时期捕获(1)或不捕获(0)。

在我的真实示例中,我有超过 1000 个人的 180 列,我想加快我的 for 循环。在下面的循环中(我循环遍历每个人和每一行),一旦发现当前个人已经死亡,我希望能够跳到下一个个人。我尝试使用 if/else 语句来执行此操作,如果“is.alive=/1”,它会将“j”的值(迭代采样周期)提升到最终值 3。我认为这会得到我晋级下一个人,但我最终得到

"Error in ifelse(is.alive == 1, ifelse(is.pres == 1, ifelse(runif(1) <=:
  unused argument(s) (j = 3)"

有什么建议吗?

survival.mat<-matrix(1,10,3) #Matrix tracking 10 individuals (rows) over 3 time periods (columns)
survival.mat[c(2,4,6),c(2,3)]<-0 #Creating some deaths (1=alive, 0=dead)
present.mat<-survival.mat #A new matrix to see if individuals are present for capture
present.mat[c(1,5,8),2]<-0 #Making some alive individuals unavailable (0) for capture
capture.mat<-matrix(0,10,3) #A matrix to test if individuals were captured
capture.mat[,1]<-1 #All individuals captured on first occasion, since this is when they are marked
cap.prob<-0.5 #our probability of capture


    for(i in 1:10){  #Iterating through the rows (each row is an individual)
        for(j in 2:3){ #Iterating through columns (each column is a time period)

        is.alive <- survival.mat[i,j]
        is.pres <- present.mat[i,j]
        ifelse(is.alive==1,  #If the individual is alive, continue, if not jump ahead to 'j=3' which is what I am using to try to advance the loop
                                ifelse(is.pres==1,ifelse(runif(1)<=cap.prob,capture.mat[i,j]<-1,NA),NA)#If it is alive (previous statement), is it present for capture?  If so, run a capture coinflip.
                                 ,j=3) #Trying to advance the simulation to j = 3 if the individual is not alive
                                }
                        }
4

1 回答 1

3

所以这里发生了两件事:

  1. ifelse想要返回一个值,但您告诉它运行一个任务(赋值运算符=)。如果您想j在 ifelse 中更改为 3,您可以执行以下任一操作:

    ifelse(cond, true stuff, {j=3 ; j})
    ifelse(cond, true stuff, j <- 3) ## assigns 3 to j but also returns j
    
  2. 循环的工作方式for,您无需更改 的值j即可进入下一个循环,R并负责处理(与其他语言不同)。命令next(NOT break) 将带您进入下一次迭代,因此请执行以下操作:

    ifelse(cond, truestuff, next)
    
于 2012-11-09T18:14:04.933 回答