含NA值的VAR模型执行报错处理方法问询(含多变量场景)
Great question — the vars package's VAR() function actually supports the same na.action parameter you're used to from lm(), so you don't need to modify your original data at all. Here's how to fix both your single-variable and multi-variable cases:
1. Single-Variable Case (Your v1 Vector)
Your original code fails because v1 starts with 4 NA values. Just add the na.action = na.omit argument to automatically drop those NA-containing observations during model estimation (without altering your original v1 vector):
library(vars) # Estimate VAR with automatic NA removal var.1 <- VAR(v1, p = 2, type = "none", na.action = na.omit)
Under the hood, this uses na.omit(v1) to create a cleaned version of your data just for the model, leaving your original vector untouched.
2. Multi-Variable Data Frame (Your var_matrix)
For your data frame where only v1 has NA values, the same approach works. na.action = na.omit will remove any rows that contain NA values (in this case, the first 4 rows) and estimate the VAR on the remaining complete observations:
# Your multi-variable data frame var_matrix <- structure(list(v1 = c(NA, NA, NA, NA, -519855.925178533, -247538.14528678, -603507.985623476, -873678.460926243, -581594.87915122, -528456.780577186, -391430.52605186, -474061.20379637, -508746.68301063, -551253.229288009, -745956.210848871, -395334.57220861, -660651.906124351, -650674.495666517, -554439.238524367, -603026.320962454, -636262.533420218, -627516.645815887, -563570.430739122, -669025.909101723), v2 = c(-0.0841196771292363, -0.0865340657541444, -0.0789115051898024, -0.0413000876182887, -0.0519876095584632, -0.0338526938134585, -0.017419320251823, -0.0227395626637981, 0.00747555221948315, 0.00490634907033316, 0.0128726833736623, 0.00562952075313272, 0.000474645930122142, 0.00414460086365942, -0.0236739434453794, 0.00536228308513542, -0.00400212632914532, -0.00956327795968659, 0.0121819821940745, -0.00875514068065508, 0.00407005673233352, 0.0158764252138643, 0.0129726728437638, 0.015)), class = "data.frame", row.names = c(NA, -24L)) # Estimate VAR on cleaned data (no NA rows) var_multi <- VAR(var_matrix, p = 2, type = "none", na.action = na.omit)
Quick Notes:
- The
na.action = na.omitargument behaves exactly like it does inlm(): it drops any observations with missing values, but only for the model estimation — your original data remains unchanged. - If you want to inspect the cleaned data before fitting the model, you can run
na.omit(v1)orna.omit(var_matrix)separately. - With 20 remaining observations after removing NAs, you have enough data to fit a VAR with
p=2(VAR models require at leastp+1observations, which you easily meet here).
内容的提问来源于stack exchange,提问作者adrCoder

