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

运行R语言glm预测代码遇newdata行数不匹配警告,请求协助

解决R语言predict函数的行数不匹配警告

Hey there, let's break down why you're getting that warning and fix it step by step.

问题根源

The warning 'newdata' had 73 rows but variables found have 371380 rows happens because of how you built your glm model. When you wrote:

PoGLM<-glm(tdt$NC.x~AGEF, family=poisson(link="log"))

You directly referenced tdt$NC.x as the dependent variable, but didn't specify the data=tdt argument in the glm() function. This means the model only remembers the variable names (NC.x and AGEF) but doesn't tie them to the tdt data frame.

When you run predict() with newdata=Ag, R tries to find the AGEF variable in your global environment—and it ends up grabbing the original AGEF from tdt (which has 371380 rows) instead of using the one in Ag (73 rows). That's the mismatch causing the warning.

修复步骤

  1. 重新构建模型时指定data参数
    一定要在glm()里明确变量所属的数据框,让模型和正确的数据集绑定:

    PoGLM <- glm(NC.x ~ AGEF, family=poisson(link="log"), data=tdt)
    

    现在模型训练时会从tdt取变量,预测时会优先从newdata里查找对应变量。

  2. 确认newdata包含正确的变量
    检查Ag里是否有列名完全匹配的AGEF(R对大小写敏感!),可以用以下命令验证:

    names(Ag)
    

    如果列名不一致(比如是agef或AgeF),记得改成和模型公式里一致的名称。

  3. 重新运行预测命令
    用修复后的模型再次执行预测:

    prf <- predict(PoGLM, newdata=Ag, type="response")
    

额外小贴士

尽量避免在模型公式里直接用$引用变量(比如tdt$NC.x),使用公式+data参数的方式不仅让代码更易读、可复现,还能避免这类变量作用域不匹配的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:23:01