为什么 R 和 statsmodels 给出的方差分析结果略有不同? [英] Why do R and statsmodels give slightly different ANOVA results?

查看:38
本文介绍了为什么 R 和 statsmodels 给出的方差分析结果略有不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用一个小的 R 样本数据集和来自 statsmodels,其中一个变量的自由度以不同方式报告,&F 值结果也略有不同.也许他们的默认方法略有不同?我可以设置 statsmodels 以使用 R 的默认值吗?

Using a small R sample dataset and the ANOVA example from statsmodels, the degrees of freedom for one of the variables are reported differently, & the F-values results are also slightly different. Perhaps they have slightly different default approaches? Can I set up statsmodels to use R's defaults?

import pandas as pd
import statsmodels.api as sm
from statsmodels.formula.api import ols


##R code on R sample dataset

#> anova(with(ChickWeight, lm(weight ~ Time + Diet)))
#Analysis of Variance Table
#
#Response: weight
#           Df  Sum Sq Mean Sq  F value    Pr(>F)
#Time        1 2042344 2042344 1576.460 < 2.2e-16 ***
#Diet        3  129876   43292   33.417 < 2.2e-16 ***
#Residuals 573  742336    1296
#write.csv(file='ChickWeight.csv', x=ChickWeight, row.names=F)

cw = pd.read_csv('ChickWeight.csv')
cw_lm=ols('weight ~ Time + Diet', data=cw).fit()   

print(sm.stats.anova_lm(cw_lm, typ=2))
#                  sum_sq   df            F         PR(>F)
#Time      2024187.608511    1  1523.368567  9.008821e-164
#Diet       108176.538530    1    81.411791   2.730843e-18
#Residual   764035.638024  575          NaN            NaN

数据集的头尾相同*,也是均值、最小值、最大值、权重和时间的中位数.

Head and tail of the datasets are the same*, also mean, min, max, median of weight and time.

推荐答案

看起来Diet"在 statsmodels 调用中只有一个自由度,这意味着它可能被视为一个连续变量,而在 R 中它有 3 个自由度自由,所以它可能是一个因子/离散随机变量.

Looks like "Diet" only has one degree of freedom in the statsmodels call which means it was probably treated as a continuous variable whereas in R it has 3 degrees of freedom so it probably was a factor/discrete random variable.

要使 ols() 将饮食"视为分类随机变量,请使用

To make ols() treat "Diet" as a categorical random variable, use

cw_lm=ols('weight ~ C(Diet) + Time', data=cw).fit()

这篇关于为什么 R 和 statsmodels 给出的方差分析结果略有不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆