%pylab inline
Populating the interactive namespace from numpy and matplotlib
# RとPandasのデータフレームを相互に変換する方法
# Sageでは、numpyとpandasをインポート
import pandas as pd
import numpy as np
import rpy2.robjects as robjects
ro = robjects.r
# 例としてR Graphic Cookbookのデータを使用
#ro("install.packages('gcookbook')")
ro('library(gcookbook)')
<StrVector - Python:0x1131c47e8 / R:0x7fe1fe23eff8> ['gcoo..., 'tools', 'stats', ..., 'data..., 'meth..., 'base']
# Rのデータフレームをpandasのデータフレームに変換する
import pandas.rpy.common as com
# heightweight = com.load_data('heightweight')
# Rのデータフレームをpandasのデータフレームに変換する
# r_dataframe = com.convert_to_r_dataframe(df)
# pandasのデータフレームをRに渡す
from sage.all import *
# print RDf2PandaDf('heightweight').head()
heightweight = com.load_data('heightweight')
heightweight.head()
sex | ageYear | ageMonth | heightIn | weightLb | |
---|---|---|---|---|---|
1 | f | 11.92 | 143 | 56.3 | 85.0 |
2 | f | 12.92 | 155 | 62.3 | 105.0 |
3 | f | 12.75 | 153 | 63.3 | 108.0 |
4 | f | 13.42 | 161 | 59.0 | 92.0 |
5 | f | 15.92 | 191 | 62.5 | 112.5 |
# PandasのデータをRに渡す
age = [20, 22, 25, 27, 21, 23, 37, 31, 61, 45, 41, 32]
sex = ['F', 'M', 'M', 'M', 'F', 'M', 'F', 'M', 'F', 'M', 'F', 'M']
df = pd.DataFrame({'age': age, 'sex': sex}); df.head()
age | sex | |
---|---|---|
0 | 20 | F |
1 | 22 | M |
2 | 25 | M |
3 | 27 | M |
4 | 21 | F |
# PandaDf2RDf(df, "a")
# r('a')
r_dataframe = com.convert_to_r_dataframe(df)
print(type(r_dataframe))
<class 'rpy2.robjects.vectors.DataFrame'>
print(r_dataframe)
age sex 0 20 F 1 22 M 2 25 M 3 27 M 4 21 F 5 23 M 6 37 F 7 31 M 8 61 F 9 45 M 10 41 F 11 32 M