GLM二项式回归:levels函数无法查看预测类别问题求助
问题:GLM二项式回归查看预测类别失败
我遇到了类似问题——想查看GLM二项式回归的预测类别,按照建议尝试用levels()方法但未能成功。
我的GLM回归代码:
glm( factor(mgroup) ~ factor(sex) + age + factor(Site_Category) + expr, data = pheno, family = binomial)
尝试执行以下命令均报错:
> levels(mgroup) Error in h(simpleError(msg, call)) : error in evaluating the argument 'x' in selecting a method for function 'levels': object 'mgroup' not found > levels(outcome) Error in h(simpleError(msg, call)) : error in evaluating the argument 'x' in selecting a method for function 'levels': object 'outcome' not found > levels(factor(mgroup)) Error in h(simpleError(msg, call)) : error in evaluating the argument 'x' in selecting a method for function 'levels': object 'mgroup' not found
请问我哪里操作出错了?
解决方案
你的操作错误在于未正确指定变量的数据源:
mgroup是数据框pheno中的列,直接单独调用mgroup时,R会在全局环境中查找这个对象,但它仅存在于pheno内部,因此触发“对象未找到”的报错。outcome是参考回答中的变量名,你的回归模型用的是mgroup,全局环境中不存在outcome对象,自然报错。
正确的操作方式:
- 直接从数据框
pheno中查看mgroup的水平:
# 如果mgroup已经是因子类型 levels(pheno$mgroup) # 如果mgroup是数值/字符类型,先转成因子再查看 levels(factor(pheno$mgroup))
- 若将回归模型保存到变量中,可从模型对象提取响应变量的水平:
# 先保存模型 model <- glm( factor(mgroup) ~ factor(sex) + age + factor(Site_Category) + expr, data = pheno, family = binomial) # 查看响应变量的水平 levels(model$y)
内容的提问来源于stack exchange,提问作者Sally
相关产品推荐
相关产品推荐

