使用rpy2从回归中获取标准错误

时间:2012-01-14 23:41:21

标签: python r rpy2 lm

我使用rpy2进行回归分析。返回的对象有一个列表,其中包括系数,残差,拟合值,拟合模型的等级等。)

但是我无法在fit对象中找到标准错误(也不是R ^ 2)。在R中直接运行lm模型,使用summary命令显示标准错误,但我无法直接在模型的数据框中访问它们。

如何使用rpy2提取此信息?

示例python代码是

from scipy import random
from numpy import hstack, array, matrix
from rpy2 import robjects 
from rpy2.robjects.packages import importr

def test_regress():
    stats=importr('stats')
    x=random.uniform(0,1,100).reshape([100,1])
    y=1+x+random.uniform(0,1,100).reshape([100,1])
    x_in_r=create_r_matrix(x, x.shape[1])
    y_in_r=create_r_matrix(y, y.shape[1])
    formula=robjects.Formula('y~x')
    env = formula.environment
    env['x']=x_in_r
    env['y']=y_in_r
    fit=stats.lm(formula)
    coeffs=array(fit[0])
    resids=array(fit[1])
    fitted_vals=array(fit[4])
    return(coeffs, resids, fitted_vals) 

def create_r_matrix(py_array, ncols):
    if type(py_array)==type(matrix([1])) or type(py_array)==type(array([1])):
        py_array=py_array.tolist()
    r_vector=robjects.FloatVector(flatten_list(py_array))
    r_matrix=robjects.r['matrix'](r_vector, ncol=ncols)
    return r_matrix

def flatten_list(source):
    return([item for sublist in source for item in sublist])

test_regress()

2 个答案:

答案 0 :(得分:3)

所以这似乎对我有用:

def test_regress():
    stats=importr('stats')
    x=random.uniform(0,1,100).reshape([100,1])
    y=1+x+random.uniform(0,1,100).reshape([100,1])
    x_in_r=create_r_matrix(x, x.shape[1])
    y_in_r=create_r_matrix(y, y.shape[1])
    formula=robjects.Formula('y~x')
    env = formula.environment
    env['x']=x_in_r
    env['y']=y_in_r
    fit=stats.lm(formula)
    coeffs=array(fit[0])
    resids=array(fit[1])
    fitted_vals=array(fit[4])
    modsum = base.summary(fit)
    rsquared = array(modsum[7])
    se = array(modsum.rx2('coefficients')[2:4])
    return(coeffs, resids, fitted_vals, rsquared, se) 

虽然,正如我所说,这实际上是我第一次涉足RPy2,所以可能有更好的方法来做到这一点。但是这个版本似乎输出包含R平方值和标准误差的数组。

您可以使用print(modsum.names)查看R对象组件的名称(类似于R中的names(modsum)),然后.rx.rx2等效R中的[[[

答案 1 :(得分:1)

@joran:非常好。我会说它几乎就是这样做的。

from rpy2 import robjects 
from rpy2.robjects.packages import importr

base = importr('base')
stats = importr('stats') # import only once !

def test_regress():
    x = base.matrix(stats.runif(100), nrow = 100)
    y = (x.ro + base.matrix(stats.runif(100), nrow = 100)).ro + 1 # not so nice
    formula = robjects.Formula('y~x')
    env = formula.environment
    env['x'] = x
    env['y'] = y
    fit = stats.lm(formula)
    coefs = stats.coef(fit)
    resids = stats.residuals(fit)    
    fitted_vals = stats.fitted(fit)
    modsum = base.summary(fit)
    rsquared = modsum.rx2('r.squared')
    se = modsum.rx2('coefficients')[2:4]
    return (coefs, resids, fitted_vals, rsquared, se) 
相关问题