0

I would like to find the index of the longest sequence of 1. I have the following data:

date1 <- c(1,0,1,1,0)
date2 <- c(0,1,0,1,0)
date3 <- c(0,1,1,1,0)
date4 <- c(1,1,1,1,1)
df <- as.data.frame(cbind(date1, date2, date3, date4))
df <- df %>% 
  pivot_longer(-c(), names_to = "dates", values_to = "drought_day")
df$pindex <- as.factor(rep(seq(from = 1, to = 5), each = 4))

I have used the rle function to separate the 0s and 1s.

rle_runs <- tapply(df$drought_day, df$pindex, function(y) rle(y))

the output should look like this:

index rle_max_length rle_max_index max_date
1      1          1         1    date1
2      2          3         2    date2
3      3          2         3    date3
4      4          4         4    date4
5      5          1         4    date4

if i now apply the following it doesn't give me the actual index, but only calculates for the values ==1 the index of the maximum sequence:

max_index <- tapply(df$drought_day, df$pindex, function(y) with(rle(y), which.max(lengths[values==1])))

I'm a bit desperate because I've googled around so much but I can't find my problem. I am unfortunately still relatively new with r. I am happy about any help! My dataset is also extremely large, so I try to avoid for-loops. Thanks!

helene
  • 1

0 Answers0