I am reivewing following code from a online example
when run mod <- lm(y ~ rcs(x, knots = c(3, 7), degree = 3, intercept = TRUE), data = data), an error message comes up and says function rcs is not available, how to fix this problem?
# Load necessary libraries
library(splines) # For general spline functions
library(ggplot2) # For plotting
# Example data (replace with your own)
set.seed(123)
x <- seq(0, 10, length.out = 50)
y <- 2 * x + 0.5 * x^2 + rnorm(50, 0, 0.5)
# Create a data frame
data <- data.frame(x = x, y = y)
# Fit a restricted cubic spline model
# - `x` is the independent variable
# - `y` is the dependent variable
# - `knots` specifies the location of the knots (breakpoints) in the spline
# - `degree` controls the degree of the polynomial (usually 3 for cubic splines)
# - `intercept` if `TRUE` includes an intercept term in the model
mod <- lm(y ~ rcs(x, knots = c(3, 7), degree = 3, intercept = TRUE), data = data)
# Get predicted values
# - `data` is a data frame with a new x-value to predict for
predicted_values <- predict(mod, newdata = data.frame(x = x))
# Plot the results
plot(data$x, data$y, col = "blue", pch = 16, main = "Restricted Cubic Spline", xlab = "x", ylab = "y")
lines(data$x, predicted_values, col = "red", lwd = 2)
legend("topright", legend = c("Data", "Model"), col = c("blue", "red"), lty = 1, pch = c(16, NA))
# Alternative using ggplot2
ggplot(data, aes(x = x, y = y)) +
geom_point(color = "blue") +
geom_line(aes(y = predicted_values), color = "red", linewidth = 1.2) +
ggtitle("Restricted Cubic Spline (ggplot2)") +
xlab("x") +
ylab("y")
# To visualize the knots
# - `knots` can be extracted from the `mod` object
knots <- attr(terms(mod), "factors")[[1]]
knots <- unique(knots[knots != 0])
# Plotting the knots
plot(data$x, data$y, col = "blue", pch = 16, main = "Restricted Cubic Spline with Knots", xlab = "x", ylab = "y")
lines(data$x, predicted_values, col = "red", lwd = 2)
points(data$x[knots], data$y[knots], col = "green", pch = 4, cex = 2)
legend("topright", legend = c("Data", "Model", "Knots"), col = c("blue", "red", "green"), lty = 1, pch = c(16, NA, 4))