R and Python in one Jupyter notebook

前端 未结 5 724
春和景丽
春和景丽 2020-12-02 04:59

Is it possible to run R and Python code in the same Jupyter notebook. What are all the alternatives available?

  1. Install r-essentials and create R notebooks in J
5条回答
  •  被撕碎了的回忆
    2020-12-02 05:38

    Yes, it is possible! Use rpy2.

    You can install rpy2 with: pip install rpy2

    Then run %load_ext rpy2.ipython in one of your cells. (You only have to run this once.)

    Now you can do the following:

    Python cell:

    # enables the %%R magic, not necessary if you've already done this
    %load_ext rpy2.ipython
    
    import pandas as pd
    df = pd.DataFrame({
        'cups_of_coffee': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
        'productivity': [2, 5, 6, 8, 9, 8, 0, 1, 0, -1]
    })
    

    R cell:

    %%R -i df -w 5 -h 5 --units in -r 200
    # import df from global environment
    # make default figure size 5 by 5 inches with 200 dpi resolution
    
    install.packages("ggplot2", repos='http://cran.us.r-project.org', quiet=TRUE)
    library(ggplot2)
    ggplot(df, aes(x=cups_of_coffee, y=productivity)) + geom_line()
    

    And you'll get your pretty figure plotting data from a python Pandas DataFrame.

提交回复
热议问题