Search code examples
rdataframewhile-loopconditional-statementsapply

how can i continue a while loop after the condition is False?


image of a single column of a dataframe (a = dfmean[,4] )

I' m trying to calculate The maximum number of days with a continuous decrease in daily mean temperature. So, first of all, i' m trying to calculate the number of days with a continuous decrease in daily temperature. After that i will find the maximum number of these values. The problem is that while loop calculates only the first five days with a continuous decrease and stops, as the condition is false. How can i continue with the rest values? OR there is an easier way to do that with apply family?

a= dfmean[,4]i=1 x=0while(a[i+1,]<a[i,]) { x=x+1 print(x) i=i+1`

}`


Solution

  • If this is your data

    set.seed(42)
    df <- data.frame(Date = seq(as.Date("2022-02-01"), as.Date("2022-02-10"), 1), 
                     temp_mean = runif(10) * 10)
    
    df
             Date temp_mean
    1  2022-02-01  9.148060
    2  2022-02-02  9.370754
    3  2022-02-03  2.861395
    4  2022-02-04  8.304476
    5  2022-02-05  6.417455
    6  2022-02-06  5.190959
    7  2022-02-07  7.365883
    8  2022-02-08  1.346666
    9  2022-02-09  6.569923
    10 2022-02-10  7.050648
    

    Get the maximum number of consecutive decreasing values with diff and rle

    df_rle <- rle(diff(df$temp_mean) < 0)
    
    max(df_rle$lengths[df_rle$values], na.rm = T)
    [1] 2