# How to extract a time series subset in R?

How to extract a time series subset in R?, This article will teach you how to use R’s window function to extract a time series subset.

data <- data.frame(dates = seq(as.Date("2022-01-01"), by = "day", length.out = 10), values = 1:10)

Now we can view the data frame

data

dates values 1 2022-01-01 1 2 2022-01-02 2 3 2022-01-03 3 4 2022-01-04 4 5 2022-01-05 5 6 2022-01-06 6 7 2022-01-07 7 8 2022-01-08 8 9 2022-01-09 9 10 2022-01-10 10

According to the preceding RStudio console output, you can see that the example data is a data frame with ten rows and two columns.

Dates are present in the first variable, while their corresponding numerical values are present in the second.

The xts package can then be used to turn our data frame into a time series object.

We also need to install and load xts in order to use the functions of the xts package.

install.packages("xts") library("xts")

Next, as illustrated below, we can use the xts function to build a time series object.

ts <- xts(data$values, data$dates) ts

[,1] 2022-01-01 1 2022-01-02 2 2022-01-03 3 2022-01-04 4 2022-01-05 5 2022-01-06 6 2022-01-07 7 2022-01-08 8 2022-01-09 9 2022-01-10 10

There are ten dates and ten associated values in our time series data.

### Example: Use the window to extract the subset from the time series object () Function

This section provides an example of how to choose a specific subset of a time series object that falls within a specified time window.

We can use the window function for this task as demonstrated below.

ts_subset <- window(ts, start = "2022-01-05", end = "2022-01-09") ts_subset

[,1] 2022-01-05 5 2022-01-06 6 2022-01-07 7 2022-01-08 8 2022-01-09 9

As you can see from the previous output, we have given you a time series subset of our data that spans two particular dates.

Time Series data analysis Guide