Ale*_*lec 6 functional-programming wolfram-mathematica date list
我有以下格式的日期和值列表:
{{{dateInfo1},value1},{{dateInfo2},value2},...,{{dateInfoN},valueN}}
Run Code Online (Sandbox Code Playgroud)
有一些实际的日期和价值观:
{{{1971, 1, 31, 0, 0, 0.}, 1.0118}, {{1971, 2, 28, 0, 0, 0}, 1.0075},
..., {{2010, 5, 31, 0, 0, 0.}, 1.0403}}
Run Code Online (Sandbox Code Playgroud)
对于那些好奇的人来说,它是从FRED数据库中提取的美国与CAD $值的列表.
我想简单地从值2中减去value1,然后创建一个包含以下形式的数据的新列表:
{{{dateInfo1},0},{{dateInfo2},change1},...,{{dateInfoN},changeN-1}}
Run Code Online (Sandbox Code Playgroud)
(更改1为value2-value1)
我知道必须有一个相对简单的方法来使用函数式编程,而不是使用索引变量和计数的Do或While以及所有那些废话.我想要实现的方法必须相对健壮,因为我会自动从具有相同格式但不同时间间隔的源中提取数据集.如果我不必指定ListPlot日期间隔(如果我从列表中剥离dateInfo会发生这种情况),那么重绘就会容易得多.
我熟悉文档中心和非编程Mathematica功能.我一直在学习使用Mathematica进行编程,并且真的希望将这种能力扩展到函数式编程中,但是发现这个主题的大部分资源有点太难了.我觉得自己正处于学习曲线中的那个驼峰,即将点击到位,但是现在我正在努力.至少如果你有一个很好的函数式编程源,我会非常乐意调查这些!任何帮助深表感谢!对不起,如果是TMI,但我相信很多人都有同样的感受.
You have a list of {date,value} pairs so if you Transpose that you'll have a list of two lists -- the first a list of dates and the second a list of corresponding values. You can then take the Differences of the values, Prepend 0, and then Transpose again to get back to a list of pairs.
In code,
data = {{{1971,1,31,0,0,0}, 1.0118},
{{1971,2,28,0,0,0}, 1.0075},
{{2010,5,31,0,0,0}, 1.0403}}
{dates, values} = Transpose[data];
diffs = Prepend[Differences[values], 0];
answer = Transpose[{dates, diffs}]
Run Code Online (Sandbox Code Playgroud)
which returns:
{{{1971,1,31,0,0,0}, 0},
{{1971,2,28,0,0,0}, -0.0043},
{{2010,5,31,0,0,0}, 0.0328}}
Run Code Online (Sandbox Code Playgroud)
To wrap that up into a single function, with thanks to Janus for the idea:
taildiffs[data_]:=
Transpose @ {#1, Prepend[Differences[#2], 0]}& @@ Transpose@data
Run Code Online (Sandbox Code Playgroud)
Note that the ... #1 ... #2 ... & construct is a pure function:
http://reference.wolfram.com/mathematica/ref/Function.html
The f@x syntax is simply shorthand for f[x].
Finally, f@@list is shorthand for Apply[f, list]:
http://reference.wolfram.com/mathematica/ref/Apply.html
所以上面定义的taildiffs只是一个简洁的(也许是神秘的)版本:
Apply[Transpose[Function[{x,y}, {x, Prepend[Differences[y],0]}], Transpose[data]]
Run Code Online (Sandbox Code Playgroud)