سؤال

I would like to create a vector whose values are derived from counting the number of rows (for each column), starting at the last row, and counting "up" until a one is reached. For example,

1 1 1
1 1 0
1 0 0

would result in the following answer 0 1 2. There are 0 rows until 1 is reached in column one, and 1 row until a 1 is reached for column 2, etc.

I would like to implement the solution described above into the following code (#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

  }
هل كانت مفيدة؟

المحلول

The following code produces the result I was seeking above:

#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 مع الإسناد
لا تنتمي إلى StackOverflow
scroll top