我想创建一个向量,其值来自计算行数(对于每列),从最后一行开始,并计算"向上"直到达到one
。例如,
1 1 1
1 1 0
1 0 0
会产生以下答案0 1 2
。在第一列中达到1
之前有0行,在第2列达到1
之前有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
}
答案 0 :(得分: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
}