[R] as.xts error

Joshua Ulrich josh.m.ulrich at gmail.com
Mon Dec 6 17:35:45 CET 2010


On Mon, Dec 6, 2010 at 5:57 AM, Gabor Grothendieck
<ggrothendieck at gmail.com> wrote:
> On Mon, Dec 6, 2010 at 6:52 AM, Ted Zeng (曾振兴) <zengzhenxing at gmail.com> wrote:
>>
>> Dear all,
>>
>> I am using the as.xts function to transfer a data frame to the xts
>>
>> The following is the code and result:
>>
>> a<-read.csv("price.csv")
>> a$Date<-as.POSIXct(a$Date)
>>
>> str(a)
>> 'data.frame':   15637 obs. of  2 variables:
>>  $ Date   : POSIXct, format: "2010-01-04 09:45:01" "2010-01-04 09:45:02"
>> "2010-01-04 09:45:03" ...
>>  $ bid_hsi: int  21850 21864 21864 21867 21859 21849 21849 21850 21854 21853
>> ...
>>
>> head(a)
>>
>>              Date bid_hsi
>> 1 2010-01-04 09:45:01   21850
>> 2 2010-01-04 09:45:02   21864
>> 3 2010-01-04 09:45:03   21864
>> 4 2010-01-04 09:45:04   21867
>> 5 2010-01-04 09:45:05   21859
>> 6 2010-01-04 09:45:06   21849
>>
>> p<-as.xts(a)
>> Error in as.POSIXlt.character(x, tz, ...) :
>>  character string is not in a standard unambiguous format
>>
>> Please help me to use the function as.xts correctly.
>>
I recommend you use Gabor's solution, but I would like to expand on
what as.xts is doing.

as.xts.data.frame and as.xts.matrix attempt to coerce the object's
rownames into the index attribute, unless specified otherwise via
order.by.  You have a couple options:

a <- data.frame(Date=Sys.Date()+1:10,
  bid_hsi=trunc(21800+runif(10)*100))
# 1)
rownames(a) <- a$Date
p <- as.xts(a[,"bid_hsi",drop=FALSE])
# 2)
p <- as.xts(a[,"bid_hsi",drop=FALSE], order.by=a$Date)

Best,
--
Joshua Ulrich  |  FOSS Trading: www.fosstrading.com


>
>
> Try this (you may need to modify the read.zoo arguments depending on
> what the file looks like):
>
> library(xts)
> z <- read.zoo("price.csv", header = TRUE, sep = ",", tz = "")
> x <- as.xts(z)
>
>
> --
> Statistics & Software Consulting
> GKX Group, GKX Associates Inc.
> tel: 1-877-GKX-GROUP
> email: ggrothendieck at gmail.com
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list