通过RPy查看R数据示例(例如:lmeSplines)

时间:2014-07-14 01:24:17

标签: python r rpy2 spline nlme

我目前正在尝试重建lmeSplines的示例代码(official documentation上的第4页和第5页)。

第一行代码是(在R语法中):

# smoothing spline curve fit
data(smSplineEx1)

如何通过RPy查看此数据?我试过:

from rpy2.robjects.packages import importr
lmeS = importr("lmeSplines")
print lmeS.smSplineEx1

我得到了:

AttributeError: 'InstalledSTPackage' object has no attribute 'smSplineEx1'

2 个答案:

答案 0 :(得分:1)

请勿尝试逐行翻译R代码,如果我们这样做,请尝试以rpy2方式执行此操作。例如,要访问数据集smsSplineEx:请使用ro.r.smSplineEx1

In [34]:

import rpy2.robjects as ro
import pandas.rpy.common as com
mydata = ro.r['data.frame']
read = ro.r['read.csv']
head = ro.r['head']
summary = ro.r['summary']
library = ro.r['library']
In [35]:

formula = '~ time'
library('lmeSplines')
ro.reval('smSplineEx1$all <- rep(1,nrow(smSplineEx1))')
result = ro.r.smspline(formula=ro.r(formula), data=ro.r.smSplineEx1) #notice: data=ro.r.smSplineEx1
In [36]:

print com.convert_robj(result).head()
         0         1         2         3         4         5         6   \
1  1.168560  2.071261  2.944953  3.782848  4.584037  5.348937  6.078121   
2  0.148786  1.072013  1.948857  2.789264  3.593423  4.361817  5.095016   
3 -0.054492  0.072766  0.952761  1.795679  2.602809  3.374698  4.111911   
4 -0.053646 -0.135912 -0.043334  0.802095  1.612194  2.387579  3.128806   
5 -0.052799 -0.133771 -0.250619 -0.191489  0.621580  1.400459  2.145701   

         7         8         9     ...           88        89        90  \
1  6.772184  7.431719  8.057321    ...     0.933947  0.769591  0.619420   
2  5.793601  6.458153  7.089255    ...     0.904395  0.745337  0.599976   
3  4.815018  5.484587  6.121190    ...     0.874843  0.721083  0.580531   
4  3.836434  4.511021  5.153124    ...     0.845291  0.696829  0.561086   
5  2.857851  3.537455  4.185059    ...     0.815739  0.672575  0.541641   

         91       92        93        94        95        96        97  
1  0.484029  0.36401  0.259959  0.172468  0.102133  0.049547  0.015305  
2  0.468893  0.35267  0.251890  0.167135  0.098986  0.048026  0.014836  
3  0.453756  0.34133  0.243821  0.161801  0.095838  0.046504  0.014368  
4  0.438620  0.32999  0.235753  0.156467  0.092691  0.044982  0.013899  
5  0.423484  0.31865  0.227684  0.151134  0.089544  0.043461  0.013431  

[5 rows x 98 columns]

答案 1 :(得分:0)

除了下面的@CT朱提出的解决方案,我发现这个appraoch:

import pandas.rpy.common as com
from rpy2.robjects.packages import importr
lmeS = importr("lmeSplines")
sp_data = com.load_data('smSplineEx1') 

正是我所寻找的(因为它将数据导入为pandas数据帧,因此您可以使用自己喜欢的Python工具对其进行操作)。