如何在 Google 协作中使用 R?

Google Collabatory 支持 Python 2.7和3.6版本

不久前,我在 Colab 看到了一个如何使用 Swift 的例子。

今天,我碰巧跑了

!jupyter-kernelspec list

并且发现了一个新的内核: IRkernel

Available kernels:
ir         /usr/local/share/jupyter/kernels/ir
python2    /usr/local/share/jupyter/kernels/python2
python3    /usr/local/share/jupyter/kernels/python3
swift      /usr/local/share/jupyter/kernels/swift

现在在 Colab 也可以使用 R 了吗?

100228 次浏览

Yes.

For a new R-notebook, use this link. (shorthand is colab.to/r )

You can learn from IRkernel demos, e.g. demo.ipynb

Save a copy in your Google Drive, and make any changes you need.

2 more demos:

See more details in IRkernel Github.

In case you want to use Python and R together, you can use R magic for some cells.

# activate R magic
%load_ext rpy2.ipython

Then, whenever you want to use R, you begin the cell with %%R

%%R
x <- 42
print(x)

More details in rpy2 documentation

Open this link in your browser to create a new notebook with R Kernel

https://colab.research.google.com/notebook#create=true&language=r

Update: this doesn't work anymore (july 2020).

The above link on answers above takes directly to R notebook, there you have an option change between R or python. It is strange that Google is changing services just like this. Hence stackoverflow not a great platform to promote tools created by profit mongering/data-selling companies.

Old answer:

enter image description here

As of now if you click at Runtime on menu bar then choose Change Runtime Type, you can choose between R or Python. Changing runtime in Colab

To expand on a previous answer, here's how you can move dataframes between the R and Python kernels so you can work with both in the same notebook (for example, if you want to load data in with Pandas, process it with an R package, and then plot it with Bokeh).

# Pandas dataframe to R data frame
!pip3 install rpy2
%load_ext rpy2.ipython
%R -i df
# R data frame to Pandas dataframe
%R seq.data <- read.delim('sequence.index', header=TRUE, stringsAsFactors=FALSE)
seq_data = %R seq.data

*****Working as of Friday 13th November 2020

Go this URL https://colab.to/r whilst signed into colab and that should do it.

You can check if R in Runtime -> Change runtime type, but it should already be setup.

enter image description here

To mount google drive:

install.packages("googledrive")
library("googledrive")


if (file.exists("/usr/local/lib/python3.6/dist-packages/google/colab/_ipython.py")){
install.packages("R.utils")
library("R.utils")
library("httr")
my_check <- function() {return(TRUE)}
reassignInPackage("is_interactive", pkgName = "httr", my_check)
options(rlang_interactive=TRUE)
}

And authenticate google drive

drive_auth(use_oob = TRUE, cache = TRUE)

Another quick way is to replace postix, .ipynb in colab title to .r
Example: change name of Untitled.ipynb to Untitled.r, and everything works perfectly!