Hi, I'm a beginner in R and need some help in calculating difference between row entries using a condition from another column. In the below dataset i need to create a column with difference in column A with the condition that the difference in A should be calculated with the previous entry in which the corresponding C is a non zero and grouped by ID.
ID A C
1 0 12
1 2 0
1 4 0
1 6 12
1 42 12
1 46 0
1 48 12
1 60 12
1 66 12
1 70 0
2 0 19
2 1.5 0
2 4.5 0
2 6 19
2 12 19
2 16 0
2 18 19
2 22 0
2 24 19
The expected output would look like as in Column X, any help is highly appreciated.
I apologize if the format of question or readability is not clear.
ID A C X
1 0 12 0
1 2 0 2
1 4 0 4
1 6 12 6
1 42 12 36
1 46 0 4
1 48 12 6
1 60 12 12
1 66 12 6
1 70 0 4
2 0 19 0
2 1.5 0 1.5
2 4.5 0 4.5
2 6 19 6
2 12 19 6
2 16 0 4
2 18 19 6
2 22 0 4
2 24 19 6