I have created a simplified version of my data:
a <- data.frame(a = c(0,1,2,3,2,1,0,-1,-2,-3,-2,-1,
0,1,2,3,4,3,2,1,0,-1,-2,-3,-2,-1,
0,1,2,1,0,-1,-2,-3,-2,-1,0,1,2,3,2,1,
0,-1,-2,-3,-2,-1,0,1,2,3,2,1,
0,-1,-2,-3,-4,-3,-2,-1,0))
a$b <- seq(1,length(a$a),1)
I try to detect the cycles in the data as the following (open to better suggestions):
library(quantmod)
max <- findPeaks(a$a)
min <- findValleys(a$a)
This actually gives be the point after the maximum and minimum. I want to find the span and set point of each cycle.
cycle: - The first cycle is defined as the first data point to the one before the first set point. For example, considering the first set point is -1.0, the first cycle is defined at rows 1 to 12. Row 12 is selected as the end of the cycle because it occurs after the first peak and valley and is also equal or smaller than -1.0. The second cycle starts at row 13 and goes to row 27, because row 27 is has an amplitude of 0 which is less than or equal to 0.5, and occurs after the second peak and valley points.:
span <- a[max-1,]$a-a[min-1,]$a
set <- a[max,]$a - span/2
I want to group the data in the original dataframe a and assign the cycle number, span, and set point of each cycle (group) to the corresponding group of rows.
The desired output is:
> print(a)
a b cycles span set
1 0 1 1 6 -1.0
2 1 2 1 6 -1.0
3 2 3 1 6 -1.0
4 3 4 1 6 -1.0
5 2 5 1 6 -1.0
6 1 6 1 6 -1.0
7 0 7 1 6 -1.0
8 -1 8 1 6 -1.0
9 -2 9 1 6 -1.0
10 -3 10 1 6 -1.0
11 -2 11 1 6 -1.0
12 -1 12 1 6 -1.0
13 0 13 2 7 0.5
14 1 14 2 7 0.5
15 2 15 2 7 0.5
16 3 16 2 7 0.5
17 4 17 2 7 0.5
18 3 18 2 7 0.5
19 2 19 2 7 0.5
20 1 20 2 7 0.5
21 0 21 2 7 0.5
22 -1 22 2 7 0.5
23 -2 23 2 7 0.5
24 -3 24 2 7 0.5
25 -2 25 2 7 0.5
26 -1 26 2 7 0.5
27 0 27 2 7 0.5
28 1 28 3 5 -1.5
29 2 29 3 5 -1.5
30 1 30 3 5 -1.5
31 0 31 3 5 -1.5
32 -1 32 3 5 -1.5
33 -2 33 3 5 -1.5
34 -3 34 3 5 -1.5
35 -2 35 3 5 -1.5
36 -1 36 4 6 -1.0
37 0 37 4 6 -1.0
38 1 38 4 6 -1.0
39 2 39 4 6 -1.0
40 3 40 4 6 -1.0
41 2 41 4 6 -1.0
42 1 42 4 6 -1.0
43 0 43 4 6 -1.0
44 -1 44 4 6 -1.0
45 -2 45 4 6 -1.0
46 -3 46 4 6 -1.0
47 -2 47 4 6 -1.0
48 -1 48 4 6 -1.0
49 0 49 5 7 -1.5
50 1 50 5 7 -1.5
51 2 51 5 7 -1.5
52 3 52 5 7 -1.5
53 2 53 5 7 -1.5
54 1 54 5 7 -1.5
55 0 55 5 7 -1.5
56 -1 56 5 7 -1.5
57 -2 57 5 7 -1.5
58 -3 58 5 7 -1.5
59 -4 59 5 7 -1.5
60 -3 60 5 7 -1.5
61 -2 61 5 7 -1.5
62 -1 62 5 7 -1.5
63 0 63 5 7 -1.5
