Table of Contents


Books

R for Data Science (2e)

https://r4ds.hadley.nz/

Advanced R

http://adv-r.had.co.nz/

Big Data Analytics

https://umatter.github.io/BigData/

Mastering Software Development in R

https://bookdown.org/rdpeng/RProgDA/

R IDE’s

  1. Jupyter Notebooks
  2. RStudio
  3. Positron
  4. VSCODE

Fundamental libraries for data

img-20260819-100897.png

install.packages("tidyverse")
library(tidyverse)

R first steps

History and comments

> history() 
> # this is a comment
> ?c # help

Assigning Values

x = 3
x -> 3
x <- 3

R objects

Atomic Vector Types

  • Numeric (double)
  • Character (text)
  • Integer (10L)
  • Complex (2+3i)
  • Logical (TRUE / FALSE)

All atomic objects are vectors

# vectors
a <- 1
> a
[1] 1
class(a)
[1] "numeric"
 
a <- c(1, 2, 5, 3, 6, -2, 4)
[1]  1  2  5  3  6 -2  4
 
b <- c(1:50)
> b
[1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
[25] 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
[49] 49 50
 
x <- c(1,2)
class(x)
[1] "numeric"
 
> typeof(x)
[1] "double"
 
> as.integer(x)
[1] 1 2

Problem with floating points

> sqrt(2) ^ 2
[1] 2
> sqrt(2) ^ 2 == 2
[1] FALSE
> near(sqrt(2) ^ 2, 2)
[1] TRUE

Data Structures in R

Data structures in R are known as objects. Each object can hold vectors, scalars, matrices, arrays, data_frames, and lists

Matrix (2 dimensions)

> x <- matrix(1:9,nrow=3,ncol=3)
> x
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9
 
> x[2,]
[1] 2 5 8
 
> x[1:2,]
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
 
> x[,2:3]
     [,1] [,2]
[1,]    4    7
[2,]    5    8
[3,]    6    9

Arrays (multi-dimensions)

> z <- array(1:8, c(2,2,2))
> z
, , 1
 
     [,1] [,2]
[1,]    1    3
[2,]    2    4
 
, , 2
 
     [,1] [,2]
[1,]    5    7
[2,]    6    8
 

Data Frames
They are similar to data storage in Microsoft Excel, Stata, SAS, or SPSS

> id <- c(1,2,3)
> mon <- c('Jan', 'Fev', 'Mar')
> sales <- c(1500, 1700, 2300)
> salesData <- data.frame(id, mon, sales)
> salesData
  id mon sales
1  1 Jan  1500
2  2 Fev  1700
3  3 Mar  2300
 
> salesData$mon
[1] "Jan" "Fev" "Mar"
 
> salesData[2,]
  id mon sales
2  2 Fev  1700

Tibbles
A tibble is a modern reimagining of R’s traditional data.frame, built as part of the tidyverse ecosystem.

> tibble(a = 1:3, b = 4:6)
# A tibble: 3 × 2
      a     b
  <int> <int>
1     1     4
2     2     5
3     3     6

Predictable Subsetting

df <- data.frame(a = 1:3, b = 4:6)
tb <- tibble(a = 1:3, b = 4:6)
 
# Returning a single column
class(df[, 1]) # Returns "integer" (vector)
class(tb[, 1]) # Returns "tbl_df" "tbl" "data.frame"

Strict Matching via $

df <- data.frame(apple_count = 10)
tb <- tibble(apple_count = 10)
 
df$apple # Returns 10 (partial match)
tb$apple # Warning: Unknown column `apple`. Returns NULL
 

Sequential Variable Definition

# Fails in data.frame (Error: object 'a' not found)
data.frame(a = 1:3, b = a * 2) 
 
# Works natively in tibble
tibble(a = 1:3, b = a * 2)

Convert data.frames to tibbles

library(tibble)
 
# Sample base R data.frame with row names
df <- head(mtcars, 3)
#                    mpg cyl disp  hp
# Mazda RX4         21.0   6  160 110
# Mazda RX4 Wag     21.0   6  160 110
# Datsun 710        22.8   4  108  93
 
# 1. Basic conversion (drops row names completely)
tb_simple <- as_tibble(df)
# # A tibble: 3 × 4
#     mpg   cyl  disp    hp
#   <dbl> <dbl> <dbl> <dbl>
# 1  21       6   160   110
# ...
 
# 2. Preserve row names into an explicit column
tb_preserved <- as_tibble(df, rownames = "model")
# # A tibble: 3 × 5
#   model         mpg   cyl  disp    hp
#   <chr>       <dbl> <dbl> <dbl> <dbl>
# 1 Mazda RX4    21       6   160   110
# ...

Comparison of data.frames and tibbles

Feature / BehaviorBase R data.frameTidyverse tibble
Console PrintingPrints all rows and columns, easily flooding the console.Prints only the first 10 rows and fitting columns; explicitly shows column data types (, ).
Subsetting (df[, 1])Automatically simplifies to a vector unless drop = FALSE is passed.Always returns a 1-column tibble to preserve data structure.
Partial Matching(x automatically matches df$x_var if unique.Requires exact column name matching; gives a warning if the column does not exist.
Sequential Column CreationCannot reference newly defined columns within the same call.Allows referencing preceding columns directly (e.g., x = 1:5, y = x * 2).
Non-Syntactic NamesSilently renames variables with spaces or special characters (e.g., replaces spaces with .)Keeps irregular column names as-is using backticks (e.g., my column).
Row NamesNative support for row names.Discourages row names, preferring explicit data columns instead.

Lists
Lists allow you to specify and store any data type object

> myList <- list(title='Sales Resume', data=salesData)
> myList
$title
[1] "Sales Resume"
 
$data
  id mon sales
1  1 Jan  1500
2  2 Fev  1700
3  3 Mar  2300
 
> myList$data[1,2]
[1] "Jan"

Factor
A factor is an integer vector; each integer type has a label

> gender <- c('Male', 'Female')
> factor(gender)
[1] Male   Female
Levels: Female Male

Visualizing data

Generic X-Y plotting

> library(stats)
> library(graphics)
 
# Speed and Stopping Distances of Cars
> cars[1:5,]
  speed dist
1     4    2
2     4   10
3     7    4
4     7   22
5     8   16
 
 
> plot(cars, xlab = "Speed (mph)", ylab = "Stopping distance (ft)", las = 1)
lines(lowess(cars$speed, cars$dist, f = 2/3, iter = 3), col = "red")
title(main = "cars data")
 
# alterntive method
# plot(dist~speed, data=cars)

img-20260819-120827.png

ggplot grammar

# Example: Fuel economy data from 1999 to 2008 for 38 popular models of cars
# ?mpg
library(ggplot2)
 
> print(mpg, n=3)
# A tibble: 234 × 11
  manufacturer model displ  year   cyl trans     drv     cty   hwy fl    class
  <chr>        <chr> <dbl> <int> <int> <chr>     <chr> <int> <int> <chr> <chr>
1 audi         a4      1.8  1999     4 auto(l5)  f        18    29 p     comp…
3 audi         a4      2    2008     4 manual(m… f        20    31 p     comp…
 
ggplot(data=mpg, mapping = aes(x=displ , y=hwy)) + geom_point() + geom_smooth() + ggtitle('Fuel economy data for popular models of cars')

img-20260819-120841.png

Reading Data

Sample data from IPMA API
https://api.ipma.pt/

# Precipitação diária por concelho
# https://api.ipma.pt/open-data/observation/climate/precipitation/prec-p1d-continental-obssup-idw-concelhos-20d.csv
 
# reading data
> df <- read.csv(file='prec-p1d-continental-obssup-idw-concelhos-20d.csv')
 
# convert chr to dttm
> ymd_hms(df$time) -> df$time
 
# Using dplyr library and tidyverse piping
> filter(df, zid==1006) %>% select (time, mean_tp)
         time mean_tp
1  2026-07-30    0.00
2  2026-07-31    0.00
3  2026-08-01    0.00
4  2026-08-02    0.00
5  2026-08-03    0.71
6  2026-08-04    0.28
7  2026-08-05    0.00
8  2026-08-06    0.01
9  2026-08-07    0.01
10 2026-08-08    0.00
11 2026-08-09    0.00
12 2026-08-10    0.01
13 2026-08-11    0.01
14 2026-08-12    0.00
15 2026-08-13    0.00
16 2026-08-14    0.00
17 2026-08-15    0.00
18 2026-08-16    0.17
19 2026-08-17    0.00
20 2026-08-18    0.01
 
> filter(df, zid==1006) %>% select (time, mean_tp) %>% ggplot(aes(x=time, y=mean_tp)) + geom_point()

img-20260819-130855.png

Data Transformation with dplyr

Sample data

library(nycflights13)
library(tidyverse)
 
> flights
# A tibble: 336,776 × 19
    year month   day dep_time sched_dep_time dep_delay arr_time sched_arr_time arr_delay carrier flight
   <int> <int> <int>    <int>          <int>     <dbl>    <int>          <int>     <dbl> <chr>    <int>
 1  2013     1     1      517            515         2      830            819        11 UA        1545
 2  2013     1     1      533            529         4      850            830        20 UA        1714
 3  2013     1     1      542            540         2      923            850        33 AA        1141
 4  2013     1     1      544            545        -1     1004           1022       -18 B6         725
 5  2013     1     1      554            600        -6      812            837       -25 DL         461
 6  2013     1     1      554            558        -4      740            728        12 UA        1696
 7  2013     1     1      555            600        -5      913            854        19 B6         507
 8  2013     1     1      557            600        -3      709            723       -14 EV        5708
 9  2013     1     1      557            600        -3      838            846        -8 B6          79
10  2013     1     1      558            600        -2      753            745         8 AA         301
# ℹ 336,766 more rows
 
  • Pick observations by their values (filter()).
  • Reorder the rows (arrange()).
  • Pick variables by their names (select()).
  • Create new variables with functions of existing variables (mutate()).
  • Collapse many values down to a single summary (summarize()).

Filter

> filter(flights, month == 1, day == 1)
# A tibble: 842 × 19
    year month   day dep_time sched_dep_time dep_delay arr_time sched_arr_time arr_delay carrier flight
   <int> <int> <int>    <int>          <int>     <dbl>    <int>          <int>     <dbl> <chr>    <int>
 1  2013     1     1      517            515         2      830            819        11 UA        1545
 2  2013     1     1      533            529         4      850            830        20 UA        1714
 3  2013     1     1      542            540         2      923            850        33 AA        1141
 4  2013     1     1      544            545        -1     1004           1022       -18 B6         725
 5  2013     1     1      554            600        -6      812            837       -25 DL         461
 6  2013     1     1      554            558        -4      740            728        12 UA        1696
 7  2013     1     1      555            600        -5      913            854        19 B6         507
 8  2013     1     1      557            600        -3      709            723       -14 EV        5708
 9  2013     1     1      557            600        -3      838            846        -8 B6          79
10  2013     1     1      558            600        -2      753            745         8 AA         301
 
# logical operators
> > filter(flights, (month==2 | month==4) & dep_time==540) 
> 

Arrange

> arrange(flights, flight, carrier, day)
# A tibble: 336,776 × 19
    year month   day dep_time sched_dep_time dep_delay arr_time sched_arr_time arr_delay carrier flight
   <int> <int> <int>    <int>          <int>     <dbl>    <int>          <int>     <dbl> <chr>    <int>
 1  2013     1     1      856            900        -4     1226           1220         6 AA           1
 2  2013    10     1      903            910        -7     1147           1220       -33 AA           1
 3  2013    11     1      925            910        15     1606           1220        NA AA           1
 4  2013    12     1      856            900        -4     1212           1225       -13 AA           1
 5  2013     2     1      859            900        -1     1251           1220        31 AA           1
 6  2013     3     1      903            900         3     1157           1220       -23 AA           1
 7  2013     4     1      855            900        -5     1246           1220        26 AA           1
 8  2013     5     1      858            900        -2     1127           1225       -58 AA           1
 9  2013     6     1      900            900         0     1146           1225       -39 AA           1
10  2013     7     1      912            915        -3     1209           1210        -1 AA           1

Select

> select(flights, year, month, day)
# A tibble: 336,776 × 3
    year month   day
   <int> <int> <int>
 1  2013     1     1
 2  2013     1     1
 3  2013     1     1
 4  2013     1     1
 5  2013     1     1
 6  2013     1     1
 7  2013     1     1
 8  2013     1     1
 9  2013     1     1
10  2013     1     1
# ℹ 336,766 more rows

Mutate

> flights_sml <- select(flights,
    year:day,
    ends_with("delay"),
	distance,
	air_time 
	)
 
> mutate(flights_sml,
  gain = arr_delay - dep_delay,
  speed = distance / air_time * 60
  )
# A tibble: 336,776 × 9
    year month   day dep_delay arr_delay distance air_time  gain speed
   <int> <int> <int>     <dbl>     <dbl>    <dbl>    <dbl> <dbl> <dbl>
 1  2013     1     1         2        11     1400      227     9  370.
 2  2013     1     1         4        20     1416      227    16  374.
 3  2013     1     1         2        33     1089      160    31  408.
 4  2013     1     1        -1       -18     1576      183   -17  517.
 5  2013     1     1        -6       -25      762      116   -19  394.
 6  2013     1     1        -4        12      719      150    16  288.
 7  2013     1     1        -5        19     1065      158    24  404.
 8  2013     1     1        -3       -14      229       53   -11  259.
 9  2013     1     1        -3        -8      944      140    -5  405.
10  2013     1     1        -2         8      733      138    10  319.
 
# If you only want to keep the new variables, use transmute()
> transmute(flights,
+           gain = arr_delay - dep_delay,
+           hours = air_time / 60,
+           gain_per_hour = gain / hours
+ )
# A tibble: 336,776 × 3
    gain hours gain_per_hour
   <dbl> <dbl>         <dbl>
 1     9 3.78           2.38
 2    16 3.78           4.23
 3    31 2.67          11.6 
 4   -17 3.05          -5.57
 5   -19 1.93          -9.83
 6    16 2.5            6.4 
 7    24 2.63           9.11
 8   -11 0.883        -12.5 
 9    -5 2.33          -2.14
10    10 2.3            4.35
# ℹ 336,766 more rows
# ℹ Use `print(n = ...)` to see more rows

Summarize

> summarize(flights, delay = mean(dep_delay, na.rm = TRUE))
# A tibble: 1 × 1
  delay
  <dbl>
1  12.6

With group_by

> by_mon <- group_by(flights, month)
> summarize(by_mon, delay = mean(dep_delay, na.rm = TRUE))
# A tibble: 12 × 2
   month delay
   <int> <dbl>
 1     1 10.0 
 2     2 10.8 
 3     3 13.2 
 4     4 13.9 
 5     5 13.0 
 6     6 20.8 
 7     7 21.7 
 8     8 12.6 
 9     9  6.72
10    10  6.24
11    11  5.44

Piping

flights %>% filter(month > 7) %>% 	
	summarize(
	    count = n(),
	    dist = mean(distance, na.rm = TRUE),
	    delay = mean(arr_delay, na.rm = TRUE)
	)
	
# A tibble: 1 × 3
   count  dist delay
   <int> <dbl> <dbl>
1 141193 1052.  3.43
 
# Example: plot not canceled flights delay time
not_cancelled <- flights %>%
	filter(!is.na(dep_delay), !is.na(arr_delay))
 
not_cancelled %>%
	group_by(year, month, day) %>%
	summarize(mean = mean(dep_delay))
	
delays <- not_cancelled %>%
	group_by(tailnum) %>%
	summarize(
	   delay = mean(arr_delay)
	)
	
ggplot(data = delays, mapping = aes(x = delay)) +
	geom_freqpoly(binwidth = 10)

R stripts

Requirements

install.packages("argparse")

Python path tmust be on your user path

img-20260819-170863.png

pip install simplejson
pip freeze
simplejson
 
# see env variables
echo %path%

plot-script.r

#!/usr/bin/Rscript
# options(python_cmd="c:/users/.../python")
# options(warn=-1)
suppressPackageStartupMessages(library("tidyverse"))
suppressPackageStartupMessages(library("argparse"))
 
parser <- ArgumentParser(description = "Plot fuel consumption by hp")
parser$add_argument("-m", "--manufacturer", type = "character", default="bmw",
                    help = "car manufacturer")
parser$add_argument("-l", "--list", action = "store_true", 
                    default=FALSE, help = "list all manufacturer")
 
args <- parser$parse_args()
 
cat('\nStarting plot app\n')
 
 
if (args$list) {
  print(mpg %>% select(manufacturer) %>% unique())
  quit(save="no")
}
 
cat(paste0('Selecting manufactor: ', args$manufacturer, '\n'))
 
select(mpg, manufacturer, model, displ, hwy) %>% 
  filter (manufacturer == args$manufacturer) %>%
  ggplot(aes(x=displ, y=hwy)) + geom_point() + 
    geom_smooth(method = "loess", formula = y ~ x)
ggsave(filename='plot.png')
 

Running

Rscript plot-script.R