Professional Documents
Culture Documents
Lecture 1
Samuel Touchard
1/12
The Command Line
R is a scripting language, which means it can run commands as soon as you type them. This is
done at the prompt, represented by >. When you type a complete command at the prompt and
press enter, it runs, does any computation, and prints the answer.
> 10+5
[1] 15
If you start a command but don’t finish it, the prompt changes to a +, indicating that it
expects more:
> 10+5+
+
If this happens by mistake, press escape to cancel the command.
2/12
Arithmetic Operators
Operator Description
+ addition
- soustraction
* multiplication
/ division
ˆ or ** exponentiation
x%%y modulus (x mod y)
x%/%y integer division
3/12
Arithmetic
The symbols +, −, ∗, /,^, () do the usual things in the usual order.
> (15+10)/5
[1] 5
> (2^-2*4)+2
[1] 3
> 4^2 %% 5
[1] 1
> 4^2 %/% 5
[1] 3
4/12
Variables
You can define and set variables with = or < −. Typing an object’s name at the command line
causes it to be printed.
Note: # is used to add comments. Everything that follows # in the same line will be ignored.
5/12
Vectors
To create a vector, use c() separating entries by commas:
> c(x, 5, x)
[1] -1 0 1 5 -1 0 1
6/12
Vector Arithmetics
7/12
Vector Arithmetics
Recycling Rule: If two vectors are of unequal length, the shorter one will be recycled in order
to match the longer vector.
8/12
Vector Arithmetics
Question: But what if you can’t divide the longest length by the shortest length?
9/12
Vector Arithmetics
Question: But what if you can’t divide the longest length by the shortest length?
9/12
Scientific notation
With very large or small values (in absolute), R will use a scientific notation that may disrupt
people at first. Indeed, it uses scientific e notation where e tells you to multiple the base
number by 10 raised to the power shown.
> 365612186454331
[1] 3.656122e+14
> 0.00000000000468
[1] 4.68e-12
> 7.1*10^16
[1] 7.1e+16
> 2.5*10^{-12}
[1] 2.5e-12
10/12
Exercise 1
Task
The gravitational force F (in Newtons) acting between two objects of masses m1 and m2 (kgs),
separated by a distance r (meters) between the centers of their masses, is:
m1 m2
F =G
r2
where G is the gravitational constant 6.674 × 10−11 SI.
Using R, calculate the gravitational force between the Sun (m1 = 1.989 × 1030 kg) and the
Earth (m2 = 5.972 × 1024 kg), separated by r = 147.1 million kms.
11/12
Exercise 2
Task
In physics, the kinetic energy (KE) of an object is the energy that it possesses due to its
motion. It can be calculated as
1
KE = mv 2
2
with m the mass in kilograms, v the speed in meters per second, and the cinetic energy KE in
joules.
When beating the 100m world record in 2009, Usain Bolt reached the maximum speed of 44.72
km/h (37.58 km/h on average). We assume he weighted 94kgs.
Using R, calculate the kinetic energy developed by Usain Bolt that day.
Try and compare with your personal (estimated) value!
12/12