Converting an XTS object to a data.frame [duplicate]

不羁岁月 提交于 2019-11-28 01:28:29

问题


Possible Duplicate:
How to create a variable of rownames?


Please run it in R:

require(quantmod)   
setSymbolLookup(SDB=list(name="000001.sz",src="yahoo"))   
getSymbols("SDB",from="2010-01-01",to="2010-02-01")   
sdb=as.data.frame(weeklyReturn(SDB))  
sdb    

What I get is:

           weekly.returns             
2010-01-08    -0.07830343          
2010-01-15    -0.05176991              
2010-01-22     0.07699487              
2010-01-29    -0.05979203         
2010-02-01    -0.02119816 

What I want to get is:

        date  weekly.returns                   
1 2010-01-08     -0.07830343           
2 2010-01-15     -0.05176991         
3 2010-01-22      0.07699487          
4 2010-01-29     -0.05979203            
5 2010-02-01     -0.02119816 

How can I do this?

Note that this is an XTS object, not a basic data.frame. After the conversion, I want the original rownames to appear as a new variable in the resulting data.frame.


回答1:


Ok. So, it's not exactly the same as your earlier question since this is an XTS object. Still, very easy to take care of:

data.frame(date = index(weeklyReturn(SDB)), 
           weeklyReturn(SDB), row.names=NULL)
#         date weekly.returns
# 1 2010-01-04    -0.03303426
# 2 2010-01-11    -0.04681569
# 3 2010-01-18    -0.05000000
# 4 2010-01-25     0.03353517
# 5 2010-02-01    -0.04281208

For help on what is being done here, view use ?indexClass to read the documentation for index in the XTS package.



来源:https://stackoverflow.com/questions/11429889/converting-an-xts-object-to-a-data-frame

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!