Introduire R¶

In [ ]:
# Aide
help(c)
In [ ]:
# Aide
?rep
In [3]:
# Aide sur le serveur
help.search("rep")
starting httpd help server ...
 done

In [4]:
# Aide sur le serveur
??seq

Manipuler des options¶

In [1]:
# Fuseau horaire
Sys.setenv(TZ = "UTC")
In [ ]:
# Voir toutes les options
options()
In [2]:
# Modifier et afficher une option
options(digits=4)
options(java.parameters = "-Xmx8000m")
getOption("java.parameters") # Affichier
'-Xmx8000m'
In [ ]:
# Information sur la Version de R
R.version
In [9]:
# Version de R
getRversion()
[1] '4.1.3'
In [ ]:
# Information sur la session actuelle
sessionInfo()

Installer des Packages¶

In [11]:
# Direction d'installation des package
# .libPaths("C:/Users/ibtall/anaconda3/Lib/R/library")
.libPaths()
'C:/Users/ibtall/anaconda3/Lib/R/library'
In [2]:
# Pour le datascience
library(tidyverse, warn.conflicts = FALSE)
-- Attaching packages --------------------------------------- tidyverse 1.3.2 --
v ggplot2 3.4.2     v purrr   1.0.2
v tibble  3.2.1     v dplyr   1.1.4
v tidyr   1.3.1     v stringr 1.5.0
v readr   2.1.5     v forcats 1.0.0
-- Conflicts ------------------------------------------ tidyverse_conflicts() --
x dplyr::filter() masks stats::filter()
x dplyr::lag()    masks stats::lag()
In [4]:
library(readxl)
In [5]:
# Aussi foreign
library(haven, warn.conflicts = FALSE)
In [6]:
library(DescTools)
In [7]:
# Aussi openxlsx (use Java)
library(xlsx)
In [8]:
library(labelled, warn.conflicts = FALSE)
In [9]:
# Aussi labelled
library(sjlabelled, warn.conflicts = FALSE)
In [10]:
# Aussi vcdExtra
library(vcd, warn.conflicts = FALSE)
Le chargement a nécessité le package : grid

In [11]:
library(kableExtra, warn.conflicts = FALSE)
In [12]:
library(knitr)

Calculer¶

In [22]:
# Addition
9+2
11
In [23]:
# Soustraction
9-2
7
In [24]:
# Multiplication
9*2
18
In [25]:
# Division réelle
9/2
4.5
In [26]:
# Puissance
9^2
81
In [27]:
# Division entière
9%/%2
4
In [28]:
# Reste de la division entière
9%%2
1
In [29]:
# Série
1:10
pi:7
10:1
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  1. 3.14159265358979
  2. 4.14159265358979
  3. 5.14159265358979
  4. 6.14159265358979
  1. 10
  2. 9
  3. 8
  4. 7
  5. 6
  6. 5
  7. 4
  8. 3
  9. 2
  10. 1
In [30]:
# Séquence de nombres
seq(1, 15, by = 3)
  1. 1
  2. 4
  3. 7
  4. 10
  5. 13
In [31]:
# Vecteurs de nombres
c(1,4,7:10)
  1. 1
  2. 4
  3. 7
  4. 8
  5. 9
  6. 10
In [32]:
# Réplication de (vecteurs) nombres
rep(c(1,3,5), 2)
rep(c(1,3,5), each = 4)
rep.int(c(1,3,5), times = c(4,4,2))
rep_len(c(1,3,5), length.out = 10)
  1. 1
  2. 3
  3. 5
  4. 1
  5. 3
  6. 5
  1. 1
  2. 1
  3. 1
  4. 1
  5. 3
  6. 3
  7. 3
  8. 3
  9. 5
  10. 5
  11. 5
  12. 5
  1. 1
  2. 1
  3. 1
  4. 1
  5. 3
  6. 3
  7. 3
  8. 3
  9. 5
  10. 5
  1. 1
  2. 3
  3. 5
  4. 1
  5. 3
  6. 5
  7. 1
  8. 3
  9. 5
  10. 1
In [33]:
# Suite de lettres
letters[1:4]
  1. 'a'
  2. 'b'
  3. 'c'
  4. 'd'
In [34]:
# Suite aléatoire
sample(1:20, 5)
  1. 2
  2. 1
  3. 16
  4. 3
  5. 9
In [35]:
# Nombres premiers
Primes(n = 20)
IsPrime(sample(1:20, 5))
  1. 2
  2. 3
  3. 5
  4. 7
  5. 11
  6. 13
  7. 17
  8. 19
  1. TRUE
  2. TRUE
  3. TRUE
  4. FALSE
  5. TRUE
In [ ]:
# Factorisation en nombre premiers
Factorize(n = c(56, 42))
In [37]:
# Diviseurs et multiplicateurs
Divisors(c(221, 452))
GCD(64, 80, 160)
LCM(10, 4, 12, 9, 2)
$`221`
  1. 1
  2. 13
  3. 17
$`452`
  1. 1
  2. 2
  3. 4
  4. 113
  5. 226
16
180
In [38]:
# Suite de Fibonacci
Fibonacci(1:12)
  1. 1
  2. 1
  3. 2
  4. 3
  5. 5
  6. 8
  7. 13
  8. 21
  9. 34
  10. 55
  11. 89
  12. 144
In [39]:
# Fcatorelle
factorial(5)
120
In [ ]:
# Combinatoire
Permn(x = c(1,4,9))
CombSet(c(1,4,9), 2, repl=FALSE, ord=TRUE)
In [41]:
# Ensemble à deux éléments
CombPairs(letters[1:3], letters[4:6])
A data.frame: 9 × 2
Var1Var2
<chr><chr>
ad
bd
cd
ae
be
ce
af
bf
cf
In [42]:
# Nombre de combinaison et d'arrangement
CombN(4, 2, repl = FALSE, ord = TRUE)
choose(4, 2)
12
6

Manipuler des dossiers et fichiers¶

In [43]:
dir.exists("TPdir")
FALSE
In [44]:
try(dir.create("TPdir"))
In [45]:
list.dirs(recursive = FALSE)
  1. './.ipynb_checkpoints'
  2. './TPdir'
In [46]:
getwd()
'C:/Users/ibtall/Documents/PERSONNAL/Custom Tables'
In [47]:
setwd("./TPdir")
In [48]:
list.dirs(path = system.file(package = "stringr"), recursive = FALSE)
  1. 'C:/Users/ibtall/anaconda3/Lib/R/library/stringr/data'
  2. 'C:/Users/ibtall/anaconda3/Lib/R/library/stringr/doc'
  3. 'C:/Users/ibtall/anaconda3/Lib/R/library/stringr/help'
  4. 'C:/Users/ibtall/anaconda3/Lib/R/library/stringr/html'
  5. 'C:/Users/ibtall/anaconda3/Lib/R/library/stringr/htmlwidgets'
  6. 'C:/Users/ibtall/anaconda3/Lib/R/library/stringr/Meta'
  7. 'C:/Users/ibtall/anaconda3/Lib/R/library/stringr/R'
In [49]:
list.files(path = system.file("data", package = "stringr"))
  1. 'Rdata.rdb'
  2. 'Rdata.rds'
  3. 'Rdata.rdx'
In [50]:
system.file("data", package = "stringr")
'C:/Users/ibtall/anaconda3/Lib/R/library/stringr/data'
In [51]:
readRDS("C:/Users/ibtall/anaconda3/Lib/R/library/stringr/data/Rdata.rds")
$fruit
'fruit'
$sentences
'sentences'
$words
'words'

Importer des base de données¶

Utiliser des données du système¶

In [52]:
# try() pour prevenir les bugs
# data()
# data(package = .packages(all.available = TRUE))
data(package = c("dplyr", "stringr"))

Data sets

A data.frame: 8 × 3
PackageItemTitle
<chr><chr><chr>
dplyr band_instruments Band membership
dplyr band_instruments2Band membership
dplyr band_members Band membership
dplyr starwars Starwars characters
dplyr storms Storm tracks data
stringrfruit Sample character vectors for practicing string manipulations
stringrsentences Sample character vectors for practicing string manipulations
stringrwords Sample character vectors for practicing string manipulations
In [13]:
data("fruit", package = "stringr")
In [13]:
data("storms", package = "dplyr")
In [55]:
str(storms)
tibble [19,537 x 13] (S3: tbl_df/tbl/data.frame)
 $ name                        : chr [1:19537] "Amy" "Amy" "Amy" "Amy" ...
 $ year                        : num [1:19537] 1975 1975 1975 1975 1975 ...
 $ month                       : num [1:19537] 6 6 6 6 6 6 6 6 6 6 ...
 $ day                         : int [1:19537] 27 27 27 27 28 28 28 28 29 29 ...
 $ hour                        : num [1:19537] 0 6 12 18 0 6 12 18 0 6 ...
 $ lat                         : num [1:19537] 27.5 28.5 29.5 30.5 31.5 32.4 33.3 34 34.4 34 ...
 $ long                        : num [1:19537] -79 -79 -79 -79 -78.8 -78.7 -78 -77 -75.8 -74.8 ...
 $ status                      : Factor w/ 9 levels "disturbance",..: 7 7 7 7 7 7 7 7 8 8 ...
 $ category                    : num [1:19537] NA NA NA NA NA NA NA NA NA NA ...
 $ wind                        : int [1:19537] 25 25 25 25 25 25 25 30 35 40 ...
 $ pressure                    : int [1:19537] 1013 1013 1013 1013 1012 1012 1011 1006 1004 1002 ...
 $ tropicalstorm_force_diameter: int [1:19537] NA NA NA NA NA NA NA NA NA NA ...
 $ hurricane_force_diameter    : int [1:19537] NA NA NA NA NA NA NA NA NA NA ...
In [14]:
storms <- as.data.frame(storms)
fruit <- as.data.frame(fruit)
In [57]:
str(storms$name)
 chr [1:19537] "Amy" "Amy" "Amy" "Amy" "Amy" "Amy" "Amy" "Amy" "Amy" "Amy" ...
In [ ]:
attach(storms)
In [59]:
str(year)
 num [1:19537] 1975 1975 1975 1975 1975 ...
In [60]:
detach(storms)
In [61]:
# load(file = "myenv.RData")
save(storms, file = "myenv.RData")
In [62]:
# load(file = "mydb.rda")
save(storms, file = "mydb.rda")
In [63]:
# load(file = ".RData")
save.image()

Lire les format SPSS, STATA, SAS¶

In [13]:
# Format SPSS
write_sav(storms, bd <- tempfile(fileext = ".sav"))
In [14]:
# Renommer et enregistrer dans le repértoire courant
file.rename(bd, "storms.sav")
TRUE
In [15]:
# Importation de la base SPSS
dat <- read_sav("storms.sav", col_select = c(1:5), n_max = 10)
In [16]:
# long (type décimal) est un nom réservé dans stata
write_dta(rename(storms, gpslong = long), bd <- tempfile(fileext = ".dta"))
In [17]:
file.rename(bd, "storms.dta")
TRUE
In [18]:
dat <- read_dta("storms.dta", col_select = c(1:5), n_max = 10)
In [13]:
write_xpt(storms, bd <- tempfile(fileext = ".xpt"))
In [14]:
file.rename(bd, "storms.xpt")
TRUE
In [21]:
dat <- read_xpt("storms.xpt", col_select = c(1:5), n_max = 10)

Lire un fichier texte (csv)¶

In [15]:
# write.table()
write_delim(storms, "storms.csv", delim = ",")
In [15]:
# Lire un fichier csv
dat <- read_delim(choose.files(), delim = ",", show_col_types = FALSE)
In [75]:
# Lire un fichier csv
dat <- read.delim(choose.files(), sep = ",")
In [76]:
# Lire un fichier csv
dat <- data.table::fread(choose.files(), select = c("name", "day", "category"))
In [77]:
# Lire un fichier csv
dat <- read_csv(choose.files(), show_col_types = FALSE)
In [78]:
# Lire un fichier csv
dat <- read.csv(choose.files())
In [79]:
# Sauvegarder au format csv avec point-virgule
write_delim(storms, "storms2.csv", delim = ";")
In [ ]:
# Lire un fichier csv avec point-virgule
dat <- read_csv2(choose.files(), show_col_types = FALSE)
In [81]:
# Lire un fichier csv point-virgule
dat <- read.csv2(choose.files())

Manipuler un fichier excel¶

In [82]:
# Création un fichier Excel
cls <- createWorkbook(type = "xlsx")
In [83]:
# Création d'une feuille
f1 <- createSheet(cls, sheetName = "STORMS")
In [84]:
# Création d'une feuille
f2 <- createSheet(cls, sheetName = "MesFruits")
In [85]:
# Ajouter des données ç la feuille f1
addDataFrame(x = storms, sheet = f1, startRow = 2, startColumn = 2)
In [86]:
# Ajouter des données ç la feuille f2
addDataFrame(x = fruit, sheet = f2, startRow = 2, startColumn = 2)
In [87]:
# Ici overwrite = FALSE
saveWorkbook(cls, file = "MaBase.xlsx")
In [88]:
# Les feuilles du classeur excel
excel_sheets("MaBase.xlsx")
  1. 'STORMS'
  2. 'MesFruits'
In [89]:
# read_xls() and read_xlsx() 
dat <- read_excel(choose.files(), range = "STORMS!C2:G10")
In [ ]:
# Impoter un fichier excel
dat <- read_excel(choose.files(), sheet = 1, range = cell_rows(2:10))
In [91]:
# Package readxl
readxl_example()
  1. 'clippy.xls'
  2. 'clippy.xlsx'
  3. 'datasets.xls'
  4. 'datasets.xlsx'
  5. 'deaths.xls'
  6. 'deaths.xlsx'
  7. 'geometry.xls'
  8. 'geometry.xlsx'
  9. 'type-me.xls'
  10. 'type-me.xlsx'
In [92]:
# Parenthèse pour afficher malgré l'assignation
readxl_example("datasets.xlsx")
'C:/Users/ibtall/anaconda3/Lib/R/library/readxl/extdata/datasets.xlsx'
In [93]:
# Importer directement le fichier
system.file("extdata", "datasets.xlsx", package = "readxl")
'C:/Users/ibtall/anaconda3/Lib/R/library/readxl/extdata/datasets.xlsx'
In [94]:
# Les feuilles du classeur excel
excel_sheets(readxl_example("datasets.xlsx"))
  1. 'iris'
  2. 'mtcars'
  3. 'chickwts'
  4. 'quakes'
In [95]:
# Importer la feuille 1
dat <- read.xlsx(readxl_example("datasets.xlsx"), sheetIndex = 1)
In [96]:
# Importer la feuille mtcars
dat <- read_excel(readxl_example("datasets.xlsx"), sheet = "mtcars")
In [ ]:
# Objects crés
ls()
In [ ]:
# Tout supprimer sauf dat
rm(list = setdiff(ls(), "dat"))
In [ ]:
# Tout supprimer
rm(list = ls())
In [ ]:
# list.files(path = getwd()), dir()
list.files()
In [ ]:
# Supprimer les fichiers
file.remove(list.files())
In [ ]:
# Remonter sur le repertoire mère
setwd("..")
In [118]:
unlink("TPdir", recursive = TRUE)