如何通过 R 中的循环/函数合并大量 xts 对象?
我有一个循环,通过调用 API 来提取约 200 个单独的时间序列。
该循环将时间序列作为 xts 对象 (library(xts)
) 输出到带有后缀“.oc”的全局环境中。所以我有 200 个“ABC.oc”、“ABD.oc”等形式的 xts 对象。每个对象包含 1000 行数据。
我想做的是编写一个循环(或使用适当的函数)来获取所有“*.oc”对象并按列合并它们。 IE 最终会得到:
Date ABC.oc ABD.oc -> 200 columns like this
2011-01-01 10 10
2011-01-02 20 20
2011-01-03 30 30
2011-01-04 40 40
2011-01-05 50 50
对于一个简短的时间序列列表,只需写:
m <- merge(ABC.oc,ABD.oc,all=FALSE)
但显然这对于 200 个单独的对象来说是不切实际的,所以我想编写一个循环来将所有这些对象粉碎在一起,就像“合并”一样。
通过 for i in length(ls(pattern="*.oc")){ 很容易访问循环的变量,但无法弄清楚循环的其余部分。 我尝试过 cbind,但似乎无法正确执行。
非常感谢任何帮助
I have a loop that extracts ~200 individual timeseries by making calls to an API.
The loop outputs the timeseries as xts objects (library(xts)
) into the Global Environment with the suffix ".oc". So I have 200 xts objects of the form "ABC.oc", "ABD.oc" etc. Each object contains 1000 rows of data.
What I would like to do is write a loop (or use an appropriate function) that takes all the "*.oc" objects and merges them by column. IE would end up with:
Date ABC.oc ABD.oc -> 200 columns like this
2011-01-01 10 10
2011-01-02 20 20
2011-01-03 30 30
2011-01-04 40 40
2011-01-05 50 50
With a short list of timeseries, would just write:
m <- merge(ABC.oc,ABD.oc,all=FALSE)
But obviously this is not practical with 200 individual objects, so I'd like to write a loop to smash all these objects together like "merge" does.
Easy enough to access the variables for the loop via for i in length(ls(pattern="*.oc")){
but just cannot figure out the rest of the loop.
I've tried cbind, but can't seem to get it right.
Any help much appreciated
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这可以通过获取名称以
.oc
结尾的所有对象的字符向量,将它们放入列表中,然后通过do.call 调用
。merge
来实现如果您在从 API 接收 xts 对象时将它们加载到列表 (
objList
) 中,则使用此方法会更容易。那么你只需要do.call(merge, objList)
。This can be accomplished by getting a character vector of all the objects with names ending in
.oc
, putting them in a list, then callingmerge
viado.call
.Using this method would be easier if you loaded the xts objects into a list (
objList
) as you received them from the API. Then you would only needdo.call(merge, objList)
.像这样的循环应该可以工作。不过,首先初始化它总是一个好主意。
A loop like this should work. Always a good idea to initialise it first though.