###---------------------------------------------------------------------------- ### Dummy for piecewise regression ###---------------------------------------------------------------------------- n1 = 100 n2 = 70 x1 = 1:100 x2 = 101:170 y1 = 1.2 + 1*x1 + rnorm(n1, 0, 10) y2 = 1 + 5*(x2-80) + rnorm(n2, 0, 10) y = c(y1, y2) x = c(x1, x2) D = as.numeric(x>100) NEWX = (x-100)*D lmout = lm(y~x+NEWX) summary(lmout) ## Plot the fitted line plot(x, y, pch = 20) points(x, lmout$fitted.values, type = "l", col = "red", lwd = 2) ###---------------------------------------------------------------------------- ### 8.26 Multiple Regression ###---------------------------------------------------------------------------- ## Read the data CableData <- read.table("Table_8_10.csv", header = TRUE) ## Make a linear regression CableLM <- lm(Y~X2+X3+X4+X5+X6, data = CableData) # With intercept CableLMNoInt <- lm(Y~0+X2+X3+X4+X5+X6, data = CableData) # Without intercept ## Summarize the models summary(CableLM) summary(CableLMNoInt) ## See what are available in the regression object names(CableLM) CableLM$fitted.values # Y Hat CableLM$residuals # Residuals ## Predictions predict(CableLM, se.fit = TRUE) #same as CableLM$fitted.values but also show #the standard error for the predictions ## The coefficients coef(CableLM) ## Variance covariance matrix for coefficients vcov(CableLM) ## Prediction with new values predict(CableLM, newdata = CableData[1:6, ], se.fit = TRUE) ## Plot the model plot(CableLM) ## Histogram of the residuals hist(CableLM$residuals) ###---------------------------------------------------------------------------- ### 9.22 Regression with dummies ###---------------------------------------------------------------------------- ## Read the data SalesData <- read.table("Table_9_3.csv", header = TRUE) ## Create dummies, ## Seasonal data, n <- nrow(SalesData) D2 <- as.numeric(((1:n)%%4) == 2) # Check if from quarter II D3 <- as.numeric(((1:n)%%4) == 3) # Check if from quarter III D4 <- as.numeric(((1:n)%%4) == 0) # Check if from quarter IV SalesDataWithDummies <- cbind(SalesData, D2, D3, D4) DISHLM <- lm(DISH~D2+D3+D4, data = SalesDataWithDummies) FRIGLM <- lm(FRIG~D2+D3+D4, data = SalesDataWithDummies) summary(DISHLM) summary(FRIGLM) ## Regression with dummies is exactly the same as the usual regression