How to make a subset in a zoo-type series choosing certain years or months?

Asked

Viewed 33 times

2

I have the following series:

library(zoo)

zoo_serie <- zoo(1:length(seq.Date(as.Date("1991-12-01"),as.Date("1998-12-31"),'day')),seq.Date(as.Date("1991-12-01"),as.Date("1998-12-31"),'day'))

I want to do a subset for the years 1991, 1995 and 1997, as I do it in an agile way?

Currently I create a series of dates and then I index in the series, this does not become feasible for huge series.

zoo_serie[index(zoo_serie) %in% vetor_de_datas]

I wanted something like this:

zoo_serie[year(index(zoo_serie)) %in% c(1911,1995,1997)]

But it doesn’t work. In the same way I wanted for specific months, this way I still haven’t managed.

  • The function year package lubridate does just that. The package has more functions to extract months, days and other date information.

  • @Jorge-Mendes, put this as an answer.

1 answer

1


As indicated by @Jorge-Mendes in the comments, the lubridate package has several functions to easily work with dates and does exactly what you want. I will use a smaller example than yours to facilitate the visualization:

library(zoo)
library(lubridate)

datas <- as.Date(c("1991-03-23", "1992-05-28", "1994-03-07", "1995-11-14", "1996-07-23"))
zserie <- zoo(seq(length(datas)), datas)

anos.sel <- c(1991, 1995, 1996)

zserie[year(index(zserie)) %in% anos.sel]
#> 1991-03-23 1995-11-14 1996-07-23
#>          1          4          5

zserie[month(index(zserie)) == 3]
#> 1991-03-23 1994-03-07
#>          1          3

You can also use regular expressions:

zserie[grep(paste(anos.sel, collapse = "|"), index(zserie))]
#> 1991-03-23 1995-11-14 1996-07-23
#>          1          4          5

zserie[grep("-03-", index(zserie))]
#> 1991-03-23 1994-03-07
#>          1          3
  • +1 for the extra of regular expressions

Browser other questions tagged

You are not signed in. Login or sign up in order to post.