Align series to first and last day of month
Sometimes you may not be able to use convenience classes like yearmon
to represent timestamps. This exercise will teach you how to manually align merged data to the timestamp representation you prefer.
First you merge the lower-frequency data with the aggregate data, then use na.locf()
to fill the NA
forward (or backward, using fromLast = TRUE
). Then you can subset the result using the index of the object with the representation you prefer.
Your workspace contains FEDFUNDS
, monthly_fedfunds
(the result of apply.monthly(DFF, mean)
), and merged_fedfunds
(the result of merge(FEDFUNDS, monthly_fedfunds)
where the monthly_fedfunds
index is a Date
). Note the NA
values in merged_fedfunds
.
This exercise is part of the course
Importing and Managing Financial Data in R
Exercise instructions
- Use
na.locf()
to fill theNA
values inmerged_fedfunds
. Assign the result tomerged_fedfunds_locf
. - Subset
merged_fedfunds_locf
byindex(monthly_fedfunds)
to create an xts object with timestamps at month-end. Name the resultaligned_last_day
. - Use the
fromLast
argument tona.locf()
to fill theNA
values with the next observation. Assign the result tomerged_fedfunds_locb
. - Subset
merged_fedfunds_locb
byindex(FEDFUNDS)
to create an xts object with timestamps on the first of the month. Name the resultaligned_first_day
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Fill NA forward
merged_fedfunds_locf <- ___(___)
# Extract index values containing last day of month
aligned_last_day <- merged_fedfunds_locf[___]
# Fill NA backward
merged_fedfunds_locb <- na.locf(___, fromLast = ___)
# Extract index values containing first day of month
aligned_first_day <- merged_fedfunds_locb[___]