How to avoid multiple for loop - R Programing : I have a dataframe that has 175180 rows and 301 columns. My first 6 columns are filled with data and after that columns in (2k+1) [k>=5] are filled and rest are null. The null columns will be filled based on the values in columns that will get filled with the for loop running.

Since, it will be an element wise comparison for each column, I am using two for loops, the inner one to run through all the columns and the outer one to run through all the rows. This is taking like infinite time to run. How can I optimise this?

I tried removing the outer for loop and the j elements from my code, but then it just compares vector of length 1 and I am not able to do element wise comparison. Following is my code :

    for (j in 1:175180) {
        for (i in 6:(ncol(nsd)-2)) {
           if ((i-1)%%5==0) {nsd[j,i]<-nsd[j,i]}
           else if ((i-2)%%5==0) {nsd[j,i]<-nsd[j,i-1]}
           else if ( (i-3)%%5==0 && nsd[j,i-1]>0  &&  nsd[j,i-1] >= nsd[j,i-3] ) {nsd[j,i] <- nsd[j,i-1] - nsd[j,i-3]}
           else if ((i-3)%%5==0 && nsd[j,i-1]>=0  &&  nsd[j,i-1]<nsd[j,i-3]) {nsd[j,i]<- 0}
           else if ((i-4)%%5==0 && nsd[j,i+2]>=(nsd[j,i-1]+nsd[j,i-4])) {nsd[j,i]<- nsd[j,i-1]+nsd[j,i-4]}
           else if ((i-4)%%5==0 && nsd[j,i+2]<(nsd[j,i-1]+nsd[j,i-4])) {nsd[j,i]<- nsd[j,i+2]}
           else if ((i-5)%%5==0 && (nsd[j,i-2] + nsd[j,i-5]) > nsd[j, i-1]) {nsd[j,i]<- nsd[j,i-2] + nsd[j,i-5] - nsd[j, i-1] }
           else if ((i-5)%%5==0 && (nsd[j,i-2] + nsd[j,i-5]) <= nsd[j, i-1]) {nsd[j,i]<- 0 }
       }}
