使用rpy2将R lm回归的统计数据提取到pandas中

3
受文档中线性模型示例的启发(链接),在运行lm命令后,我想打印一个漂亮的摘要。
当我运行时(见示例的最后一行):
print(base.summary(stats.lm('foo ~ bar'))

我收到了一个完整的函数列表,其开头如下所示:
Call:
(function (formula, data, subset, weights, na.action, method = "qr", 
    model = TRUE, x = FALSE, y = FALSE, qr = TRUE, singular.ok = TRUE, 
    contrasts = NULL, offset, ...) 
{
    ret.x <- x
    ret.y <- y
    cl <- match.call()
    mf <- match.call(expand.dots = FALSE)

希望在底部得到所需的R输出:

Coefficients:
         Estimate Std. Error t value Pr(>|t|)    
foo        5.0320     0.2202   22.85 9.55e-15 ***
bar        4.6610     0.2202   21.16 3.62e-14 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1   1

Residual standard error: 0.6964 on 18 degrees of freedom
Multiple R-squared:  0.9818,    Adjusted R-squared:  0.9798 
F-statistic: 485.1 on 2 and 18 DF,  p-value: < 2.2e-16

这种情况有一定的问题,但当输入到lm的数据是pandas.DataFrame时,就变得不可行了,因为base.summary似乎想要打印所有数据。

是否有一种方法可以仅获取pd.DataFrame中漂亮格式化的R输出,而没有所有额外的内容?


3
R中的broom包是什么? - Metrics
1
@Metrics 这看起来是一个不错的选择。如果这个问题能教我一些关于 rpy2 的情况,那就太好了。比如,我该如何明确处理 lm 的返回类型? - LondonRob
1个回答

2

为了后人,这里有一个非常好的方法可以将lm中的数字返回到pd.DataFrame(感谢@Metrics提供关于broom的提示)

def _run_regression(data, y_name):
    """
    Run a linear regression, in R, using `data` with dependent variable
    `y_name` and independent variables all other columns of `data`.
    """
    from rpy2.robjects.packages import importr
    stats = importr('stats')
    broom = importr('broom')
    lm = broom.tidy(stats.lm('%s ~ . ' % y_name, data=data))
    return _extract_R_df(lm).set_index('term')

def _extract_R_df(df):
    """
    Extract the R DataFrame `df` as a pd.DataFrame. This slightly
    longer method is necessary because `np.asarray(df)` drops the
    exponent on very small numbers!
    """
    return pd.DataFrame({name:np.asarray(df.rx(name))[0] for name in df.names})

这将导致一个类似于这样的DataFrame:
                 estimate   p.value     statistic     std.error
term                                                           
(Intercept) -3.709995e-16  0.000056 -4.712554e+00  7.872579e-17
x_is         8.000000e-01  0.000000  1.067919e+16  7.491204e-17
v_is         2.000000e-01  0.000000  2.107838e+15  9.488394e-17
d_ij        -2.000000e-01  0.000000 -2.970482e+14  6.732913e-16
d1           1.000000e-01  0.000000  4.045155e+14  2.472093e-16
d2           3.000000e-01  0.000000  5.320521e+14  5.638545e-16
d3           7.000000e-01  0.000000  1.779338e+15  3.934048e-16

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接