Data Structure: XTS
# Loading the xts package and converting the sample_matrix data to an xts object
library(xts)
data(sample_matrix)
sample_xts <- as.xts(sample_matrix)
head(sample_xts)
Exercises Using sample_xts
Extract the data from January 3, 2007, to January 15, 2007, from the sample_xts
object.
Calculate the weekly average of each column in the sample_xts
object using the apply.weekly()
function.
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
Extract only the data from Fridays in the sample_xts
object. This will involve subsetting by day of the week.
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.
Calculate a 10-day rolling mean for each column in sample_xts
.
Aggregate the data by month and calculate the sum of each column using apply.monthly()
.
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
)