Solved Exercises on Introduction to Time Series in R

Master basic R concepts for time series: data structures, time-based analysis, and fundamental operations through these 5 detailed exercises.

Solution: Exercises 1 to 3
1 Creating Time Series
Exercise 1
In R, create a simple time series for 5 days of temperature: 70, 72, 75, 73, 71 degrees. How do you store this in R?
Definition:

Time Series: A collection of data points indexed in time order

R Method:
  1. Create a vector of values
  2. Use the ts() function to create a time series object
  3. Specify the start time and frequency
Code
ts(data, start, freq)
Values
70, 72, 75, 73, 71
ts(temp, start=1, freq=1)
Step 1: Create the data vector
temp <- c(70, 72, 75, 73, 71)
Step 2: Create the time series object
temp_ts <- ts(temp, start=1, frequency=1)
Step 3: View the time series
print(temp_ts)
Time Series Object Created
Final answer:
temp <- c(70, 72, 75, 73, 71)
temp_ts <- ts(temp, start=1, frequency=1)
print(temp_ts)
Applied rules:

• Vector Creation: Use c() to combine values

• Time Series: Use ts() function to create time series object

• Parameters: Specify start time and frequency

Key Note: The ts() function creates a special R object for time series analysis.
Common Mistake: Don't forget to assign the result to a variable.
2 Viewing Time Series
Exercise 2
How do you view the time series you created? Show the R commands to display it.
Definition:

Time Series Display: Showing the values with their associated time indices

Function
plot()
Display
print()
summary()
Step 1: Print the time series
print(temp_ts)
Step 2: Plot the time series
plot(temp_ts)
Step 3: Get summary statistics
summary(temp_ts)
Time Series Displayed Successfully
Final answer:
print(temp_ts) # Shows values with time indices
plot(temp_ts) # Creates a line plot
summary(temp_ts) # Shows basic statistics
Applied rules:

• Print Function: Displays the raw time series data

• Plot Function: Creates a visual representation

• Summary Function: Provides basic statistics

Key Note: The plot() function automatically creates a time series plot with proper time axes.
Important: Always check your data after creating it.
3 Time Series Operations
Exercise 3
How do you calculate the average temperature from your time series? Show the R command.
Definition:

Time Series Operations: Mathematical functions applied to time series data

Mean
mean()
Max
max()
Min
min()
Step 1: Calculate the mean
avg_temp <- mean(temp_ts)
Step 2: Display the result
print(avg_temp)
Step 3: Other useful operations
max_temp <- max(temp_ts)
min_temp <- min(temp_ts)
range_temp <- range(temp_ts)
Step 4: Verify the calculation
# (70 + 72 + 75 + 73 + 71) / 5 = 72.2
Average Temperature = 72.2°F
Final answer:
avg_temp <- mean(temp_ts)
print(avg_temp)
Applied rules:

• Mean Function: Calculates the average of time series values

• Statistical Functions: Work directly on time series objects

• Arithmetic Operations: Can be applied to time series

Key Note: Most R functions work directly on time series objects.
Important: Time series objects preserve their temporal structure during operations.
R Time Series Fundamentals
ts(data, start, freq)
Time Series Creation
Function 1
ts()
Create Time Series
Function 2
plot()
Visualize
Function 3
mean()
Calculate Average
Key definitions:

Time Series: Data points collected at regular time intervals

R Object: Special data structure in R programming language

ts Function: Creates time series objects in R

Frequency: Number of observations per unit time

R Time Series methods:
  1. Create: Use ts() to make time series objects
  2. View: Use print(), plot(), or summary()
  3. Analyze: Apply statistical functions
  4. Transform: Modify or process the data
Common errors: Forgetting to load R packages, incorrect data types, misunderstanding time frequencies.
Key insight: R treats time series as special objects that preserve temporal relationships.
Solution: Exercises 4 to 5
4 Time Series Modification
Exercise 4
How do you add a new temperature value to your existing time series? Show how to add a 6th day with 74°F.
Definition:

Time Series Modification: Adding or changing values in a time series

Concatenate
c(ts, new_value)
Update
ts[index] = value
Result
Extended TS
Step 1: Create new value
new_temp <- 74
Step 2: Concatenate with existing series
extended_ts <- c(temp_ts, new_temp)
Step 3: Alternatively, update specific index
temp_ts[6] <- 74 # If space exists
Step 4: Create new time series with updated parameters
temp_extended <- ts(c(70, 72, 75, 73, 71, 74), start=1, frequency=1)
Step 5: Verify the result
print(temp_extended)
Extended Time Series Created
Final answer:
original_values <- c(70, 72, 75, 73, 71)
new_values <- c(original_values, 74)
extended_ts <- ts(new_values, start=1, frequency=1)
Applied rules:

• Concatenation: Use c() to combine vectors

• Index Assignment: Access specific positions with brackets

• Object Recreation: Create new time series with updated data

Key Note: Time series objects have fixed length, so concatenation creates a new object.
Important: Update the time series parameters when extending the series.
5 Time Series Analysis
Exercise 5
How do you find which day had the highest temperature in your time series? Show the R commands.
Definition:

Time Series Analysis: Examining patterns and features in time-ordered data

Maximum
which.max()
Index
position
Result
day number
Step 1: Find the position of maximum value
max_pos <- which.max(temp_ts)
Step 2: Get the maximum value
max_value <- max(temp_ts)
Step 3: Display both results
cat("Highest temp:", max_value, "at position:", max_pos)
Step 4: Additional analysis functions
length(temp_ts) # Number of observations
start(temp_ts) # Start time
end(temp_ts) # End time
Step 5: Verify the result
# Day 3 had 75°F, which is the highest
Highest Temperature: Day 3 (75°F)
Final answer:
max_day <- which.max(temp_ts)
max_temp <- temp_ts[max_day]
print(paste("Day", max_day, "had highest temp:", max_temp))
Applied rules:

• which.max(): Returns the index of maximum value

• Indexing: Access values using brackets []

• Time Series Functions: R provides specialized functions for analysis

Key Note: which.max() returns the position, not the value itself.
Important: Time series positions correspond to time periods in order.
R Time Series Analysis Methods
ts(data, start, freq)
Time Series Creation Formula
Key definitions:

Time Series: Data points collected at regular time intervals

R Object: Special data structure in R programming language

ts Function: Creates time series objects in R

Frequency: Number of observations per unit time

Indexing: Accessing specific positions in the series

R Time Series analysis methods:
  1. Creation: Use ts() to make time series objects
  2. Visualization: Use plot() for time series graphs
  3. Descriptive: Apply mean(), max(), min(), summary()
  4. Analysis: Use which.max(), which.min(), diff(), lag()
Tip 1: Always specify start and frequency when creating time series.
Tip 2: Use plot() to visualize patterns and trends.
Tip 3: Check your data with summary() before analysis.
Tip 4: Time series preserve temporal order in all operations.
Common errors: Incorrect frequency settings, mismatched data lengths, improper indexing.
Memorization aids: Remember ts() for creation, plot() for visualization, and which.max() for location of extremes.
Essential R time series functions:

• ts(): Create time series objects

• plot(): Visualize time series

• mean(), max(), min(): Descriptive statistics

• which.max(), which.min(): Locate extreme values

• start(), end(), frequency(): Access time attributes

Questions & Answers

Question: What does the 'frequency' parameter mean in the ts() function?

Answer: The frequency parameter tells R how many observations there are per unit of time:

  • frequency=1: One observation per time unit (yearly data)
  • frequency=4: Quarterly data (4 per year)
  • frequency=12: Monthly data (12 per year)
  • frequency=7: Weekly data (7 per week)

For our simple example with 5 days of temperature, we used frequency=1 because we're treating each day as a separate time unit.

The frequency helps R understand the time structure of your data!

Question: Can I plot multiple time series on the same graph in R?

Answer: Yes! You can plot multiple time series together:

  • First series: Use plot(ts1) to create the initial plot
  • Additional series: Use lines(ts2) to add to the same plot
  • Different colors: Specify col="color" parameter

Example:

plot(temp_ts, col="blue")
lines(humidity_ts, col="red")

This allows you to compare different time series visually!

Question: How do I import time series data from a file in R?

Answer: You can import time series data from various file formats:

  • CSV files: Use read.csv() to read tabular data
  • Create ts object: Convert imported data to time series
  • Specify date columns: Include time information

Example:

data <- read.csv("temperatures.csv")
temp_ts <- ts(data$temp, start=c(2023,1), frequency=365)

This imports daily temperature data from a CSV file!

Complete Summary: Introduction to Time Series in R

This comprehensive summary covers all essential R concepts for time series analysis for first grade students.

Key Definitions

Time Series: Data points collected at regular time intervals

R Object: Special data structure in R programming language

ts Function: Creates time series objects in R

Frequency: Number of observations per unit time

Indexing: Accessing specific positions in the series

Vector: A basic R data structure for storing sequences of values

Core Rules and Principles

Time Series Creation: Use ts() function with data, start, and frequency

Temporal Structure: Time series preserve chronological order

Statistical Functions: Most R functions work directly on time series objects

Data Integrity: Time series maintain their temporal relationships

Regular Intervals: Observations should be at consistent time periods

Indexing Rules: Use brackets [] to access specific time points

Step-by-Step Methods

Creating Time Series:

  1. Prepare your data as a numeric vector using c()
  2. Call ts() with your data, start time, and frequency
  3. Assign the result to a variable
  4. Verify the creation by printing or plotting

Time Series Analysis:

  1. Visualize with plot() to see patterns
  2. Calculate statistics with mean(), max(), min()
  3. Locate specific values with which.max(), which.min()
  4. Access individual points with indexing [ ]
Examples and Applications

Simple Examples:

temp <- c(70, 72, 75, 73, 71)
temp_ts <- ts(temp, start=1, frequency=1)

Advanced Examples:

monthly_sales <- ts(sales_data, start=c(2023,1), frequency=12)
weekly_temps <- ts(temps, start=c(2023,1), frequency=7)

Real-Life Applications:

• Daily temperature monitoring

• Stock price tracking

• Sales data analysis

• Website traffic patterns

Tips and Common Pitfalls

Helpful Tips:

• Always specify start and frequency when creating time series

• Use plot() to visualize your data before analysis

• Check data with summary() to identify issues

• Remember that R positions start at 1, not 0

Common Mistakes:

• Forgetting to specify frequency parameter

• Mixing different time frequencies in the same series

• Not checking for missing values before analysis

• Assuming time series behave like regular vectors in all contexts

Memory Aids:

• "ts() for time series creation"

• "plot() for visualization"

• "which.max() gives position, not value"

Key Takeaways

Essential Knowledge:

• R treats time series as special objects that preserve temporal structure

• The ts() function is the primary way to create time series in R

• Frequency parameter defines the time structure of your data

Skills to Master:

• Creating time series objects from raw data

• Visualizing time series with plots

• Applying statistical functions to time series

• Locating specific values within time series

Why This Matters:

• Time series analysis is fundamental for understanding temporal patterns

• R provides powerful tools for time-based data analysis

• These skills apply to many real-world datasets

• Foundation for more advanced time series modeling