在R中构建虚拟变量后lm回归失效的问题求助
Let's walk through the likely issues causing your regression to fail and fix them step by step:
1. Incorrect Factor Creation
Your current code for creating CNAME uses Combined.data[6], which returns a single-column data frame instead of a numeric vector. The factor() function requires an atomic vector as input, so this is a critical mistake that's probably breaking your model.
Fix:
Use double brackets ([[ ]]) or comma indexing to extract the column as a vector, then add the factor to your finalresults dataset (since that's what your regression uses):
# Extract the 6th column as a vector and convert to factor CNAME <- factor(Combined.data[[6]], levels = 1:20, labels = c("AUSTRIA", "BELGIUM", "DENMARK", "FINLAND", "FRANCE", "GERMANY", "IRELAND", "ISLE OF MAN", "ITALY", "LUXEMBOURG", "NETHERLANDS", "NORWAY", "POLAND", "PORTUGAL", "SPAIN", "SWEDEN", "SWITZERLAND", "TURKEY", "UNITED KINGDOM", "UNITED STATES")) # Add the factor to your regression dataset finalresults$CNAME <- CNAME
2. Duplicate Variable in Regression Formula
Your formula includes ROA twice:
Tax_Avoidance ~ ... + ROA + MTB + ROA + ...
This introduces perfect multicollinearity, which will either trigger an error or produce unreliable coefficient estimates.
Fix:
Remove one instance of ROA from the formula:
# Corrected regression formula results <- lm(Tax_Avoidance ~ ENVSCORE + CGVSCORE + SOCSCORE + ECNSCORE + Size + Leverage + ROA + MTB + RND + AUD + PPE + Intang + CDP + CHS + NET + CNAME, data = finalresults) summary(results)
Additional Troubleshooting Steps
If the regression still fails after fixing the above, check these common issues:
- Missing Values: Use
colSums(is.na(finalresults))to identify variables with missing data.lm()drops rows with NA values by default, but excessive missingness can leave too few observations to estimate the model. - Mismatched Factor Levels: Verify that the values in
Combined.data[[6]]are all within 1-20 withtable(Combined.data[[6]]). Any values outside this range will becomeNAinCNAME, which can break the regression. - No Variation in Factor: If all observations belong to a single country,
CNAMEhas no variability, andlm()will throw an error. Usetable(finalresults$CNAME)to confirm there are multiple countries represented.
内容的提问来源于stack exchange,提问作者VishJ

