Search code examples
rrangemax

maximum value from values between two zeros


I have values in a column and would like to pick the maximum value from non-zero ranges in that column. A range is defined by non-zero values between two zeros. I am not sure if this explanation is right though. Kindly see the example below. I have done this is excel but I need to be able to do this in R and I am not sure of how to go about it. Any guide on where to start will be appreciated. My target is the column named "out".

ind<-c(0,0,0,0.4,0.6,0.7,0.7,0.9,0,0,0,1,3,10,0,0)
out<-c(0,0,0,0.9,0.9,0.9,0.9,0.9,0,0,0,10,10,10,0,0)
bbb<-data.frame (ind,out)

Solution

  • Here is a way to do it iteratively. Probably slow for big datasets.

    m=c(0,0,0,0.1,0.6,0.3,0,0,0.2,0.1,0.2,0,0,0)
    maxims=0
    aux=NULL
    pos=1
    for (i in 1:length(m)){
    
      if (m[i]!=0){
        aux=c(aux,m[i])
      }
      if (m[i]==0 && length(aux)>0){
        maxims[pos]=max(aux)
        aux=NULL
        pos=pos+1
      }
    }
    > maxims
    [1] 0.6 0.2