Last active
December 19, 2020 02:54
-
-
Save audhiaprilliant/daae162c0a07146ae0456bb59001d21d to your computer and use it in GitHub Desktop.
Simulation of Autocorrelation in Linear Regression Model
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Function to conduct simulation | |
| generate_beta = function(ti, rho, repetition) { | |
| # Vector intercept and slope | |
| vector_intercept_auto = rep(x = 0, len = repetition) | |
| vector_slope_auto = rep(x = 0, len = repetition) | |
| vector_intercept_non = rep(x = 0, len = repetition) | |
| vector_slope_non = rep(x = 0, len = repetition) | |
| j = 1 | |
| while (j < (repetition + 1)) { | |
| t = 1:ti | |
| number_data = length(t) | |
| error_t = rnorm(n = number_data, mean = 0, sd = 1) | |
| # Create an empty vector for the Vt | |
| vector_vt = rep(x = 0, len = number_data) | |
| # Generate the vector Vt | |
| vector_vt[1] = rho * rnorm(n = 1, mean = 0, sd = 1) + error_t[1] | |
| for (i in 2:number_data) { | |
| vector_vt[i] = rho * vector_vt[i-1] + error_t[i] | |
| } | |
| # Generate vector Ut | |
| scalar_v = mean(vector_vt) | |
| vector_ut = vector_vt - scalar_v | |
| # Generate vector Yt and Zt | |
| vector_yt = 1 + 0.8 * t + vector_ut | |
| vector_zt = 1 + 0.8 * t + error_t | |
| # Regression with autocorrelation | |
| model_autocorrelation = lm(formula = vector_yt ~ t) | |
| vector_intercept_auto[j] = as.numeric(model_autocorrelation$coefficients[1]) | |
| vector_slope_auto[j] = as.numeric(model_autocorrelation$coefficients[2]) | |
| # Regression without autocorrelation | |
| model_nonautocorrelation = lm(formula = vector_zt ~ t) | |
| vector_intercept_non[j] = as.numeric(model_nonautocorrelation$coefficients[1]) | |
| vector_slope_non[j] = as.numeric(model_nonautocorrelation$coefficients[2]) | |
| # Index | |
| j = j + 1 | |
| } | |
| # Save the intercept and slope to the dataframe | |
| beta_coefficient = data.frame(rho, | |
| vector_intercept_non, | |
| vector_slope_non, | |
| vector_intercept_auto, | |
| vector_slope_auto) | |
| colnames(beta_coefficient) = c('Rho', | |
| 'interceptNonAutocorrelation', | |
| 'slopeNonAutocorrelation', | |
| 'interceptAutocorrelation', | |
| 'slopeAutocorrelation') | |
| return(beta_coefficient) | |
| } | |
| # Generate the simulation | |
| df = data.frame() | |
| for (rho in seq(-1,1,0.1)) { | |
| beta_coef = generate_beta(ti = 30, rho = rho, repetition = 1000) | |
| df = rbind(df, beta_coef) | |
| } | |
| # Print the result | |
| View(df) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment