Lesson 1 · R Programming: Zero to Expert
Learn R Programming from Scratch: Full Beginner Course in RStudio | R 101
R Programming: Zero to Expert. No experience needed. Type along with me! R script: 01rbasics.R. Download it from this page and open it in RStudio, or run…
- CourseR Programming: Zero to Expert
- Lesson1 of 6
- Video1 h 9 min
- FormatR script + Jupyter notebook (R) · 107 code cells
What you'll learn
Files for this lesson
Save these in one folder, open the script in RStudio and set that folder as the working directory (Session → Set Working Directory → To Source File Location).
- 01_r_basics.R12.7 KB
📓 Full notebook
Download .ipynbR 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!
R script: 01_r_basics.R. Download it from this page and open it in RStudio, or run this notebook with an R kernel (for example in Google Colab: Runtime → Change runtime type → R).
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
Look at the Console. We get five, six, forty two, and two point five. Notice the little one in square brackets before each answer. It just means this is the first value in the result. We'll see why that matters soon.
2 ^ 3
5 ^ 2
100 ^ 0.5
Two cubed is eight, five squared is twenty five, and one hundred to the power of a half is ten.
Order of operations#
Powers first, then * and /, then + and -. Brackets go first.
2 + 3 * 4
(2 + 3) * 4
10 - 2 ^ 2
(10 - 2) ^ 2
Without brackets we get fourteen, but with brackets we get twenty. Same numbers, different answer. Ten minus two squared is six, while ten minus two, all squared, is sixty four.
Whole-number division and remainders#
%/% gives the whole number part, %% gives the remainder.
17 %/% 5
17 %% 5
Five fits into seventeen three whole times, with two left over. So we get three and then two.
# A film lasts 135 minutes. How many hours and minutes?
135 %/% 60
135 %% 60
Two hours and fifteen minutes. This trick turns up all the time with times, dates and money.
10 %% 2
7 %% 2
Ten leaves zero, so ten is even. Seven leaves one, so seven is odd.
# Dinner costs 86 dollars. Add a 15% tip, then split by 4
86 * 1.15
86 * 1.15 / 4
The bill with the tip is ninety eight dollars ninety, and each friend pays twenty four point seven two five. R shows all the decimals it has. We'll learn how to round to cents in a little while.
1500000 * 12
0.5 / 100000
R prints one point eight e plus zero seven. That's scientific notation, meaning one point eight times ten to the power of seven, or eighteen million. And the small one is five e minus zero six, which is five millionths. Don't panic when you see an e in a number, it's just a compact way to write it.
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
The lattes cost thirteen fifty, the muffins five fifty, and the whole bill is nineteen dollars. R ran the sums but printed nothing for the comments. They're only there for us.
Pause and try it#
A pizza is cut into 8 slices. 3 friends get equal whole slices.
How many slices each, and how many are left over?
What is 5 plus 3, all multiplied by 2, then squared?
8 %/% 3
8 %% 3
((5 + 3) * 2) ^ 2
Each friend gets two slices, and two slices are left over. Maybe for the person who wrote the code. Five plus three is eight, times two is sixteen, and sixteen squared is two hundred fifty six.
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
The Console prints four point five. Notice that R drops the trailing zero. The value is the same. Now look at the Environment pane on the top right. Our variable latte price has appeared there, with its value.
cups_sold <- 120
revenue <- latte_price * cups_sold
revenue
Five hundred and forty dollars. R looked inside both boxes, multiplied the values, and stored the answer.
Overwriting a variable#
latte_price <- 4.75
latte_price
revenue
The latte price is now four point seven five. The old value is gone, replaced without any warning. But revenue is still five hundred and forty. It was calculated with the old price, and R doesn't recalculate it automatically.
revenue <- latte_price * cups_sold
revenue
Now revenue is five hundred and seventy dollars, using the new price.
cups_sold <- cups_sold + 10
cups_sold
One hundred and thirty. Ten more cups were sold, and we updated our count.
tip = 2
tip
Tip holds the value two, exactly as if we had used the arrow.
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
We get nine hundred, nine hundred fifty, and one thousand. Three separate boxes.
Good names describe what is inside the box.
total_cost is clear. x2 or tc are not.
2nd_place <- 50
R gives an error saying unexpected symbol. It can't make sense of a name that starts with a number.
This one is meant to fail, so you can see the error message.
second_place <- 50
place_2 <- 30
second_place + place_2
No errors this time, and the sum is eighty.
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
Seven hundred and three dollars a week, and thirty six thousand five hundred and fifty six dollars a year. Your numbers will be different, and that's perfect. What matters is the pattern: store inputs, then calculate with them.
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)
Class says numeric, and type of says double. Double is the computer science name for a number with decimals.
customers <- 42
class(customers)
customers_int <- 42L
class(customers_int)
typeof(customers_int)
Surprise! Plain forty two is still numeric. R treats every number as a decimal number by default. With the capital L, the class becomes integer. For everyday work you rarely need the L, but you'll see it in other people's code.
shop_name <- "Bean There"
shop_name
class(shop_name)
drink <- 'Cappuccino'
class(drink)
R prints the name with double quotes around it, a reminder that it's text. Both classes say character.
is_open <- TRUE
has_wifi <- FALSE
class(is_open)
typeof(has_wifi)
Both say logical. These yes or no values look simple, but they're the secret behind filtering data, as we'll see later.
number_text <- "42"
class(number_text)
It's character. Quotes always mean text, even when what's inside looks like a number.
number_text + 8
R refuses, with the message non numeric argument to binary operator. In plain English: I can't do maths with text.
This one is meant to fail, so you can see the error message.
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)
Now we get fifty, a real number. The price text becomes three point nine nine. And twenty twenty four is printed with quotes, because it's now character.
as.integer(7.9)
as.numeric(TRUE)
as.numeric(FALSE)
Seven point nine becomes seven, not eight. It's chopped, not rounded. True gives one and false gives zero.
as.numeric("hello")
R gives back N A, with a warning saying N A's introduced by coercion. N A means not available, R's way of saying a value is missing. Coercion is just the fancy word for conversion.
as.numeric("$4.50")
as.numeric("4,500")
Both become N A with a warning. R only understands plain digits and a decimal point, so symbols and commas break the conversion.
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)
Fifteen times three is forty five. Three L is an integer, and false is logical. Well done if you got all three.
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
All seven temperatures are printed in order, from twenty two up to twenty four. In the Environment pane, temps shows num, meaning numeric, then one to seven, telling us it holds seven values.
days <- c("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
days
open_late <- c(FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, FALSE)
open_late
We see the seven day names in quotes, and seven true or false values. The shop stays open late Thursday to Saturday.
mixed <- c(10, "apple", TRUE)
mixed
class(mixed)
Everything has become text! Ten and true now have quotes around them, and the class is character. A vector can only hold one type, so R converts everything to the most flexible type, which is text.
Shortcuts for building vectors#
The colon makes a run of whole numbers. seq() and rep() do more.
1:10
5:1
-2:2
We get one to ten, then five, four, three, two, one, and then minus two up to two.
seq(0, 100, by = 25)
seq(1, 2, by = 0.25)
seq(0, 1, length.out = 5)
Zero, twenty five, fifty, seventy five, one hundred. Then one up to two in quarter steps. And five evenly spaced values from zero to one: zero, a quarter, a half, three quarters, and one.
rep("hello", times = 3)
rep(c(1, 2), times = 3)
rep(c(1, 2), each = 3)
Hello three times. Then one two, one two, one two, and finally one one one, two two two.
Vectorised arithmetic#
Maths on a vector is applied to every value at once.
temps + 1
temps * 2
Every one of the seven temperatures went up by one, then every value was doubled. One short line did seven calculations.
# Celsius to Fahrenheit: multiply by 9/5, then add 32
temps_f <- temps * 9 / 5 + 32
temps_f
Twenty two Celsius is seventy one point six Fahrenheit, and our hottest day, thirty degrees, is eighty six Fahrenheit.
price <- c(4.50, 3.00, 5.25)
quantity <- c(2, 5, 1)
price * quantity
We get nine, fifteen, and five point two five. That's the cost of each line on the receipt.
basket <- c(2.50, 1.20, 3.80, 7.50)
basket * 1.10
basket - 0.50
With tax the prices become two seventy five, one thirty two, four eighteen and eight twenty five. And with the coupon, every item is fifty cents cheaper. One line, four prices updated.
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)
The first gives ten, twenty, thirty, forty. In the second, one is used, then ten, then one, then ten again. So we get one, twenty, three, forty.
c(1, 2, 3, 4, 5) + c(10, 20)
R still gives an answer, eleven, twenty two, thirteen, twenty four, fifteen, but with a warning. It says the longer object length is not a multiple of the shorter object length.
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)
The discounted prices are one eighty, three fifteen, three sixty, four oh five, and five forty. And the even numbers run from two to twenty, ten values in total.
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]
Monday was twenty two degrees, Friday was thirty, and the fifth day is indeed Fri.
temps[c(1, 7)]
temps[2:4]
days[6:7]
We get twenty two and twenty four for Monday and Sunday, then twenty five, nineteen, twenty eight. And the weekend days, Sat and Sun.
length(temps)
temps[length(temps)]
Seven values, and the last one is twenty four. This trick works whatever length the vector is.
temps[10]
R doesn't give an error. It returns N A, because there is nothing stored there.
temps[-1]
temps[-c(6, 7)]
The first result has six values, Monday is gone. The second has five values, Monday to Friday.
temps[c(TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE)]
days[open_late]
The first line keeps positions one, three, five and seven, so we get twenty two, nineteen, thirty and twenty four. And using the logical vector gives Thu, Fri and Sat, the days that are true. We'll use this idea a lot.
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")]
The names are printed above the values, like a little price list. The latte costs four fifty. And picking two names gives espresso at three, and mocha at five twenty five.
names(menu)
names(temps) <- days
temps
temps["Sat"]
Names gives espresso, latte and mocha. Now every temperature has its day printed above it. And Saturday was twenty seven degrees.
menu["latte"] <- 4.75
menu[2]
The latte now costs four seventy five, and the other prices are untouched.
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]
London is twelve degrees. Dropping the first city leaves London and Cairo. And the cities above twenty are Nairobi and Cairo. Notice the names travel with the values every time.
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)
We sold one thousand and fifteen cups in total, an average of one hundred forty five cups a day. The median is one hundred forty. If you sort the seven values, one hundred forty sits right in the middle.
min(sales)
max(sales)
range(sales)
sd(sales)
The quietest day had ninety five cups, the busiest had two hundred and ten, and range gives both together. The standard deviation is about forty one. Roughly speaking, a typical day is around forty cups away from the average.
round(3.14159)
round(3.14159, 2)
sqrt(144)
abs(-15)
We get three, then three point one four, then twelve, and fifteen.
round(sd(sales), 1)
abs(sales - mean(sales))
The standard deviation, rounded to one decimal, is forty point nine. And each day's distance from the average: twenty five, fifty, five, thirty five, thirty five, sixty five, and fifteen.
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)
All three give exactly the same answer, two point seven one eight.
seq(from = 10, to = 50, by = 10)
seq(10, 50, length.out = 3)
Ten, twenty, thirty, forty, fifty. And three evenly spaced values: ten, thirty, fifty.
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]
I spent fifty two dollars fifty five in total, an average of ten fifty one a day. And Wednesday's lunch cost seven twenty five. A cheap day!
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)
Both the sum and the mean come back as N A. Can you guess why? R is being honest. If two days are unknown, the true total is also unknown. It could be anything.
sum(rainfall, na.rm = TRUE)
mean(rainfall, na.rm = TRUE)
max(rainfall, na.rm = TRUE)
Now we get a total of twenty eight millimetres from the five known days, an average of five point six, and a maximum of twelve.
is.na(rainfall)
sum(is.na(rainfall))
We get true in positions three and six, and summing them tells us two values are missing.
rainfall == NA
Every result is N A! Asking whether something equals an unknown value gives an unknown answer. So always use is dot N A to find missing values, never double equals.
Logical comparisons#
Comparisons give TRUE or FALSE: >, <, >=, <=, == and !=.
Note: == compares, while <- (or =) assigns.
5 > 3
5 < 3
4 >= 4
10 == 10
10 != 7
True, false, true, true, and true. Each comparison gives a single logical value.
"latte" == "latte"
"Latte" == "latte"
The first is true, but the second is false. A capital L makes it a different word in R's eyes.
sales
sales > 150
sales[sales > 150]
Sales above one hundred fifty gives false for the first four days, then true, true, true. And indexing with that gives us just the busy days: one hundred eighty, two hundred ten, and one hundred sixty.
sum(sales > 150)
mean(sales > 150)
Three busy days, which is a proportion of about zero point four three, or forty three percent of the week.
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
And gives false, because only one is true. Or gives true, because one is enough. And not true is false.
sales > 100 & sales < 150
sales[sales < 100 | sales > 200]
days[!open_late]
Days one, three and four fall in the middle range, so they're true. The unusual days sold ninety five and two hundred ten cups. And the shop closes early Monday, Tuesday, Wednesday and Sunday.
which(), any() and all()#
which() gives positions, any() and all() summarise.
which(sales > 150)
days[which(sales > 150)]
which(sales == max(sales))
Positions five, six and seven, which are Friday, Saturday and Sunday. The best day was position six, Saturday.
any(sales > 200)
all(sales > 100)
any(is.na(rainfall))
Yes, one day passed two hundred. But not every day passed one hundred, because of that quiet ninety five cup day. And yes, rainfall does contain missing values.
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)
Tuesday, Thursday, Friday and Saturday were twenty five or warmer. Three days were between twenty and twenty six, and yes, every day was above eighteen degrees.
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 = "-")
We get Hello Mathew with a space, then HelloMathew squashed together, and finally twenty twenty six, dash, eleven, dash, zero two.
customer <- "Amina"
order_total <- 13.5
paste("Thank you,", customer, "- your total is", order_total)
The message reads: Thank you, Amina, dash, your total is thirteen point five. Notice that paste happily converted the number to text for us.
paste0("$", order_total)
paste("Table", 1:4)
We get the dollar sign right next to thirteen point five, then four labels: Table one, Table two, Table three and Table four.
drink <- "Cappuccino"
nchar(drink)
toupper(drink)
tolower(drink)
Cappuccino has ten characters. Then we see it all in capitals, and all in lower case.
substr(drink, 1, 3)
substr(drink, 4, 10)
toupper(substr(drink, 1, 3))
We get Cap, then puccino, and finally the code C A P in capitals. Handy for product codes.
menu_items <- c("espresso", "latte", "flat white")
nchar(menu_items)
toupper(menu_items)
Espresso has eight characters, latte five, and flat white ten. Notice the space counts as a character too.
Toupper(drink)
R says could not find function Toupper. Function names are case sensitive, just like variable names.
This one is meant to fail, so you can see the error message.
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)
We get Hi MATHEW with an exclamation mark, and my name has six letters.
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.")
We answered Mathew and ten. So the program says: Hi Mathew! Coffee costs you forty five dollars a week, and two thousand three hundred forty dollars a year. That's a lot of coffee money. Maybe our budget tracker will help with that later!
This step asks for input; in the video we answered: Mathew, 10.
as.numeric(readline("Enter a temperature in Celsius: ")) * 9 / 5 + 32
We typed thirty five, and R converted it to ninety five degrees Fahrenheit.
This step asks for input; in the video we answered: 35.
Your first plots#
plot() draws points or lines, hist() shows how values are spread.
Charts appear in the Plots pane, bottom right.
plot(sales)
A chart appears in the Plots pane, with seven points. The horizontal axis is labelled index, which is just the position, one to seven. The vertical axis shows the sales. You can see the dip on day two, and the peak on day six.
plot(1:7, sales,
type = "b",
col = "darkgreen",
pch = 19,
main = "Coffee sales this week",
xlab = "Day of the week",
ylab = "Cups sold")
Now we have a proper line chart, with dark green points joined by lines, a title, and clear axis labels. The weekend rise is obvious. Sales climb from Friday, peak at two hundred ten on Saturday, then drop a little on Sunday.
plot(temps, sales,
main = "Do warmer days sell more coffee?",
xlab = "Temperature (C)", ylab = "Cups sold",
pch = 19, col = "brown")
This is a scatter plot. Each point is one day. The warmest days, around twenty seven to thirty degrees, have the highest sales. So in this little made up week, warmer days do seem to sell more coffee. Maybe people are out and about more.
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)
We have thirty values, and the average wait is exactly four point nine minutes.
hist(wait_times,
col = "skyblue",
main = "How long do customers wait?",
xlab = "Waiting time (minutes)")
Most customers wait between two and six minutes, which is where the tallest bars are. On the right there's a long, thin tail, including one customer who waited twelve minutes. That's the outlier the manager should look into.
plot(1:7, temps_f,
type = "b", col = "red", pch = 19,
main = "Temperatures this week (F)",
xlab = "Day", ylab = "Degrees Fahrenheit")
We get a red line chart. The temperature dips to sixty six point two on day three, then climbs to a peak of eighty six on day five.
Common beginner errors#
Errors are normal. Read the message: it tells you what is wrong.
Sales
R says object Sales not found. We created sales with a small s, and to R, capital S Sales is a completely different name.
This one is meant to fail, so you can see the error message.
sales
Now it works. When you see object not found, check the spelling, the capitals, and that you actually ran the line that created it.
total_tips
Object total tips not found. This often happens when you write a line in the script but forget to run it.
This one is meant to fail, so you can see the error message.
city <- Nairobi
Again, object not found. Without quotes, R thinks Nairobi is the name of a variable, and goes looking for it.
This one is meant to fail, so you can see the error message.
city <- "Nairobi"
city
Now city holds the text Nairobi. Quotes are the difference between a name and a value.
c(10 20 30)
R says unexpected numeric constant. It found a number where it expected a comma or a closing bracket.
This one is meant to fail, so you can see the error message.
c(10, 20, 30)
We get ten, twenty, thirty, exactly as intended.
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
We see each category name above its amount, from rent at nine fifty down to coffee at ninety. In the Environment pane, income and expenses have both appeared, ready to use.
length(expenses)
total_spent <- sum(expenses)
total_spent
left_over <- income - total_spent
left_over
Seven categories, two thousand and fifteen dollars spent, which leaves four hundred and eighty five dollars at the end of the month.
savings_rate <- left_over / income * 100
round(savings_rate, 1)
any(expenses > 500)
all(expenses > 0)
We save nineteen point four percent of our income. That's a healthy number. Yes, at least one category is over five hundred, and yes, every expense is positive, so our data looks sensible.
Where does the money go?#
pct_of_income <- round(expenses / income * 100, 1)
pct_of_income
sum(pct_of_income)
Rent takes thirty eight percent of our income, food sixteen point eight percent, and coffee three point six percent. Together they add up to eighty point six percent. The rest is what we save.
biggest <- names(which(expenses == max(expenses)))
biggest
smallest <- names(which(expenses == min(expenses)))
smallest
The biggest expense is rent, which is no surprise, and the smallest is the phone bill.
yearly <- expenses * 12
yearly
paste0("Biggest expense: ", biggest, ", ",
pct_of_income[biggest], "% of income")
Over a year, rent costs eleven thousand four hundred dollars, and even coffee adds up to one thousand and eighty. And our sentence says: Biggest expense, rent, thirty eight percent of income.
expenses[expenses > 200]
sort(expenses, decreasing = TRUE)
Rent, food and fun are each over two hundred dollars. And sorted, the order is rent, food, fun, transport, utilities, coffee, and finally phone.
barplot(sort(expenses, decreasing = TRUE),
col = "steelblue",
main = "Where my money goes each month",
ylab = "Dollars",
las = 2)
Each bar is one category, from tallest to shortest. The names come from the named vector automatically. Rent towers over everything else. It's even more than food, fun and transport put together.
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)
Fun drops to one hundred sixty five, and coffee to forty five. Everything else stays the same. Now we have five hundred and eighty five dollars left every month, one hundred dollars more than before.
extra_per_year <- (sum(expenses) - sum(new_expenses)) * 12
paste0("Small changes save $", extra_per_year, " a year!")
Small changes save one thousand two hundred dollars a year! Not bad for a few less coffees.
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.
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



