How to get years from a time series index when the

2019-06-14 07:13发布

I´d like to extract years from a time series index (the underlying time series is of monthly frequency). The reason I want to do it is creating a yearly axis, e.g.

plot(myts)
axis(1, at = year(time(myts)), labels = FALSE)
# note I know 'year()' does not work :)

because if I just plot it, R arbitrarily(?) creates a time axis. Often it's a two or even 5 year axis which makes is inappropriate sometimes.

tsp(myts) 
[1] 1966.000 1974.917   12.000

2条回答
干净又极端
2楼-- · 2019-06-14 07:20

I found an own solution. Maybe this helps someone else, too. Besides I think it's not overly smart... so I am looking forward to your suggestions.

 axis(1, at = start(time(myts))[1]:end(time(myts))[1], labels = TRUE)

EDIT: found a more elegant solution:

require(zoo)
x <- as.yearqtr("1991 Q1")
format.Date(x,"%Y")

according to @matty T pain it also works for ts (see comments).

查看更多
贼婆χ
3楼-- · 2019-06-14 07:36

I am not familiar with your data, but if it is a time series class (ts), then you can use the window function:

window(myts,start="*beginyear*",end="*endyear*")

If you cannot do that, maybe you can use some of the suggestions here:

http://r.789695.n4.nabble.com/Year-and-Month-extraction-from-Date-object-td904011.html

Matt

查看更多
登录 后发表回答