[R] How to combine Date and time in one column

Gabor Grothendieck ggrothendieck at gmail.com
Mon Nov 22 13:32:11 CET 2010


On Mon, Nov 22, 2010 at 2:24 AM, rnick <nikos.rachmanis at gmail.com> wrote:
>
> Hello everyone,
>
> I am trying to built an xts object and i have run into some problems on the
> data handling. I would really appreciate if someone could help me with the
> following:
>
> 1) I have a OHLC dataset with Time and date in different columns. How could
> i combine date and time in one column in order to pass on the new column to
> xts? I have use cbind and data.frame before but i did not manage to yield
> any good results as the formating of the file changes.
>
> Date            Time           O                H               L               C
> 1/2/2005        17:05          1.3546   1.3553  1.3546  1.35495
> 1/2/2005        17:10          1.3553   1.3556  1.3549  1.35525
> 1/2/2005        17:15          1.3556   1.35565 1.35515 1.3553
> 1/2/2005        17:25          1.355            1.3556  1.355           1.3555
> 1/2/2005        17:30          1.3556   1.3564  1.35535 1.3563
>
> 2) It is not clear to me what is the best way to construct the .xts object?
> Should i use only the Date&time to index or should i also combine it with
> the rest of the variables?
>

Use read.zoo and then as.xts to convert it to xts.   The following
shows it for chron date/times.  Replace textConnection(Lines) with
"myfile.dat" to read it from that file.   You can replace the FUN=
part with a conversion to any date/time class supported by xts.  Here
we show it for chron.  In the example below we are assuming that the
date format is month/day/year. See R News 4/1.

Lines <- "Date Time O H L C
1/2/2005 17:05 1.3546 1.3553 1.3546 1.35495
1/2/2005 17:10 1.3553 1.3556 1.3549 1.35525
1/2/2005 17:15 1.3556 1.35565 1.35515 1.3553
1/2/2005 17:25 1.355 1.3556 1.355 1.3555
1/2/2005 17:30 1.3556 1.3564 1.35535 1.3563"

library(xts) # this also pulls in zoo and its read.zoo
library(chron)

z <- read.zoo(textConnection(Lines), header = TRUE, index = list(1, 2),
	FUN = function(d, t) as.chron(paste(as.Date(chron(d)), t)))

x <- as.xts(z)


-- 
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com



More information about the R-help mailing list