Overview#
R is not popular in industry. It’s more popular in academia, and I’ll occasionally find myself leaving Python to use R if I need to do something more advanced.
Running R#
This is a Python notebook that runs R code. This is done with the first cell below and then by adding the %%R
command to every cell with R code.
Alternative#
Open an R notebook in Google Colab by opening a notebook and then changing the runtime type.
Go to the ‘Runtime’ menu at the top of the page.
Select ‘Change runtime type’.
Choose ‘R’ under ‘Runtime type’.
Click ‘Save’.
R as a Calculator#
Below is a list of some typical operations.
Operator |
Description |
---|---|
|
Addition |
|
Subtraction |
|
Multiplication |
|
Floating point (normal) division |
|
Exponentiation |
We can use parenthesis for readability and to order operations in the usual way.
!pip install rpy2
%load_ext rpy2.ipython
%%R
2 ^ 3
[1] 8
%%R
(1 - 1) * 0
[1] 0
%%R
1 - 1 * 0
[1] 1
Variables#
You can assign a value to a variable with <-
.
%%R
x <- 0
%%R
x <- x + 1
x
[1] 1
Comments#
Commenting your code is helpful if you care about your colleagues or your future self. Comments should add clarity to the intention and workings of code. A comment is a piece of code that isn’t actually executed-it’s a comment left for the reader or the person who inherits and modifies your code.
Everything after a #
will be ignored by R.
%%R
# The + 1000 is ignored because it's commented out.
9*10 # + 1000
[1] 90