mercredi 2 août 2017

Assign a new column based on consecutive values after a defined point

I have a data frame with a column of minutes.

data.frame(minutes=(c(180,180,180,180,180,180,180,180,180,180,180,230,180,180,379,9847,298)))

I need to assign a new binary column based on the mean minute values of 8 consecutive rows: when the mean equals 180(+/-2) I assign a value of 1, which I have managed using the loop:

total <- nrow(dat)
len <- 1:total

for(i in len){
  temp<- dat[i:(i+8),] 
  xdiff<- ifelse(mean(temp$minutes)>178 & mean(temp$minutes)<182 ,1,0)
  temp2<- cbind(dat[i,],xdiff)
  if(i==1) {dat2 <- temp2}
  else {dat2<- rbind(dat2,temp2)}
} 

What I now need is for the the binary column output to assign each row after the first value of 1 to be a 1 until the minutes column is no longer 180(+/-2) as I need the final 180 values to also be assigned values of 1 even though their 8 consecutive row mean value is not 180(+/-2).

So would create a data frame looking like this:

data.frame(minutes=(c(180,180,180,180,180,180,180,180,180,180,180,230,180,180,379,9847,298)), xdiff=(c(1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0)))

I have tried using another loop after running the initial loop:

total2<-(nrow(dat2))
len2 <- 1:total2
for(j in len2){
  if (j==1) {
    dat2$xdiff[j]=dat2$xdiff[j]
   } else if (j==total2) {
     dat2$xdiff[j]=dat2$xdiff[j]
   }
     else if(dat2$xdiff[j]==1 & dat2$diffsecs[j+1]>178 & dat2$diffsecs[j+1]<182)  {
        seals6$xdiff[j+1]<-1
            } else{dat2$xdiff[j+1]<-0}

 }

But this just produces a vector of 0s. Any ideas?

Aucun commentaire:

Enregistrer un commentaire