simplePiecewiseReg: Fit a Basic Piecewise Regression

Description Usage Arguments Value Examples

View source: R/utility_functions.R

Description

Given an indepdent and dependent variable, along with a vector of break points, fits a basic piecewise regression to the data.

Usage

1
simplePiecewiseReg(x, y, breaks, ...)

Arguments

x

the independent (predictor) variable.

y

the dependent variable.

breaks

a vector of break points (in the same scale as the independent variable).

...

additional parameters for the lm function.

Value

A list with the output from the lm function, a data frame with the dummy coding used to construct the piecewise regression, and x and y-axis values that can be used for plotting the estimated line segments.

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# Define generating parameters
beta = c( 1, 1, 1, -1 )
sigma = .5

# Define break point
breaks = 0

# Simulate data
x = runif( 100, -1, 1 ) # Predictor
# Define design matrix
X = matrix( 1, 100, 2 )
X[ x > breaks, 1] = 0; X[ x <= breaks, 2] = 0
X = cbind( X, X*x )
colnames( X ) = c( 'I1', 'I2', 'S1', 'S2' )
# Generate dependent variable
y = as.vector( X %*% cbind( beta ) )
y = y + rnorm( 100, 0, sigma )

# Fit piecewise regression
fit = simplePiecewiseReg( x, y, breaks )
summary( fit$lm )

Plot results
plot( x, y, pch = 19 )
lines( fit$xa, fit$ya )

rettopnivek/utilityf documentation built on March 1, 2021, 7:05 p.m.