Perform a KPSS Test With Non-Stationary Data
# Load necessary libraries
library(tseries) # For KPSS test
library(ggplot2) # For plotting
# Generate non-stationary data with a trend
set.seed(123)
trend <- 0.05 * (1:100) # Linear trend
non_stationary_data <- trend + rnorm(100) # Add noise
# Create a data frame for plotting
non_stationary_df <- data.frame(Time = 1:100, Value = non_stationary_data)n
# Perform KPSS test for trend stationarity
kpss_test_non_stationary <- kpss.test(non_stationary_data, null = "Trend")
# Output the KPSS test result
kpss_test_non_stationary
Output:
KPSS Test for Trend Stationarity
data: non_stationary_data
KPSS Trend = 0.059139, Truncation lag parameter = 4, p-value = 0.1
Plot the non-stationary data
# Plot the non-stationary data
ggplot(non_stationary_df, aes(x = Time, y = Value)) +
geom_line() +
geom_smooth(method = "loess", se = FALSE, color = "red") +
labs(title = "Non-Stationary Data", x = "Time", y = "Value") +
theme_minimal()
Output:
Generates non-stationary data by adding a linear trend (0.05 * (1:100)) to 100 random numbers from a normal distribution.
- Represents a dataset with a noticeable trend or varying variance.
- Creates a data frame with two columns: Time (1 to 100) and Value (the generated non-stationary data).
- Creates a line plot with Time on the x-axis and Value on the y-axis using ggplot2.
- Adds a smooth line (geom_smooth) with loess method to illustrate the upward trend.
- Uses minimalistic labels and theme for clarity.
- The plot shows a clear upward trend, indicating non-stationarity, with consistent increase in the data over time.
How to Perform a KPSS Test in R
In this article, we will discuss What is KPSS Test and how to perform the KPSS Test in R Programming Language.