Date information disappears when save to CSV

江枫思渺然 提交于 2019-12-30 07:13:05

问题


I am trying to pull some data in from the internet and then export it to a CSV file, but I am loosing my date information in the CSV file. I can't figure out why. I'm new to R so please keep responses simple. Here is my code:

Library(quantmod)
getSymbols("SPY", from = "2012-01-01", to = "2012-12-31")
write.csv(SPY, "C:/SPY.csv")

回答1:


as SPY is a xts/zoo object this will do the trick:

replace:

write.csv(SPY, "C:/SPY.csv")

with

write.zoo(SPY,"C:/SPY.csv",index.name="Date",sep=",")



回答2:


Try:

write.csv(SPY, file= "SPY.csv", row.names = index(SPY))



回答3:


Are you sure that the date information is being lost? If you are using MS-Excel to open the .CSV, it may be that Excel is munging your data.




回答4:


If you do str(SPY) you get to see the inner structure of your xts object. The dates are in the index, not in the main data.

I use these three lines to save an xts object as a csv file:

#Convert to a data frame so it can be written to disk
d=as.data.frame(SPY)
d=cbind(datestamp=rownames(d),d)
write.csv(d,file="SPY.csv",row.names=F)


来源:https://stackoverflow.com/questions/15796499/date-information-disappears-when-save-to-csv

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