# R for Absolute Beginners: Your First Hour of R ----
# Video 1 of the series R Programming: Zero to Expert.
# No experience needed. Type along with me!

# What is R? ----
# R is a free language built for working with data.
# People use it for analysis, charts, statistics and reports.

# A tour of RStudio ----
# Top left: this script, where we write and save our code.
# Bottom left: the Console, where R runs code and shows results.
# Top right: Environment. Bottom right: Files, Plots and more.

# R as a calculator ----
# Type a sum, run it, and R prints the answer.

2 + 3
10 - 4
6 * 7
20 / 8

2 ^ 3
5 ^ 2
100 ^ 0.5

# Order of operations
# Powers first, then * and /, then + and -. Brackets go first.

2 + 3 * 4
(2 + 3) * 4
10 - 2 ^ 2
(10 - 2) ^ 2

# Whole-number division and remainders
# %/% gives the whole number part, %% gives the remainder.

17 %/% 5
17 %% 5

# A film lasts 135 minutes. How many hours and minutes?
135 %/% 60
135 %% 60

10 %% 2
7 %% 2

# Dinner costs 86 dollars. Add a 15% tip, then split by 4
86 * 1.15
86 * 1.15 / 4

1500000 * 12
0.5 / 100000

# Comments ----
# Anything after # is a comment. R ignores it completely.
# Comments explain WHY your code does something.

# Coffee shop order: 3 lattes at 4.50 each
3 * 4.50
2 * 2.75  # plus 2 muffins
3 * 4.50 + 2 * 2.75  # the whole bill

# Pause and try it
# 1. A pizza is cut into 8 slices. 3 friends get equal whole slices.
# How many slices each, and how many are left over?
# 2. What is 5 plus 3, all multiplied by 2, then squared?

8 %/% 3
8 %% 3
((5 + 3) * 2) ^ 2

# Variables: giving values a name ----
# A variable is a labelled box that stores a value.
# We fill the box with the assignment arrow: a less-than and a dash.

latte_price <- 4.50
latte_price

cups_sold <- 120
revenue <- latte_price * cups_sold
revenue

# Overwriting a variable

latte_price <- 4.75
latte_price
revenue

revenue <- latte_price * cups_sold
revenue

cups_sold <- cups_sold + 10
cups_sold

tip = 2
tip

# Naming rules
# Names can use letters, numbers, dots and underscores.
# They must start with a letter, and cannot contain spaces.
# R is case sensitive: Price and price are different names.

monthly_rent <- 900
monthlyRent <- 950
monthly.rent <- 1000
monthly_rent
monthlyRent
monthly.rent

# Good names describe what is inside the box.
# total_cost is clear. x2 or tc are not.

2nd_place <- 50

second_place <- 50
place_2 <- 30
second_place + place_2

# Pause and try it
# Store your hourly pay and hours worked per week in variables.
# Then calculate your weekly pay, and your pay for 52 weeks.

hourly_pay <- 18.5
hours_per_week <- 38
weekly_pay <- hourly_pay * hours_per_week
yearly_pay <- weekly_pay * 52
weekly_pay
yearly_pay

# Data types ----
# Numbers, whole numbers, text, and TRUE or FALSE values.
# class() and typeof() tell us what type a value is.

temperature <- 23.5
class(temperature)
typeof(temperature)

customers <- 42
class(customers)
customers_int <- 42L
class(customers_int)
typeof(customers_int)

shop_name <- "Bean There"
shop_name
class(shop_name)
drink <- 'Cappuccino'
class(drink)

is_open <- TRUE
has_wifi <- FALSE
class(is_open)
typeof(has_wifi)

number_text <- "42"
class(number_text)

number_text + 8

# Converting between types
# as.numeric() turns text into a number.
# as.character() turns a number into text.

as.numeric(number_text) + 8
as.numeric("3.99")
as.character(2024)

as.integer(7.9)
as.numeric(TRUE)
as.numeric(FALSE)

as.numeric("hello")

as.numeric("$4.50")
as.numeric("4,500")

# Pause and try it
# Convert the text "15" to a number and multiply it by 3.
# What class is the value 3L? And the value FALSE?

as.numeric("15") * 3
class(3L)
class(FALSE)

# Vectors: many values in one variable ----
# A vector is an ordered list of values of the same type.
# We build one with c(), which stands for combine.

temps <- c(22, 25, 19, 28, 30, 27, 24)
temps

days <- c("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
days
open_late <- c(FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, FALSE)
open_late

mixed <- c(10, "apple", TRUE)
mixed
class(mixed)

# Shortcuts for building vectors
# The colon makes a run of whole numbers. seq() and rep() do more.

1:10
5:1
-2:2

seq(0, 100, by = 25)
seq(1, 2, by = 0.25)
seq(0, 1, length.out = 5)

rep("hello", times = 3)
rep(c(1, 2), times = 3)
rep(c(1, 2), each = 3)

# Vectorised arithmetic
# Maths on a vector is applied to every value at once.

temps + 1
temps * 2

# Celsius to Fahrenheit: multiply by 9/5, then add 32
temps_f <- temps * 9 / 5 + 32
temps_f

price <- c(4.50, 3.00, 5.25)
quantity <- c(2, 5, 1)
price * quantity

basket <- c(2.50, 1.20, 3.80, 7.50)
basket * 1.10
basket - 0.50

# Recycling
# R reuses the shorter vector until it matches the longer one.

c(1, 2, 3, 4) * 10
c(1, 2, 3, 4) * c(1, 10)

c(1, 2, 3, 4, 5) + c(10, 20)

# Pause and try it
# Make a vector of 5 prices: 2, 3.5, 4, 4.5 and 6.
# Then show the prices after a 10% discount.
# Bonus: use seq() to make the even numbers from 2 to 20.

menu_prices <- c(2, 3.5, 4, 4.5, 6)
menu_prices * 0.9
seq(2, 20, by = 2)

# Indexing: picking values out of a vector ----
# Square brackets after a name select values by position.
# R counts from 1, so the first value is at position 1.

temps
temps[1]
temps[5]
days[5]

temps[c(1, 7)]
temps[2:4]
days[6:7]

length(temps)
temps[length(temps)]

temps[10]

temps[-1]
temps[-c(6, 7)]

temps[c(TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE)]
days[open_late]

# Named vectors
# Each value in a vector can have a name, and we can index by it.

menu <- c(espresso = 3.00, latte = 4.50, mocha = 5.25)
menu
menu["latte"]
menu[c("espresso", "mocha")]

names(menu)
names(temps) <- days
temps
temps["Sat"]

menu["latte"] <- 4.75
menu[2]

# Pause and try it
# Make a named vector: Nairobi 24, London 12, Cairo 31 degrees.
# Show London, every city except the first, and cities above 20.

city_temps <- c(Nairobi = 24, London = 12, Cairo = 31)
city_temps["London"]
city_temps[-1]
city_temps[city_temps > 20]

# Built-in functions ----
# A function takes inputs, called arguments, and returns a result.
# You call it with its name and brackets: function_name(arguments).

sales <- c(120, 95, 140, 110, 180, 210, 160)
sum(sales)
mean(sales)
median(sales)

min(sales)
max(sales)
range(sales)
sd(sales)

round(3.14159)
round(3.14159, 2)
sqrt(144)
abs(-15)

round(sd(sales), 1)
abs(sales - mean(sales))

# Arguments by position and by name
# Arguments can be matched by their order, or by their name.

round(2.71828, 3)
round(x = 2.71828, digits = 3)
round(digits = 3, x = 2.71828)

seq(from = 10, to = 50, by = 10)
seq(10, 50, length.out = 3)

# Pause and try it
# Weekly spend on lunch: 8.5, 12, 7.25, 9.8, 15.
# Find the total, the average rounded to 2 decimals, and Wednesday.

lunch <- c(8.5, 12, 7.25, 9.8, 15)
sum(lunch)
round(mean(lunch), digits = 2)
lunch[3]

# Missing values: NA ----
# R marks a missing value with NA, meaning not available.

rainfall <- c(5, 0, NA, 12, 3, NA, 8)
rainfall
sum(rainfall)
mean(rainfall)

sum(rainfall, na.rm = TRUE)
mean(rainfall, na.rm = TRUE)
max(rainfall, na.rm = TRUE)

is.na(rainfall)
sum(is.na(rainfall))

rainfall == NA

# Logical comparisons ----
# Comparisons give TRUE or FALSE: >, <, >=, <=, == and !=.
# Note: == compares, while <- (or =) assigns.

5 > 3
5 < 3
4 >= 4
10 == 10
10 != 7

"latte" == "latte"
"Latte" == "latte"

sales
sales > 150
sales[sales > 150]

sum(sales > 150)
mean(sales > 150)

# Combining conditions: & | !
# & means AND (both true), | means OR (at least one true).
# ! means NOT, it flips TRUE to FALSE and FALSE to TRUE.

TRUE & FALSE
TRUE | FALSE
!TRUE

sales > 100 & sales < 150
sales[sales < 100 | sales > 200]
days[!open_late]

# which(), any() and all()
# which() gives positions, any() and all() summarise.

which(sales > 150)
days[which(sales > 150)]
which(sales == max(sales))

any(sales > 200)
all(sales > 100)
any(is.na(rainfall))

# Pause and try it
# Using temps: which days were 25 degrees or warmer?
# How many days were between 20 and 26? Were all days above 18?

temps[temps >= 25]
sum(temps >= 20 & temps <= 26)
all(temps > 18)

# Working with text ----
# paste() and paste0() glue text together.
# nchar(), toupper() and substr() measure and change text.

paste("Hello", "Mathew")
paste0("Hello", "Mathew")
paste("2026", "11", "02", sep = "-")

customer <- "Amina"
order_total <- 13.5
paste("Thank you,", customer, "- your total is", order_total)

paste0("$", order_total)
paste("Table", 1:4)

drink <- "Cappuccino"
nchar(drink)
toupper(drink)
tolower(drink)

substr(drink, 1, 3)
substr(drink, 4, 10)
toupper(substr(drink, 1, 3))

menu_items <- c("espresso", "latte", "flat white")
nchar(menu_items)
toupper(menu_items)

Toupper(drink)

# Pause and try it
# Store your first name, then print "Hi NAME!" in capitals.
# Also print how many letters your name has.

my_name <- "Mathew"
paste0("Hi ", toupper(my_name), "!")
nchar(my_name)

# A tiny interactive program ----
# readline() asks a question and waits for you to type an answer.
# The answer always comes back as text.

name <- readline("What is your name? ")
coffees <- readline("How many coffees do you buy a week? ")
coffees <- as.numeric(coffees)
weekly_cost <- coffees * 4.5
yearly_cost <- weekly_cost * 52
paste0("Hi ", name, "! Coffee costs you $", weekly_cost,
       " a week and $", yearly_cost, " a year.")

as.numeric(readline("Enter a temperature in Celsius: ")) * 9 / 5 + 32

# Your first plots ----
# plot() draws points or lines, hist() shows how values are spread.
# Charts appear in the Plots pane, bottom right.

plot(sales)

plot(1:7, sales,
     type = "b",
     col = "darkgreen",
     pch = 19,
     main = "Coffee sales this week",
     xlab = "Day of the week",
     ylab = "Cups sold")

plot(temps, sales,
     main = "Do warmer days sell more coffee?",
     xlab = "Temperature (C)", ylab = "Cups sold",
     pch = 19, col = "brown")

wait_times <- c(2, 4, 3, 5, 7, 3, 4, 6, 2, 8,
                5, 4, 3, 6, 9, 4, 5, 3, 4, 12,
                5, 6, 4, 3, 7, 5, 4, 6, 3, 5)
length(wait_times)
mean(wait_times)

hist(wait_times,
     col = "skyblue",
     main = "How long do customers wait?",
     xlab = "Waiting time (minutes)")

# Pause and try it
# Draw temps_f as red points joined by lines, with a title
# and labels for both axes.

plot(1:7, temps_f,
     type = "b", col = "red", pch = 19,
     main = "Temperatures this week (F)",
     xlab = "Day", ylab = "Degrees Fahrenheit")

# Common beginner errors ----
# Errors are normal. Read the message: it tells you what is wrong.

Sales

sales

total_tips

city <- Nairobi

city <- "Nairobi"
city

c(10 20 30)

c(10, 20, 30)

# Mini project: a monthly budget tracker ----
# Questions: How much do I spend? How much is left?
# Where does my money go, and what is my biggest expense?

# Monthly income after tax
income <- 2500

# Monthly expenses, named by category
expenses <- c(rent = 950, food = 420, transport = 160,
              phone = 45, utilities = 130,
              fun = 220, coffee = 90)
expenses

length(expenses)
total_spent <- sum(expenses)
total_spent
left_over <- income - total_spent
left_over

savings_rate <- left_over / income * 100
round(savings_rate, 1)
any(expenses > 500)
all(expenses > 0)

# Where does the money go?

pct_of_income <- round(expenses / income * 100, 1)
pct_of_income
sum(pct_of_income)

biggest <- names(which(expenses == max(expenses)))
biggest
smallest <- names(which(expenses == min(expenses)))
smallest

yearly <- expenses * 12
yearly
paste0("Biggest expense: ", biggest, ", ",
       pct_of_income[biggest], "% of income")

expenses[expenses > 200]
sort(expenses, decreasing = TRUE)

barplot(sort(expenses, decreasing = TRUE),
        col = "steelblue",
        main = "Where my money goes each month",
        ylab = "Dollars",
        las = 2)

# What if?
# What if we cut fun by 25% and coffee by half?

new_expenses <- expenses
new_expenses["fun"] <- expenses["fun"] * 0.75
new_expenses["coffee"] <- expenses["coffee"] * 0.5
new_expenses
income - sum(new_expenses)

extra_per_year <- (sum(expenses) - sum(new_expenses)) * 12
paste0("Small changes save $", extra_per_year, " a year!")

# Recap ----
# Calculator, comments, variables and the four basic data types.
# Vectors: c(), seq(), rep(), indexing, names and vectorised maths.
# Functions, NA values, comparisons, text, readline and plots.
# Errors are friends: read the message, check spelling and quotes.