Data Structure: XTS
The dataset
Exercises Using sample_xts
1. Extract a Specific Date Range
2. Calculate Weekly Averages
3. Identify Missing Dates
Check if there are any missing dates in the sample_xts
object. If there are, fill them in by forward-filling the previous values.
Solution:
# Check for missing dates
missing_dates <- !all(seq(start(sample_xts), end(sample_xts), by = "days") %in% index(sample_xts))
if (missing_dates) {
# Fill missing dates with NA and then forward-fill
sample_xts <- merge(x = sample_xts,
y = zoo(, seq(start(sample_xts),
end(sample_xts),
by = "days")))
sample_xts <- na.locf(sample_xts)
}
sample_xts
4. Extract Data for a Specific Day of the Week
5. Merge
sample_xts
with a New Time Series
Create a new xts
object with the same date range as sample_xts
but with different data, and merge it with sample_xts
so that both time series are aligned by date.
6. Create a 10-Day Rolling Mean
7. Calculate Monthly Sum
8. Identify Highest and Lowest Values
Find the highest and lowest values for each column in sample_xts
, and determine the dates on which these values occurred.
Solution:
# Find the highest and lowest values for each column
highest_values <- apply(X = sample_xts, MARGIN = 2, FUN = max)
lowest_values <- apply(X = sample_xts, MARGIN = 2, FUN = min)
# Find the dates for highest and lowest values
highest_dates <- apply(X = sample_xts, MARGIN = 2, FUN = function(col){index(sample_xts)[which.max(col)]})
lowest_dates <- apply(X = sample_xts, MARGIN = 2, FUN = function(col){ index(sample_xts)[which.min(col)]})
list(
highest_values = highest_values,
highest_dates = highest_dates,
lowest_values = lowest_values,
lowest_dates = lowest_dates
)