0

Here we go againi, I am still banging my head against the wall on the above problem. I have a data.frame that I upload via csv which looks like:

X          SPY      VTI
01.02.2002 0.0000   0.0000
04.02.2002 -2.4578  -2.4167 
.....
31.12.2015 -1.003   -0.9685

where X is date and SPY and VTI are stock returns

I tried many things to convert to a time series. first I tried

spyvti$X <- as.Date(as.character(spyvti$X),format="%d.%m.%Y.")

and what I get is:

 X        SPY     VTI
 NA       0.0000    0.0000
 NA       -2.4856   -2.4167
 .....
 NA       -1.003   -0.9685

so it looks like it can't convert the first column, which is a factor, in an object of class(Date).

I tried also to detach the data.drame into 3 different vectors, converting first the date vector into character, which worked, then

date <- as.Date(date, format = "%d.%m.%Y.")
error in charToDate(x):
character string is not in a standard unambiguous format.

So I'd like to get some help with overcoming the Date problem, and I'd like to know if, when the date problem is over, creating a ts object as below is correct

 tsobject <- xts(date,spy)

where spy is a numeric.

Thanks a lot

Paolo

paolino
  • 11
  • 2

3 Answers3

0

Use the "lubridate" package. It makes conversion of dates super easy.

library(lubridate)
dmy(spyvti$x)
Jim
  • 36
  • 2
0

I am making this up from my mind. Hope it works. You can try the following:

  Yourdataframe$X<-strptime(as.character(Yourdataframe$X),format="%d.%m.%Y")
  Yourdataframe<-xts(Yourdataframe[,2:3],order.by=Yourdataframe[,1]
Dr. Jones
  • 141
  • 1
  • 10
0

Assuming your example data frame is named df you can convert it into a xts time series object like so:

library(xts)
xtsObject <- as.xts(df[,-1],order.by = as.Date(as.character(df[,1]), format = "%d.%m.%Y"))
hvollmeier
  • 2,956
  • 1
  • 12
  • 17