如何使R数据文件成为Python类型

时间:2018-01-05 10:28:31

标签: pandas dataframe rpy2

我想让下面的Python数据类型的R数据类型是整个代码

def convert_datafiles(datasets_folder):
import rpy2.robjects
rpy2.robjects.numpy2ri.activate()
pandas2ri.activate()
for root, dirs, files in os.walk(datasets_folder):
    for name in files:
        # sort out .RData files
        if name.endswith('.RData'):
            name_ = os.path.splitext(name)[0]
            name_path = os.path.join(datasets_folder, name_)
            # creat sub-directory
            if not os.path.exists(name_path):
                os.makedirs(name_path)
            file_path = os.path.join(root, name)
            robj = robjects.r.load(file_path)
            # check out subfiles in the data frame
            for var in robj:

                ###### error   happend right here
                myRData = pandas2ri.ri2py_dataframe( var  )
                ####error happend right here



                # convert to DataFrame
                if not isinstance(myRData, pd.DataFrame):
                    myRData = pd.DataFrame(myRData)
                var_path = os.path.join(datasets_folder,name_,var+'.csv')
                myRData.to_csv(var_path)
            os.remove(os.path.join(datasets_folder, name)) # clean up

print ("=> Success!")

我想将R数据类型设置为pythone类型,但错误会不断弹出:AttributeError:' str'对象没有属性' dtype'

我该如何解决此错误?

1 个答案:

答案 0 :(得分:0)

与大熊猫交互时,rpy2 documentation有点不完整,但单元测试会提供examples of conversion。例如:

rdataf = robjects.r('data.frame(a=1:2, '
                    '           b=I(c("a", "b")), '
                    '           c=c("a", "b"))')
with localconverter(default_converter + rpyp.converter) as cv:
    pandas_df = robjects.conversion.ri2py(rdataf)