I'm trying to create a data frame where a column exists that holds values representing the length of runs of positive and negative numbers, like so:
Time V Length 0.5 -2 1.5 1.0 -1 1.5 1.5 0 0.0 2.0 2 1.0 2.5 0 0.0 3.0 1 1.75 3.5 2 1.75 4.0 1 1.75 4.5 -1 0.75 5.0 -3 0.75
Length column sums the length of time that the value has been positive or negative. Zeros are given a
0 since they are an inflection point. If there is no zero separating the sign change, the values are averaged on either side of the inflection.
I am trying to approximate the amount of time that these values are spending either positive or negative. I've tried this with a
for loop with varying degrees of success, but I would like to avoid looping because I am working with extremely large data sets.
I've spent some time looking at
diff as they are used in this question about sign changes. I've also looked at this question that uses
aggregate to sum consecutive duplicate values. I feel like I could use this in combination with
diff, but I'm not sure how to retroactively assign these sums to the ranges that created them or how to deal with spots where I'm taking the average across the inflection.
Any suggestions would be appreciated. Here is the sample dataset:
dat <- data.frame(Time = seq(0.5, 5, 0.5), V = c(-2, -1, 0, 2, 0, 1, 2, 1, -1, -3))