用真假语句推进'for-loop'

时间:2012-11-09 18:01:39

标签: r

我正在模拟标记重新捕获数据。在下面的缩略示例中,我有一个矩阵,在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
                                }
                        }

1 个答案:

答案 0 :(得分:3)

所以这里有两件事:

  1. ifelse想要返回一个值,而是告诉它运行一个任务(赋值运算符=)。如果您想在ifelse中将j更改为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负责处理({1}}与那种方式不同于其他语言)。命令next(非break)将带您进入下一次迭代,所以:

    ifelse(cond, truestuff, next)