Minimal example of rpy2 regression using pandas data frame

前端 未结 3 472
灰色年华
灰色年华 2020-12-08 15:57

What is the recommended way (if any) for doing linear regression using a pandas dataframe? I can do it, but my method seems very elaborate. Am I making things unnecessarily

3条回答
  •  离开以前
    2020-12-08 16:24

    After calling pandas2ri.activate() some conversions from Pandas objects to R objects happen automatically. For example, you can use

    M = R.lm('y~x', data=df)
    

    instead of

    robjects.globalenv['dataframe'] = dataframe
    M = stats.lm('y~x', data=base.as_symbol('dataframe'))
    

    import pandas as pd
    from rpy2 import robjects as ro
    from rpy2.robjects import pandas2ri
    pandas2ri.activate()
    R = ro.r
    
    df = pd.DataFrame({'x': [1,2,3,4,5], 
                       'y': [2,1,3,5,4]})
    
    M = R.lm('y~x', data=df)
    print(R.summary(M).rx2('coefficients'))
    

    yields

                Estimate Std. Error  t value  Pr(>|t|)
    (Intercept)      0.6  1.1489125 0.522233 0.6376181
    x                0.8  0.3464102 2.309401 0.1040880
    

提交回复
热议问题