2015-01-26 64 views
1

我使用rpy2在python中嵌入一些R,並在python中調用lm。我的目標是提取參數t-stat或p值。我不知道該怎麼做。一般在R我使用summary(model)$coefficients[1,4]。我如何在python環境中調用它?提取係數p值rpy2

回答

0

一些(但不是很多)在the rpy2 docsthe 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對象熊貓數據幀:

# Build a DataFrame from the coefficients tables 
df = pd.DataFrame(pandas2ri.ri2py(coeffs), 
      index=coeffs.names[0], columns=coeffs.names[1]) 

這現在使我們能夠使用係數,因爲我們將n 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