问题描述
使用一个小的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.
推荐答案
看起来像饮食"在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和stats模型给出的方差分析结果略有不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!