Introduction to Data Science
Lecture 3B - Introduction to R Programming
Assa Mulagha-Maganga, PhD Econ
Department of Applied Economics
Lilongwe University of Agriculture and Natural Resources
Monday 09 December, 2024
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
1 / 60
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
2 / 60
Table of contents
1 Introduction
2 Initial settings
3 File paths
4 Using packages
5 Functions inception
6 Mapping and iterations
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
3 / 60
Introduction
What this session is about
In the first session, you learned how to work with R
You are probably eager to start programming in R by now
But before you start, we recommend learning how to write R code
that will be reproducible, efficient, intelligible and easy to
navigate
Indeed, that’s what this session is about!
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
4 / 60
What this session is about
We will cover common coding practices in R so that you can make
the most efficient use for it
We will also discuss some styling conventions to make your code
readable and reproducible
This will give you a solid foundation to write code in R and hopefully
you’ll be able to skip some painful steps of the
“getting-your-hands-dirty” learning approach
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
5 / 60
Initial settings
Let’s start by opening RStudio or by closing and opening it again
Notice two things:
1 Your environment is probably empty (it’s okay if it’s not)
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
6 / 60
Initial settings
Let’s start by opening RStudio or by closing and opening it again
Notice two things:
1 Your environment is probably empty (it’s OK if it’s not)
2 Go to the Console panel and use the up and down keys to navigate
through previously executed commands. They are saved by default in a
file named .Rhistory that you might have noticed
We’d usually want these two things – an empty environment and
the history of commands executed in previous sessions – to be
present every time we open a new RStudio session
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
7 / 60
File paths
setwd("your/path")
However, we recommend not using it unless it’s absolutely necessary
(never, if possible)
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
8 / 60
Packages
Since there is a lot of people developing for R, it can have many
different functionalities
To make it simpler, these functionalities are bundled into packages
A package is just a unit of shareable code
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
9 / 60
Packages
Packages may contain new functions, but also more complex
functionalities, such as a Graphic User Interface (GUI) or settings for
parallel processing (similar to Stata MP)
They are usually shared through R’s official repository - CRAN
(19,000+ packages reviewed and tested)
There are many other online sources such as GitHub, but it’s
important to be careful, as these probably haven’t gone through a
review process as rigorous as those in CRAN
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
10 / 60
Packages
To install and use packages you can either do it with the user
interface or by the command prompt.
# Installing a package
[Link]("dplyr",
dependencies = TRUE)
# the dependencies argument also installs all other packages
# that it may depend upon to run
You only have to install a package once, but you have to load them
every new session.
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
11 / 60
Using packages
Exercise 2.1 ( 1 min)
1 Load the packages dplyr and purrr in part 1 of your script using
library(dplyr) and library(purrr)
1 Run your script
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
12 / 60
Warnings vs errors
What if this happens?
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
13 / 60
Warnings vs errors
R has two types of error messages, warnings and actual errors:
Errors - break your code, usually preventing it from running
Warnings - your code kept running, but R wants you to be aware of
something that might be a problem later
RStudio’s default is to print warning messages, but not to stop the code at
the lines where they occur. You can configure R to stop at warnings if you
want.
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
14 / 60
A function inside a function
In R, you can write one function inside another
In fact, you have already done this several times in this course
Here’s an example:
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
15 / 60
A function inside a function
# Print the summary of the logarithm of the age score
## The long way:
log_score <- log(titanic$Age)
summary(log_score)
# The shortcut
summary(log(titanic$Age))
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
16 / 60
A function inside a function
This is a simple example of metaprogramming (that’s the real name
of this technique) and may seem trivial, but it’s not
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
17 / 60
A function inside a function
Metaprogramming is a very powerful technique, as you will soon see
It’s also a common source of error, as you can only use one
function inside the other if the output of the inner function can be
taken as the input of the outer function
It can also get quite tricky to follow what a line of code with multiple
functions inceptions is doing
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
18 / 60
Piping
Ever heard of piping? It’s this: %>%
Piping is a way of doing metaprogramming
The actual meaning of the pipes is: Pipes take the output of the
function at the left and pass it as the first argument of the function
at the right
The advantages of using piping is that it allows to have a cleaner
division of successively applied functions in R code, drastically
improving code readability
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
19 / 60
Piping
# 1: Doing it the long way -----------------------------
log_score <- log(titanic$Age)
mean(log_score)
# 2: Shortcut to get to the same place -----------------
mean(log(titanic$Age))
# 3: Now with pipes ------------------------------------
titanic$Age %>%
log() %>%
mean()
Just remember:
x %>% f() is the same as f(x)
x %>% f() %>% g() is the same as g(f(x))
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
20 / 60
Iterations in R
In R, the syntax of for loops is:
for (number in 1:3) {
print(number)
}
## [1] 1
## [1] 2
## [1] 3
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
21 / 60
Map
R, however, has a set of functions that allows users to loop through
an object in a more efficient way, without using explicit loops
In this training we’ll introduce map(). It is a function part of purrr,
a package that contains tools for functional programming
Also, in case you have not noticed yet: R is vectorized! this means
that many operations are applied element-wise by default so you don’t
have to code loops to apply them to each element of a vector or
dataframe
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
22 / 60
Map
To use map(), you need to load the package purrr
The basic syntax of map() is:
map(X, function, ...): applies function to each of the elements
of X. If X is a dataframe then function is applied column-wise while
if it’s a vector or a list it is applied item-wise. The output of map() is
always a list with the results.
X: a dataframe, matrix or vector the function will be applied to
function: the name of the function you want to apply to each of the
elements of X
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
23 / 60
Map
# Round the values of the following vector
x <- c(1.2, 2.5, 9.1, 5.8)
x %>% map(round) # Rounding the vector elements (same as map(x
round(x) # since R is vectorized, this also works
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
24 / 60
Map vs looping
When looping, you repeat the same operation over a set of items
map(), instead, takes all your elements at once and applies an
operation to them simultaneously
The difference is like this:
Imagine you ask a yes/no question to a group of people
You can collect the answers by asking each one of them individually –
this is looping
Otherwise, you can ask them to raise their hands and collect all
answers at once – this is map()
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
25 / 60
Map vs looping
The output of a loop is the regular output of the operation you’re
repeating, times the number of iterations you did
The output of map() will be always a list
When it comes to code clarity, map() has a few advantages:
Loops often have side effect results, like a temporary variable that stays
in the environment after the loop finishes
map() often involves less lines of code than loops
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
26 / 60
Map vs looping
Exercise 2.2: Looping over a dataframe (‘r fa( 3 min)
Create a toy dataframe of 50,000 columns and 400 observations using
this code
df <- [Link](
replicate(50000,
sample(1:100, 400, replace=TRUE)))
Create an empty vector named col_means_loop where you will store
column means with this code: col_means_loop <- c()
Loop over every column to get the column means and store them in
the vector
for (column in df) {
....
}
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
27 / 60
Map vs looping
- Inside the loop:
+ Use ‘mean()‘ to get each column mean
+ Use ‘append()‘ to add a new mean to the vector: ‘col_means_l
]
The solution is this:
df <- [Link](replicate(50000, sample(1:100, 400, replace=T
col_means_loop <- c()
for (column in df){
col_means_loop <- append(col_means_loop, mean(column))
}
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
28 / 60
Map vs looping
Exercise 5.3: Now use map() ( 1 min)
1. Use ‘map()‘ to produce a list with the means of the columns
1. Store the result in a list named ‘col_means_map‘
Hints: + Remember the syntax of map(): map(X, function_name) +
The function name inside map() shouldn’t have parentheses next to it
(i.e.: mean instead of mean())
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
29 / 60
Map vs looping
Compare the syntax of the solutions of both exercises:
# Dataframe creation
df <- [Link](replicate(50000, sample(1:100, 400, replace=T
# Loop exercise
col_means_loop <- c()
for (col in df){
col_means_loop <- append(col_means_loop, mean(col))
}
# Map exercise
col_means_map <- map(df, mean)
Do you remember which one ran faster?
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
30 / 60
Map vs looping
Also, remember we said that loops produce side effects?
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
31 / 60
Map vs looping
Map
map() looks nice, doesn’t it?
But what about cases when it’s impossible to implement the
operations I want to apply in only one function? Do I have to use for
loops then?
Not at all! Let’s get to the next section for those cases.
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
32 / 60
Writing your own functions
As we have said several times, R is super flexible
One example of that is that it’s super easy and quick to create
custom functions
Here’s how:
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
33 / 60
Custom functions
square <- function(x) {
y <- x ˆ 2
return(y)
}
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
34 / 60
Custom functions
Exercise 2.4 ( 2 min)
Create a function named zscore that standardizes the values of a vector.
> **Hints:**
The command to obtain the mean of a vector is mean(x)
The command to get the SD of a vector is sd(x)
R is vectorized: you can operate vectors and numbers directly and the
result will be a vector
Don’t forget to include the argument [Link] = TRUE in mean() and
sd()
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
35 / 60
Custom functions
zscore <- function(x) {
mean <- mean(x, [Link] = TRUE)
sd <- sd(x, [Link] = TRUE)
z <- (x - mean)/sd
return(z)
}
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
36 / 60
Custom functions
Exercise 8
1 Subselect the columns health_life_expectancy and freedom in
titanic
Use dplyr’s select() for this, as in: titanic %>% select(Fare,
Age)
2 Use map() combined with the zscore function to get the z-score of
these two columns and assign the resulting list to an object named
z_scores
3 Use list indexing on z_scores to generate two new columns in
titanic with the standardized values of Fare and Age
Hints: * Don’t use parenthesis next to the function name we’re using
map() with
Use double brackets instead of single brackets or the symbol $ to
index the elements of a list
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
37 / 60
Custom functions
z_scores <- titanic %>%
select(Fare, Age) %>%
map(zscore)
titanic$fare_st <- z_scores[[1]]
titanic$age_st <- z_scores[[2]]
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
38 / 60
Appendix
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
39 / 60
Appendix - More on packages
Once a package is loaded, you can use its features and functions. Here’s a
list of some useful packages:
Rcmdr - easy to use GUI
swirl - an interactive learning environment for R and statistics.
ggplot2 - beautiful and versatile graphics (the syntax is a pain,
though)
stargazer - awesome latex regression and summary statistics tables
foreign - reads .dta and other formats from inferior statistical
software
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
40 / 60
Appendix - Column extraction operators
Remember the use of $ to extract columns from a dataframe?
Other than $, we can also use double brackets to extract the column
of a dataframe:
# With $:
titanic$Survived
# With [[]]:
titanic[["Survived"]] # Notice the use of double quotes
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
41 / 60
Appendix - Column extraction operators: [[]] vs $
What’s the key difference between them?
Well, [[]] lets us use other objects to refer to column names, while $
doesn’t
col_name <- "Survived"
head(titanic$col_name) # this returns a NULL object
## NULL
#because no column has the name "col_name" in titanic
col_name <- "Survived"
head(titanic[[col_name]])
## [1] 0 1 1 1 0 0
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
42 / 60
Appendix - Column extraction operators: [[]] vs $
This difference is key because we can use [[]] to loop through column
names, while this is not directly possible with $.
# Printing the first observation of every column of titanic
for (col in colnames(titanic)) {
titanic[[col]] %>%
head(1) %>%
print()
}
## [1] 1
## [1] 0
## [1] 3
## [1] "Braund, Mr. Owen Harris"
## [1] "male"
## [1] 22
## [1] 1
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
43 / 60
Appendix - Apply
Apart from purrr’s map(), base R also has a set of functions that
allows users to apply a function to a number of objects without using
explicit loops
They’re called apply and there are many of them, with different use
cases
If you look for the apply help file, you can see all of them
We’ll show only two of them, sapply and apply
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
44 / 60
Appendix - Apply
The syntax of sapply() is:
sapply(X, FUN, ...)
Its main arguments are:
X: a dataframe, matrix or vector the function will be applied to
FUN: the function you want to apply
sapply() applies the function (FUN) to all the elements of X. If X is a
dataframe then the function is applied column-wise, while if it’s a
vector or a list it is applied item-wise
The output of sapply() is usually a vector with the results, but it
can be a matrix if the results have more than one dimension
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
45 / 60
Appendix - Apply
# A for loop in R
for (number in c(1.2, 2.5)) {
print(round(number))
}
# A much more elegant option
sapply(c(1.2, 2.5), round)
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
46 / 60
Appendix - Apply
# Printing the first observation of every column of titanic
for (col in names(titanic)) {
print(head(titanic[[col]], 1))
} # Option 1
sapply(titanic, head, 1) # A more elegant and efficient option
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
47 / 60
Appendix - Apply
A more general version of sapply() is the apply() function. This is
its syntax:
apply(X, MARGIN, FUN, ...)
Arguments:
X: a dataframe (or matrix) the function will be applied to
MARGIN: 1 to apply the function to all rows or 2 to apply the
function to all columns
FUN: the function you want to apply
apply() applies a function (FUN) to all columns or rows of matrix
(X). A value of 1 in MARGIN indicates that the funcion should be
applied row-wise, while 2 indicates columns
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
48 / 60
Appendix - Apply
matrix <- matrix(c(1, 24, 9, 6, 9, 4,
2, 74, 2),
nrow = 3) # Defining a matrix
apply(matrix, 1, mean) # row means
apply(matrix, 2, mean) # column means
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
49 / 60
Appendix - Assignment 1
Exercise: Get the row max
1 Select the columns Fare and Age of titanic
2 Use apply() to get the row max between these two columns, for
every row
Hints:
Remember the syntax of apply(): apply(X, MARGIN, FUN)
A value of 1 for MARGIN indicates that the function must applied
row-wise
The function to get the maximum over a set of number is max
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
50 / 60
Appendix - Apply
Solution:
titanic %>%
select(freedom, happiness_score) %>%
apply(1, max)
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
51 / 60
Appendix - Commenting
To comment a line, write # as its first character
# This is a comment
print("But this part is not")
You can also add # halfway through a line to comment whatever
comes after it
print("This part is not a comment") # And this is a comment
In R everything that comes after # will always be a comment
To comment a selection of lines, press Ctrl + Shift + C
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
52 / 60
Appendix - Assignment 2
Exercise
1 In your script panel, select all the lines of your script
2 Use the keyboard shortcut to comment these lines.
Shortcut: Ctrl + Shift + C
3 Use the keyboard shortcut to comment these lines again. What
happened?
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
53 / 60
Appendix - Indentation
# Here's some code
annualHappy_reg <- aggregate(happy_score ~ year + region,
data = whr, FUN = mean)
ggplot(annualHappy_reg,aes(y = happy_score,x =
[Link](year), color =
region, group = region)) +
geom_line() + geom_point()
# Here's the same code
annualHappy_reg <-
aggregate(happiness_score ~ year + region,
data = whr,
FUN = mean)
ggplot(annualHappy_reg,
aes(y = happiness_score,
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
54 / 60
Appendix - Indentation
30
Sex
Age
female
male
28
26
0 1
[Link](Survived)
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
55 / 60
Appendix - Indentation
R understands what unindented code says, but it can be quite
difficult for a human being to read it
On the other hand, white space does not have a special meaning
for R, so it will understand code that is more readable for a human
being
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
56 / 60
Appendix - Indentation
Indentation in R looks different than in Stata:
To indent a whole line, you can select that line and press Tab
To unindent a whole line, you can select that line and press Shift +
Tab
However, this will not always work for different parts of a code in the
same line
In R, we typically don’t introduce white space manually
It’s rather introduced by RStudio for us
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
57 / 60
Appendix - Assignment 3
Exercise
To see an example of how indenting works in RStudio, let’s use an
example with map():
# An elegant "loop" in R
map(c(1.2, 2.5, 9.1, 5.8), round)
1 Add a line between the two arguments of the function (the vector of
numbers and round)
2 Now add a line between the numbers in the vector.
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
58 / 60
Appendix - Indentation
Note that RStudio formats the different arguments of the function
differently:
# A much more elegant loop in R
map(c(1.2,
2.5,
9.1,
5.8),
round)
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
59 / 60
Appendix - Exploring a dataframe
Some useful functions:
View(): opens a visualization of the dataframe
class(): reports object type or type of data stored
dim(): reports the size of each one of an object’s dimension
names(): returns the variable names of a dataframe
str(): general information about the structure of an R object
summary(): summary information about the variables in a dataframe
head(): shows the first few observations in the dataframe
tail(): shows the last few observations in the dataframe
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3B - Introduction
of Monday
Agriculture
to R09Programming
December,
and Natural2024
Resources)
60 / 60