【问题标题】:Variable lengths differ help, lm regression and weights, variables have the same number of rows可变长度不同帮助,lm回归和权重,变量具有相同的行数
【发布时间】:2020-10-31 04:47:39
【问题描述】:

我正在尝试运行加权平方回归,在创建权重并尝试将其添加到回归函数后,我收到以下错误:

model.frame.default 中的错误(公式 = CO2_pc_cmice1 ~ GDP_pc_cmice1_C + :
可变长度不同(为 '(weights)' 找到)

lm 模型有 31 行,我创建的权重也是 31,我检查了其中是否有 NAs 和没有。有一些负数,但如果这是问题,我会感到惊讶。我已经使用na.action = na.omitna.action = na.exclude 运行了公式

我也在用 99 个样本进行回归运行,我遇到了同样的问题。

我的回归是

LinearCO2_lowerF <- (lm(CO2_pc_cmice1 ~ PolCiv_incPressFreedom_C + CorpInf_cmice1_C + 
                                        Gov_cmicepos1_C + LitGini_umice_C + 
                                        GDP_pc_cmice1_C + PopDensity_cmice1_C + 
                                        TradeOpen_cmice1_C + Urban_cmice1_C +
                                        poly(Oil_coal_umice_C,2), 
                                        data = mydata_completemice2, 
                                        subset = IncomeL == "L"))

创建的权重

wtsco2low <- 1/fitted( lm(abs(residuals(LinearCO2_lowerF))~fitted(LinearCO2_lowerF)) )^2 

还有权重回归

LinearCO2_lowerFw <- lm(CO2_pc_cmice1 ~ GDP_pc_cmice1_C + PolCiv_incPressFreedom_C +
                                        CorpInf_cmice1_C + Gov_cmicepos1_C + 
                                        LitGini_umice_C + PopDensity_cmice1_C +
                                        TradeOpen_cmice1_C + Urban_cmice1_C + 
                                        poly(Oil_coal_umice_C,2), 
                                        data = mydata_completemice2, 
                                        subset = IncomeL == "L",
                                        weights = wtsco2low, 
                                        na.action = na.omit)

(也试过na.exlude

有人可以帮忙吗?

【问题讨论】:

    标签: r linear-regression


    【解决方案1】:

    R 建模函数的 subset= 参数应用于所有参数。因此,看起来您的权重向量正在被子集化。因为它已经是正确的长度,所以你会得到一个错误。

    考虑这个例子:数据框有 30 行,但要分析的子集中只有 20 行,而我只有 20 个权重。如果我使用 subset= 参数,权重会被子集化,并且会出现错误。

    相反,您可以在将数据传递给lm() 之前对数据使用subset(),这样就可以了。

    > d<-data.frame(y=rnorm(30),x=1:30)
    > w<-rep(2,20)
    > 
    > lm(y~x,data=d, subset=x>10)
    
    Call:
    lm(formula = y ~ x, data = d, subset = x > 10)
    
    Coefficients:
    (Intercept)            x  
        -0.3161       0.0189  
    
    > lm(y~x,data=d, subset=x>10, weights=w)
    Error in model.frame.default(formula = y ~ x, data = d, subset = x > 10,  : 
      variable lengths differ (found for '(weights)')
    > lm(y~x,data=subset(d, x>10),  weights=w)
    
    Call:
    lm(formula = y ~ x, data = subset(d, x > 10), weights = w)
    
    Coefficients:
    (Intercept)            x  
        -0.3161       0.0189  
    ```
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-24
      • 1970-01-01
      • 1970-01-01
      • 2016-06-24
      • 1970-01-01
      • 2019-06-01
      • 1970-01-01
      相关资源
      最近更新 更多