I download some rates from FRED, how I can filter the index date in order to keep only the dates after '2010' ?
Asked
Active
Viewed 2,247 times
-2
-
Can you show the `dput` of example – akrun Apr 15 '21 at 23:14
-
My question is general. I am just wondering if there is a way to filter an index column in R. – pRo Apr 15 '21 at 23:16
-
1Depends on the structure of the data – akrun Apr 15 '21 at 23:17
-
Maybe `yourobj[year(index(yourobj)) >= 2010]` – akrun Apr 15 '21 at 23:18
-
For example in this case is an 'xts' 'zoo' . – pRo Apr 15 '21 at 23:20
-
then the above code should work – akrun Apr 15 '21 at 23:20
2 Answers
6
xts accepts / notation as shown below:
library(quantmod)
getSymbols("DGS3MO", src = "FRED") # generate test data
DGS3MO["2010/"]
## DGS3MO
## 2010-01-01 NA
## 2010-01-04 0.08
## 2010-01-05 0.07
## 2010-01-06 0.06
## 2010-01-07 0.05
## 2010-01-08 0.05
## ...snip...
Alternately, xts has a window method:
window(DGS3MO, start = "2010-01-01")
## DGS3MO
## 2010-01-01 NA
## 2010-01-04 0.08
## 2010-01-05 0.07
## 2010-01-06 0.06
## 2010-01-07 0.05
## 2010-01-08 0.05
## ...snip...

G. Grothendieck
- 254,981
- 17
- 203
- 341
0
It it is an xts
object, then we extract the year
from index to create a logical vector for subsetting
library(xts)
xt1[lubridate::year(index(xt1)) >= 2010]
Or use subset
with %>%
library(dplyr)
xt1 %>%
subset(year(index(.))>= 2010)
data
set.seed(24)
xt1 <- xts(rnorm(50), order.by = seq(as.Date('2009-01-01'),
length.out = 50, by = '1 month'))

akrun
- 874,273
- 37
- 540
- 662