我正在使用rpy2在python中嵌入一些R,并从python内部调用lm。我的目标是提取参数t-stat或p值。我不知道该怎么做。通常,在R中,我使用summary(model)$coefficients[1,4]。如何在python环境中调用它?
发布于 2017-09-27 19:32:20
在the rpy2 docs和the Pandas docs中有一些(但不多)有用的信息。
检索R命令详细结果的最佳方法似乎如下所示。
我们从通常的导入开始:
import pandas as pd
from rpy2.robjects import r as R
from rpy2.robjects.packages import importr
from rpy2.robjects import pandas2ri
stats = importr('stats')
base = importr('base')现在运行R中的线性模型并检索系数:
# Equivalent of lm(Sepal.Length ~ Sepal.Width, data='iris')
lm = stats.lm("Sepal.Length ~ Sepal.Width", data=R['iris'])
# Equivalent of summary(lm)
summary = base.summary(lm)
# Extract the coefficients
coeffs = summary.rx2('coefficients')然后,我们可以从coeffs对象创建一个Pandas数据帧:
# Build a DataFrame from the coefficients tables
df = pd.DataFrame(pandas2ri.ri2py(coeffs),
index=coeffs.names[0], columns=coeffs.names[1])现在,我们可以像在Python中一样使用系数:
In [11]: df['Pr(>|t|)'] # p-values!
Out[11]:
(Intercept) 6.469702e-28
Sepal.Width 1.518983e-01
Name: Pr(>|t|), dtype: float64
In [12]: df.loc['Sepal.Width', 'Pr(>|t|)']
Out[12]: 0.15189826071144744发布于 2015-02-01 10:58:54
这不是在rpy2简介中涉及到的吗?
http://rpy.sourceforge.net/rpy2/doc-2.5/html/introduction.html#linear-models
https://stackoverflow.com/questions/28157218
复制相似问题