[英]Count number of rows in each column in a dataframe that specify a specific condition
[英]For each column, count number of rows until condition is met
我想創建一個向量,其值是從對行數進行計數(針對每一列)開始,從最后一行開始,然后對“向上”進行計數,直到達到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
}
以下代碼產生了我在上面尋找的結果:
#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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.