I have a list of multiple dataframes, each of which comprises a string of dates and, for each date, either +1 to indicate an increase or -1 for a decrease.
Here’s an example
security1 <- data.frame(
date = seq(from =as.Date('2019-01-01'), to = as.Date('2019-01-10'), by = 'day'),
direction = c(1, 1, 1, -1, -1, 1, 1, 1, 1, -1))
security2 <- data.frame(
date = seq(from =as.Date('2019-01-01'), to = as.Date('2019-01-10'), by = 'day'),
direction = c(1, -1, 1, -1, -1, 1, 1,- 1, 1, -1))
clcn <- list(Sec1 = security1, Sec2 = security2)
For each dataframe, I am trying to find the length of the most recent string of changes and last time the number was bigger than this. It may be that the current streak is just 1 day if the previous day’s move was in the other direction.
I’ve searched for several days for an answer to this and found the following using sequence and rle for a single dataframe at Compute counting variable in dataframe
sequence(rle(as.character(data$list))$lengths)
But I’m struggling to feed that into lapply or map to get it to iterate over the list.
I don’t mind the exact output, but ideally it would include: Dataframe name, current streak, previous streak that’s longer, and date that streak ended. But at the most basic, just getting the sequence number added as a new column on the dataframe would be a huge help, and I can (try to) take it from there.