Basics of R Programming
Finally, with all the set-ups, you can write your first piece of R script. The following paragraphs introduce you to the basics of R programming.
A quick tip before going: all lines after the symbol
# will be treated as a comment and will not be rendered in the output.
Let’s start with some basic arithmetics. You can do some simple calculations with the arithmetic operators:
/ should be intuitive.
1 + 1
2 - 2
3 * 2
4 / 2
The exponentiation operator
^ raises the number to its left to the power of the number to its right: for example
3 ^ 2 is 9.
2 ^ 4
The modulo operator
%% returns the remainder of the division of the number to the left by the number on its right, for example 5 modulo 3 or
5 %% 3 is 2.
5 %% 2
Lastly, the integer division operator
%/% returns the maximum times the number on the left can be divided by the number on its right, the fractional part is discarded, for example,
9 %/% 4 is 2.
# Integer division
5 %/% 2
You can also add brackets
() to change the order of operation. Order of operations is the same as in mathematics (from highest to lowest precedence):
(3 + 5) * 2
A basic concept in (statistical) programming is called a variable.
A variable allows you to store a value (e.g. 4) or an object (e.g. a function description) in R. You can then later use this variable’s name to easily access the value or the object that is stored within this variable.
Create New Variables
Create a new object with the assignment operator
<-. All R statements where you create objects and assignment statements have the same form:
num_var <- 10
chr_var <- "Ten"
To access the value of the variable, simply type the name of the variable in the console.
You can access the value of the variable anywhere you call it in the R script, and perform further operations on them.
first_var <- 1
second_var <- 2
first_var + second_var
sum_var <- first_var + second_var
Not all kinds of names are accepted in R. Variable names must start with a letter, and can only contain letters, numbers,
_. Also, bear in mind that R is case-sensitive, i.e.
Cat would not be identical to
Your object names should be descriptive, so you’ll need a convention for multiple words. It is recommended to
snake_case where you separate lowercase words with
If you’ve been programming in other languages before, you’ll notice that the assignment operator in R is quite strange as it uses
<- instead of the commonly used equal sign
= to assign objects.