In continuation to the earlier query as mentioned below
Regression with lagged time time series data in R
My objective is to extract the 4th coefficient of the regression model which are significant i.e p-value < 0.05
The general form of the model is
A ~ Lags(A, 1:2) + Lags(B, 1:2)
I have a data frame Deposits_2015Q2 having 10 columns and 24 rows. Stating below the first 6 rows of the data frame Deposits_2015Q2
Deposits_2015Q2
B1 B2 B3 B4 B5 B6 B7 B8 B9 B10
234174.8 807526.7 93198.03 83191.27 79443.31 79593.98 52686.17 34536.29 70645.93 132601.4
236352.8 804852.0 92187.96 81834.52 77953.43 78687.54 51993.71 36098.29 69301.58 132588.6
227331.2 751653.9 83174.36 80386.75 74743.49 73838.38 50211.90 32020.65 67010.77 126405.7
219533.7 735303.5 79304.15 76730.38 73645.53 73450.54 48976.98 28927.36 64938.26 122845.9
210172.2 704675.6 79827.54 75258.59 69907.54 71725.17 47578.75 28821.78 63474.15 118728.5
198614.2 677182.0 76796.17 72260.30 67320.08 68386.68 45167.51 29215.77 59916.35 114406.4
I am able to run the below codes without a loop to extract the 4th coefficient of the model
# Loading the library
library(dyn)
# Performing Dynamic Regression and storing the results in fm
lag <- stats::lag
# Running the regression without loop
fm <- dyn$lm(B1 ~ lag(B1, -(1:2)) + lag(B10, -(1:2)), zoo(Deposits_15Q2_21Q1))
model_summary <- summary(fm)
model_summary
# Extracting the 4th coefficient
Beta <- model_summary$coefficients[5,1]
Beta
# Extracting the p-value of the 4th coefficient
Beta_p_value <- model_summary$coefficients[5,4]
Beta_p_value
My objective is to create a 10 x 10 matrix where I will store the value of the 4th coefficient of the model which is significant. The model will run w.r.t each column. I am unable to execute the below code
# Matrix to store the p-values
p=matrix(rep(0,10*10),nrow=10,ncol=10)
# Matrix to store the 4th coefficient values of the model
K=matrix(rep(0,10*10),nrow=10,ncol=10)
# Binding the data in the data set
Deposits=rbind(Deposits_2015Q2$B1,Deposits_2015Q2$B2,Deposits_2015Q2$B3,Deposits_2015Q2$B4,Deposits_2015Q2$B5,Deposits_2015Q2$B6,Deposits_2015Q2$B7,Deposits_2015Q2$B8,Deposits_2015Q2$B9,Deposits_2015Q2$B10)
Deposits
# Converting dataframe into time series
B = zoo(Deposits)
for (i in 1:10){
for (j in 1:10){
if (j!=i){
fm=dyn$lm(B[i] ~ lag(B[i], -(1:2)) + lag(B[j], -(1:2)))
p[i,j]=summary(fm)$coefficients[5,4]
}
else{
p[i,j]=0
}
}
}
for (i in 1:10){
for (j in 1:10){
if (p[i,j]>0.05){
K[i,j]=0
}
else {
K[i,j]=summary(fm)$coefficients[5,1]
}
}
}
# Converting the Matrix K into data frame
dataf <- as.data.frame(K)
The error message that I am getting is
Error in model.frame.default(formula = dyn(B[i] ~ lag(B[i], -(1:2)) + :
variable lengths differ (found for 'lag(B[i], -(1:2))')