###################################################################################################################### #Generate increasing variance ###################################################################################################################### #Defining the Sample Size and the increasing variance scale size <- 20 X <- seq(0,size,by=0.5) sigma <-seq(0.125,5,by=0.125) # Generating observations with increasing variance Y <- X + rnorm(length(X),0,sigma) Y <- Y + min(Y) + 1 fit <- lm(Y~X) ## Plot the original data and the fitted line plot(x=X,y=Y) lines(x=X,y=predict(fit),col="red") ## Plot the residual x predicted value to validate the hypothesis plot(x=predict(fit),y=residuals(fit)) lines(x=c(min(predict(fit)-0.5),size),y=c(0,max(residuals(fit))),col="blue") lines(x=c(min(predict(fit)-0.5),size),y=c(0,min(residuals(fit))),col="blue") ## Perform the normal Shapiro-Wilk test for the residuals shapiro.test(residuals(fit)) ## Perform breush-pagan test for hetereocedascity library(lmtest) bptest(fit) ## Perform white test for hetereocedascity library(bstats) white.test(fit) ###################################################################################################################### #Fixing the problem with a log transformation ###################################################################################################################### Ypr <- log(Y) fit <- lm(Ypr~X) ## Plot the original data and the fitted line plot(x=X,y=Ypr) lines(x=X,y=predict(fit),col="red") ## Plot the residual x predicted value to validate the hypothesis plot(x=predict(fit),y=residuals(fit)) ## Perform the normal Shapiro-Wilk test for the residuals shapiro.test(residuals(fit)) ###################################################################################################################### #Fixing the problem with a square-root transformation ###################################################################################################################### Yst <- sqrt(Y) fit <- lm(Yst~X) ## Plot the original data and the fitted line plot(x=X,y=Yst) lines(x=X,y=predict(fit),col="red") ## Plot the residual x predicted value to validate the hypothesis plot(x=predict(fit),y=residuals(fit)) ## Perform the normal Shapiro-Wilk test for the residuals shapiro.test(residuals(fit))