1

assume, that I've an xts Format like this:

foo 

2000-01-01   2.6
2000-02-01   4.0
2000-03-01   2.6
2000-04-01   1.0
2000-05-01   2.4
...
...
2012-12-01   3.2

Now, I want transform my xts format to an ts series.

With the use of

foo_ts<-ts(foo, freq=12, start=index(foo)[1])

I'm loosing the date Format and get just numerical values instead of the years.

The results should look like this:

      Jan  Feb  Mar  Apr  May  Jun  Jul  Aug  Sep  Oct  Nov  Dec
2000  2.6  4.0  2.6  1.0  2.4
2001 
2002 
2003 
2004

I dont want to set it manually wit c(2000,1). Im searching for a automatically way to deal with the problem.

M--
  • 25,431
  • 8
  • 61
  • 93
Leo96
  • 489
  • 3
  • 12

1 Answers1

1

This is something that needs to be fixed in xts, but here's a work-around:

# first, some sample 'foo' data
foo <- as.xts(sunspot.month)["2000/2012"]
# Now convert to 'ts' via zooreg()
foo_ts <- as.ts(as.zooreg(foo))
foo_ts
#        Jan   Feb   Mar   Apr   May   Jun   Jul   Aug   Sep   Oct   Nov   Dec
# 2000  90.1 112.9 138.5 125.5 121.6 124.9 170.1 130.5 109.7  99.4 106.8 104.4
# 2001  95.6  80.6 113.5 107.7  96.6 134.0  81.8 106.4 150.7 125.5 106.5 132.2
# 2002 114.1 107.4  98.4 120.7 120.8  88.3  99.6 116.4 109.6  97.5  95.5  80.8
# 2003  79.7  46.0  61.1  60.0  54.6  77.4  83.3  72.7  48.7  65.5  67.3  46.5
# 2004  37.3  45.8  49.1  39.3  41.5  43.2  51.1  40.9  27.7  48.0  43.5  17.9
# 2005  31.3  29.2  24.5  24.2  42.7  39.3  40.1  36.4  21.9   8.7  18.0  41.1
# 2006  15.3   4.9  10.6  30.2  22.3  13.9  12.2  12.9  14.4  10.5  21.4  13.6
# 2007  16.8  10.7   4.5   3.4  11.7  12.1   9.7   6.0   2.4   0.9   1.7  10.1
# 2008   3.3   2.1   9.3   2.9   3.2   3.4   0.8   0.5   1.1   2.9   4.1   0.8
# 2009   1.3   1.4   0.7   0.8   2.9   2.9   3.2   0.0   4.3   4.8   4.1  10.8
# 2010  13.2  18.8  15.4   8.0   8.7  13.6  16.1  19.6  25.2  23.5  21.5  14.4
# 2011  18.8  29.6  55.8  54.4  41.6  37.0  43.8  50.6  78.0  88.0  96.7  73.0
# 2012  58.3  32.9  64.3  55.2  69.0  64.5  66.5  63.0  61.4  53.3  61.8  40.8
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
  • With your example, it works perfecty. But with my dataset the results are totally wrong. The frequency, start and end Points are not detected. The resulting ts format contains a lot of NA's and has something about 9000 rows, while my xts has 152 rows. The date Format of my xts is like above "2000-02-01", yours is "Feb 2000". Maybe thats the problem. Is there a way to do it with my date format ? – Leo96 Mar 19 '18 at 09:03
  • @Leo96: It would be easiest if you could edit your question to include a [reproducible example](https://stackoverflow.com/q/5963269/271616) that includes your data. You might try: `index(foo) <- as.yearmon(index(foo))`. – Joshua Ulrich Mar 19 '18 at 09:36