window Function in R (Example)
In this tutorial you’ll learn how to extract a time series subset using the window function in R programming.
The post is structured as follows:
If you want to know more about these content blocks, keep reading.
Example Data & Packages
The following data will be used as basement for this R programming tutorial:
my_data <- data.frame(dates = seq(as.Date("2023-01-01"), # Create example data frame by = "day", length.out = 10), values = 1:10) my_data # Print example data frame # dates values # 1 2023-01-01 1 # 2 2023-01-02 2 # 3 2023-01-03 3 # 4 2023-01-04 4 # 5 2023-01-05 5 # 6 2023-01-06 6 # 7 2023-01-07 7 # 8 2023-01-08 8 # 9 2023-01-09 9 # 10 2023-01-10 10
As you can see based on the previous RStudio console output, our example data is a data frame consisting of ten rows and two columns. The first variable contains dates and the second variable contains the corresponding numeric values.
Next, we can use the xts package to convert our data frame to a time series object.
To be able to use the functions of the xts package, we also have to install and load xts:
install.packages("xts") # Install xts package library("xts") # Load xts package
Next, we can apply the xts function to create a time series object as shown below:
my_ts <- xts(data$values, data$dates) # Convert data frame to time series my_ts # Print time series object # [,1] # 2023-01-01 1 # 2023-01-02 2 # 2023-01-03 3 # 2023-01-04 4 # 2023-01-05 5 # 2023-01-06 6 # 2023-01-07 7 # 2023-01-08 8 # 2023-01-09 9 # 2023-01-10 10
Our time series data contains ten dates and ten corresponding values.
Example: Extract Subset from Time Series Object Using window() Function
This section illustrates how to select a particular subset of a time series object that is within a certain range of dates.
For this task, we can apply the window function as shown below:
my_ts_subset <- window(my_ts, # Apply windows function start = "2023-01-03", end = "2023-01-08") my_ts_subset # Print time series subset # [,1] # 2023-01-03 3 # 2023-01-04 4 # 2023-01-05 5 # 2023-01-06 6 # 2023-01-07 7 # 2023-01-08 8
As you can see based on the previous output, we have returned a time series subset between two specific dates in our data.
Video, Further Resources & Summary
Do you need further explanations on the topics of this article? Then I recommend watching the following video on my YouTube channel. In the video, I show the examples of this tutorial.
The YouTube video will be added soon.
Furthermore, you might have a look at the related tutorials on https://statisticsglobe.com/. I have released several tutorials already.
- Convert Data Frame with Date Column to Time Series Object
- How to Create a Range of Dates
- as.Date Function in R
- Useful Commands in R
- Introduction to R
In summary: In this R tutorial you have learned how to apply the window function. In case you have additional questions, let me know in the comments below.
Statistics Globe Newsletter