Search code examples
rloopsfor-loopif-statementnested-loops

Not sure how to turn this into a for-loop in R


I am looking for a more elegant way of coding this including for loops. I'd like to not need to index each column of the spreadsheet separately because eventually I'd like to have a much larger "tsf" matrix.

Does anyone have any thoughts on how to do this?

edit: the important part is that if treat = 0, then that row should = 0; if treat = 1, then that row should have a sequence of 0-5 that repeats

I <- 50                     
T <- 10            

treat <- round(runif(I,0,1))

tsf <- matrix(NA, I, T) #if treat = 0, then all rows should = 0; if treat = 1, then all rows should have a sequence of 0-5 that repeats until the end of the row

tsf[,1] <- ifelse(treat > 0, 0, round(runif(I,0,5)))
tsf[,2] <- ifelse(tsf[,1]>0 & tsf[,1]<5, tsf[,1]+1, 0)
tsf[,3] <- ifelse(tsf[,1]!=0 & tsf[,2]<5, tsf[,2]+1, 0)
tsf[,4] <- ifelse(tsf[,1]!=0 & tsf[,3]<5, tsf[,3]+1, 0)
tsf[,5] <- ifelse(tsf[,1]!=0 & tsf[,4]<5, tsf[,4]+1, 0)
tsf[,6] <- ifelse(tsf[,1]!=0 & tsf[,5]<5, tsf[,5]+1, 0)
tsf[,7] <- ifelse(tsf[,1]!=0 & tsf[,6]<5, tsf[,6]+1, 0)
tsf[,8] <- ifelse(tsf[,1]!=0 & tsf[,7]<5, tsf[,7]+1, 0)
tsf[,9] <- ifelse(tsf[,1]!=0 & tsf[,8]<5, tsf[,8]+1, 0)
tsf[,10] <- ifelse(tsf[,1]!=0 & tsf[,9]<5, tsf[,9]+1, 0)


Solution

  • I suppose you had a typo, i.e., i should be 1. Below might be a for loop option for you

    tsf[,1] <- ifelse(treat > 0, 0, round(runif(I,0,5)))
    for (k in 2:10) {
      tsf[,k] <- ifelse(tsf[,1]>0 & tsf[,k-1]<5, tsf[,k-1]+1, 0)
    }