Often when manipulating time series, you may want to get difference between adjacent elements in a list.
Take a look at the example below:
"Original" is the original time series list of Date/Value, with the Delta row illustrating the expected dela we are trying to calculate.
Linq can handle this in a pretty simple way (this can be pasted into linqpad):
var original = new [] { Tuple.Create(new DateTime(2010, 1, 1), 100), Tuple.Create(new DateTime(2010, 2, 1), 50), Tuple.Create(new DateTime(2010, 3, 1), 75) }; var anchor = Tuple.Create(new DateTime(2009, 12, 1), 0); var B = (new []{ anchor }).Concat(original); var A = original; var deltas = A.Zip(B, (a, b) => Tuple.Create(a.Item1, a.Item2 - b.Item2)); deltas.Dump(1);
Note that if you don't really care about the first diff, you can simply Skip and Zip like so:
var B = new [] { Tuple.Create(new DateTime(2010, 1, 1), 100), Tuple.Create(new DateTime(2010, 2, 1), 50), Tuple.Create(new DateTime(2010, 3, 1), 75) }; var A = B.Skip(1); var deltas = A.Zip(B, (a, b) => Tuple.Create(a.Item1, a.Item2 - b.Item2)); deltas.Dump(1);
No comments :
Post a Comment