2014-04-08 75 views
0

我想要創建一個向量,其值是從計數行數(對於每列)中,從最後一行開始,並計數「up」直到達到one。例如,對於每列,計數直到滿足條件的行數

1 1 1 
1 1 0 
1 0 0 

將導致以下回答0 1 2。有0行中的一列直到達到1,和1行達到用於塔2直到1

我想實現上述成以下代碼的溶液(#TimeSince):

Lattice <- rep(NA_integer_, 6) # 
Results <- rep(0, 6) # 
TimeSince <- rep(0,6) # 
Prob <- c(0.92, 0.90, 0.85, 0.80, 0.35, 0.15) 

resultList <- list() 

for (j in 1:100) { 
    for (i in 1:6){ 
    if (runif(1,min=0, max=1) < Prob[i]){ 
     Lattice[i] <- 1} 
    else{Lattice[i:6] <- 0} 
    if (Lattice[i] == 0) break()} 

    resultList[[j]] <- Lattice 
    Results <- Lattice + Results 
    #TimeSince[[j]] <- count rows until '1' in Results per column 

    } 
+3

像'申請(M,1,函數(X),其(REV(X)=​​= 1)[1])' –

+0

你是否試圖找到零的最長行數爲1的行s達到了(+那些只有1s)? –

+1

@BenBolker如果稍微修改你的代碼到'apply(m,2,function(x)which(rev(x)== 1)[1])) - 1',並在我的列表中循環這個工作循環。 – nofunsally

回答

0

下面的代碼產生的結果,我上述尋找:

#Edited code based on Ben Bolker comment 
for (j in 1:100) { 
    for (i in 1:6){ 
    if (runif(1,min=0, max=1) < Prob[i]){ 
     Lattice[i] <- 1} 
    else{Lattice[i:6] <- 0} 
    if (Lattice[i] == 0) break()} 

    resultList[[j]] <- Lattice 
    dm <- do.call("rbind",resultList) # added in edit 
    TimeSince <- (apply(dm,2,function(x) which(rev(x)==1)[1])) - 1 # added in edit 

    }