You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在R中构建虚拟变量后lm回归失效的问题求助

Troubleshooting Your lm() Regression with Factor Dummy Variables

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 with table(Combined.data[[6]]). Any values outside this range will become NA in CNAME, which can break the regression.
  • No Variation in Factor: If all observations belong to a single country, CNAME has no variability, and lm() will throw an error. Use table(finalresults$CNAME) to confirm there are multiple countries represented.

内容的提问来源于stack exchange,提问作者VishJ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:57:34