R#1: Introduction to R and RStudio

Laurent Modolo laurent.modolo@ens-lyon.fr

10 Oct 2019

R#1: Introduction to R and RStudio

The goal of this practical is to familiarize yourself with R and the RStudio environment.

The objectives of this session will be to:

Acknowledgments

Some R background

is a programming language and free software environment for statistical computing and graphics supported by the R Foundation for Statistical Computing.

Some R background

Some R background

Reasons to use

Some R background

RStudio, the R IDE

An interface

The same console as before

R as a calculator

R as a calculator

1 + 100
1 +
3 + 5 * 2
(3 + 5) * 2
(3 + (5 * (2 ^ 2))) # hard to read
3 + 5 * 2 ^ 2       # clear, if you remember the rules
3 + 5 * (2 ^ 2)     # if you forget some rules, this might help
2/10000

2e-4 is shorthand for 2 * 10^(-4)

5e3

Mathematical functions

log(1)  # natural logarithm
log10(10) # base-10 logarithm
exp(0.5)

Compute the factorial of 9

factorial(9)

Comparing things

equality (note two equal signs read as “is equal to”)

1 == 1

inequality (read as “is not equal to”)

1 != 2 

less than

1 < 2

less than or equal to

1 <= 1

greater than

1 > 0

Variables and assignment

<- is the assignment operator in R. (read as left member take right member value)

x <- 1/40
x

The environment

Variables and assignment

log(x)
x <- 100
log(x)
x <- x + 1
y <- x * 2
z <- "x"
x + z

Variables and assignment

Variable names can contain letters, numbers, underscores and periods.

They cannot start with a number nor contain spaces at all.

Different people use different conventions for long variable names, these include

periods.between.words
underscores_between_words
camelCaseToSeparateWords

What you use is up to you, but be consistent.

It is also possible to use the = operator for assignment but don’t do it !

Variables and assignment

Which of the following are valid R variable names?

min_height
max.height
_age
.mass
MaxLength
min-length
2widths
celsius2kelvin

http://perso.ens-lyon.fr/laurent.modolo/R/1_a

Functions are also variables

logarithm <- log

A R function can have different arguments

function (x, base = exp(1))

To know more about the log function we can read its manual.

help(log)
?log

Various output

Functions are also variables

Test that your logarithm function can work in base 10

10^logarithm(12, base = 10)

Functions are also variables

We can also define our own function with

<FUNCTION_NAME> <- function(a, b){
  <RESULT_1> <- <OPERATION_1>(a, b)
  <RESULT_2> <- <OPERATION_2>(<RESULT_1>, b)
  return(<RESULT_2>)
}

write a function to test the base of the logarithm function