B Google Colab

Colab, or Colaboratory is an interactive notebook provided by Google (primarily) for writing and running Python through a browser. We can perform data analysis, create models, evaluate these models in Colab. The processing is done on Google-owned servers in the cloud. We only need a browser and a fairly stable internet connection.

Colab is a great alternative tool to facilitate our work, whether as a student, professional, or researcher.

Although Colab is primarily used for coding in Python, apparently we can also use it for R (#Rstats).

There are two ways to run R in Colab

  • The first way is to use the rpy2 package in the Python runtime. This method allows you to execute R and Python syntax together.
  • The second way is to actually start the notebook in the R runtime.

How to use R and Python together in Colab

  • Open your favorite browser.
  • Create a new notebook: https://colab.research.google.com/#create=true
  • Run rmagic by executing this command %load_ext rpy2.ipython.
  • After that, every time you want to use R, add %%R in the beginning of each cell.

Start rmagic by executing this in a cell:

%load_ext rpy2.ipython

Use %%R to execute cell magic. Use this if you want all syntax in a cell to be executed in R. Note that this must be placed at the beginning of the cell.

%%R x <- seq(0, 2*pi, length.out=50) x

Use %R to execute line magic. Use this if you want a single line in a cell to be executed in R.

Here is how you could use this line magic to copy R variable to Python:

x = %R x

How to use R in Colab

To use the notebook directly with R:

After accessing the URL, you will be taken to a new Colab notebook with the default title Unitled.ipynb.

At first glance, there is no difference between notebooks with Python and R runtimes. However, if we go to the “Runtime” settings, and select “Change runtime type”, we will get a dialog confirming that we are already in R runtime:

Here is the few-minutes video-tutorial on how to work with Google Colab and R: