能否仅定义一次完整回归模型,逐个删除回归变量并生成Stargazer表格?
Great question! You can absolutely write your full two-way fixed effects model once, then generate nested models by dropping variables one at a time without repeating redundant code. The key is using R's update() function to modify your base model, then passing all models to stargazer for a clean, professional table.
Step 1: Set Up Your Environment and Data
First, load the required packages and prepare the airquality dataset (we’ll handle missing values and structure it as panel data for fixed effects):
# Load necessary packages library(plm) library(stargazer) # Load and clean the airquality data data(airquality) aq_clean <- na.omit(airquality) # Convert to panel data frame (Month = cross-section, Day = time dimension) aq_panel <- pdata.frame(aq_clean, index = c("Month", "Day"))
Step 2: Fit the Full Base Model
Write your complete two-way fixed effects within model once—this will be your starting point for all nested models:
# Full model: Ozone ~ Solar.R + Wind + Temp (with Month and Day fixed effects) full_model <- plm( formula = Ozone ~ Solar.R + Wind + Temp, data = aq_panel, model = "within", effect = "twoways" # Enables both cross-section and time fixed effects )
Step 3: Generate Nested Models by Dropping Variables
Use update() to create new models by removing variables from the full model. This avoids rewriting the entire model specification every time:
# Model 2: Drop Solar.R from the full model no_solar <- update(full_model, . ~ . - Solar.R) # Model 3: Drop Wind from Model 2 (leaving only Temp as a covariate) no_solar_wind <- update(no_solar, . ~ . - Wind)
Alternatively, if you want to drop multiple variables directly from the full model, you can do:
no_solar_wind <- update(full_model, . ~ . - Solar.R - Wind)
Step 4: Create a Clean Stargazer Table
Pass all your models to stargazer to generate a polished table. Customize labels, stats, and formatting to your needs:
stargazer( full_model, no_solar, no_solar_wind, type = "text", # Use "html" or "latex" for file output title = "Nested Two-Way Fixed Effects Models", column.labels = c("Full Model", "No Solar.R", "No Solar.R/Wind"), keep.stat = c("n", "adj.rsq"), # Keep sample size and adjusted R-squared omit.stat = "f", # Optional: Omit F-stat if not needed notes = "Two-way fixed effects (Month and Day) included in all models" )
Key Benefits
- No code duplication: You only define the core model structure once, reducing repetition.
- Consistency: All models use the same panel setup and fixed effects specification, minimizing errors.
- Efficiency: Adding or removing variables takes just one line with
update().
The output table will neatly display coefficients, standard errors, and key stats for each nested model, making it easy to compare how dropping variables affects your results.
内容的提问来源于stack exchange,提问作者BeSeLuFri

