Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
984 views
in Technique[技术] by (71.8m points)

r - How can I change XTS to data.frame and keep Index?

I have an XTS timeseries in R of the following format and am trying to do some processing, subsetting and re-arranging before exporting as a CSV for work in another program.

head(master_1)
                   S_1
2010-03-03 00:00:00 2.8520
2010-03-03 00:30:00 2.6945
2010-03-03 01:00:00 2.5685
2010-03-03 01:30:00 2.3800
2010-03-03 02:00:00 2.2225
2010-03-03 02:30:00 2.0650

and

str(master_1)
An ‘xts’ object from 2010-03-03 to 2010-05-25 08:30:00 containing:
  Data: num [1:4000, 1] 2.85 2.69 2.57 2.38 2.22 ...
 - attr(*, "dimnames")=List of 2
  ..$ : NULL
  ..$ : chr "S_1"
  Indexed by objects of class: [POSIXt,POSIXct] TZ: 
  Original class: 'zoo'  
  xts Attributes:  
List of 1
 $ dateFormat: chr "Date"

And I would like to convert this to a data.frame so I can manipulate it more easily and then export to another program. However, when I use test1 <- as.data.frame(master_1) the test1 does have the Index (i.e. the dates and times) visible,

head(test1)
                       S_1
2010-03-03 00:00:00 2.8520
2010-03-03 00:30:00 2.6945
2010-03-03 01:00:00 2.5685
2010-03-03 01:30:00 2.3800
2010-03-03 02:00:00 2.2225
2010-03-03 02:30:00 2.0650 

But the Index is not shown,

str(test1)
'data.frame': 4000 obs. of  1 variable:
 $ S_1: num  2.85 2.69 2.57 2.38 2.22 ...

And writing a csv write.csv(master_1, file="master_1.csv") does not include the time or date. Why is this, and how can I include the data/time data as a column, so it is used in other R commands and exported properly?

Thanks for any help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

That's because the dates are rownames in your data.frame. You need to make them a separate column.

Try this:

 data.frame(date=index(master_1), coredata(master_1))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...