0% found this document useful (0 votes)
7 views80 pages

Introduction to R for Data Science

This document outlines a lecture on Introduction to R, presented by Assa Mulagha-Maganga at Lilongwe University. It covers the course format, including hands-on sessions and exercises, as well as basic concepts in R, such as importing data, working with dataframes, and creating objects. The session aims to help Stata users transition to R by demonstrating its features and functionalities.

Uploaded by

NafeMgwadira
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views80 pages

Introduction to R for Data Science

This document outlines a lecture on Introduction to R, presented by Assa Mulagha-Maganga at Lilongwe University. It covers the course format, including hands-on sessions and exercises, as well as basic concepts in R, such as importing data, working with dataframes, and creating objects. The session aims to help Stata users transition to R by demonstrating its features and functionalities.

Uploaded by

NafeMgwadira
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Introduction to Data Science

Lecture 3A - Introduction to R

Assa Mulagha-Maganga, PhD Econ

Department of Applied Economics


Lilongwe University of Agriculture and Natural Resources

Monday 02 December, 2024

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
1 / 80
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
2 / 80
Table of contents
1 Introduction

2 Getting started

3 Data in R

4 Functions

5 R objects

6 Basic types of data


Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
3 / 80
Sessions format

Welcome!
We’re glad you’re joining us today!

Format
These are hands-on sessions. You are strongly encouraged to follow
along in your computer what the presenter is doing
The sessions include exercises. You will be given 3-4 minutes to solve
each exercise before we show the solution

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
4 / 80
Sessions format

Format
Every session has two TAs. For this session, our TAs are Chripine
Mtocha and Lumbani Banda
The TAs will help you troubleshooting particular issues which make
you unable to follow along the presentation. Send a message over the
chat whenever you need help

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
5 / 80
Sessions format

Format
If you have a question feel free to unmute yourself or use the chat to
ask it
Please mute your microphone the rest of the time
If your connection is good enough, please leave your video on
The materials of each session will be shared in on my google webpage
of the course by the end of each session: R Training Page

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
6 / 80
Introduction

About this course


These training sessions will offer an introduction to R, its amazing
features, and how Stata users can adapt from using Stata to using R.
We assume that you know how to do statistical programming in Stata or
that you have a computer programming background.

About this session


This first session will present the basic concepts you will need to use R.

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
7 / 80
Getting started - RStudio interface

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
8 / 80
Getting started - RStudio interface

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
9 / 80
Getting started - RStudio interface

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
10 / 80
Getting started - RStudio interface

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
11 / 80
Getting started - RStudio interface

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
12 / 80
Getting started - Importing data

Let’s start by loading the data we’ll be using:


Exercise 1: Import data manually ( 3 min)
1 Go to the OSF page of the course R Training Page and download the
file located in Datasets > [Link]
2 In RStudio, go to File > Import Dataset > From Text (base)
and open the [Link] file.
Depending on your Rstudio version, it might be File > Import
Dataset > From CSV
3 Assign the name titanic to the data on the import window.
If you solved the exercise correctly, you’ll see that RStudio opens a
tab with a viewer of the dataframe

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
13 / 80
Getting started - Importing data

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
14 / 80
Getting started - Importing data

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
15 / 80
Getting started - RStudio interface

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
16 / 80
Data in R

In R:
Datasets are called dataframes. R works with them in a different way:
You can load as many dataframes as you wish or your computer’s
memory allows
Operations will have lasting effects only if you store their results

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
17 / 80
Data in R

In R:
Everything that exists in R’s memory -variables, dataframes,
functions- is an object
You could think of an object like a chunk of data with some
properties that has a name by which you call it
If you create an object, it’s going to be stored in memory until you
delete it or quit R
Whenever you run anything you intend to use in the future, you need
to store it as an object.

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
18 / 80
Data in R
To better understand the idea, we’re going to use the data we opened
from the United Nations’ World Happiness Report.
First, let’s take a look at the data.
Type the following code in the Console panel and press Enter to explore
the data:

# We can use the function View() to browse the whole data


View(titanic) # <--- Note that the first letter is uppercase

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
19 / 80
Data in R
Alternatively we can print the first 6 obs. with head():

## PassengerId Survived Pclass


## 1 1 0 3
## 2 2 1 1
## 3 3 1 3
## 4 4 1 1
## 5 5 0 3
## 6 6 0 3
## Name Se
## 1 Braund, Mr. Owen Harris mal
## 2 Cumings, Mrs. John Bradley (Florence Briggs Thayer) femal
## 3 Heikkinen, Miss. Laina femal
## 4 Futrelle, Mrs. Jacques Heath (Lily May Peel) femal
## 5 Allen, Mr. William Henry mal
## 6 Moran, Mr. James mal
## Ticket
Assa Mulagha-Maganga, PhD Econ (Department
Introduction Fare
of Applied
to Data Cabin
Economics Embarked
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
20 / 80
Data in R

Now, let’s try some simple manipulations. First, assume we’re only
interested in data of the survivors
Exercise 2: Subset the data (1 min)
Subset the dataframe, keeping only observations where variable
Survived equals 1.

# To do that we'll use the subset() function


subset(titanic, Survived == 1)

Then, look again at the first 6 observations

# Use the head() function again


head(titanic)

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
21 / 80
Data in R

Important: It is a good practice to always write your code in the script


window and run it from there

subset(titanic, Survived == 1)
head(titanic)

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
22 / 80
Data in R

We can see that nothing happened to the original data. This was because
we didn’t store the edit we made.
To store an object, we use the assignment operator (<-):
# Assign the Answer to the Ultimate Question of Life,
# the Universe, and Everything
x <- 42

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
23 / 80
Data in R

# Assign the Answer to the Ultimate Question of Life,


# the Universe, and Everything
x <- 42

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
24 / 80
Data in R

From now on, x is associated with the stored value (until you replace it,
delete it, or quit the R session).

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
25 / 80
Data in R

Exercise 3: Create an object (1 min)


Create a new dataframe, called titanic1, that is a subset of the titanic
dataframe containing only data from the survivors.

# Using the same function but now assigning it to an object


titanic1 <- subset(titanic, Survived == 1)

# Display the 6 first obs. of the new data


head(titanic1)

# Notice that we still have the original dataframe intact


head(titanic)

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
26 / 80
Data in R

You can also see that your environment panel now has two data objects:

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
27 / 80
Data in R

Important features to take note:


In R, if you want to change your data, you need to store the result
in an object using the arrow operator <-
It is also possible to simply replace the original data. This happens if
you assign the new object to the same name as the original.

# This would have replaced "titanic" instead of creating a new


titanic <- subset(titanic, Survived == 1)

Important: This will modify the original object – titanic in this case. R
will not give you a warning when you’re modifying an existing object with
<-

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
28 / 80
Data in R

Printing a result vs storing a result


Print (display) is built into R. If you execute any action without storing it,
R will simply print the results of that action but will not save anything
in the memory.

# For instance, this will only print the observations that mee
subset(titanic, Survived == 1)

# To actually store the result, we would need to assign it to


titanic1 <- subset(titanic, Survived == 1)

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
29 / 80
Functions

Quick intro to functions


head(), View(), subset() and [Link]() are functions.
Functions in R take named arguments
Type help(subset) in the console to check the arguments of the
subset() function

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
30 / 80
Functions
Quick intro to functions
When we used subset(titanic, Survived == 1) we’re implicitily
telling R that the x argument is whr and the subset argument is
Survived == 1
In other words, these two commands will return the same results:
subset(titanic, Survived == 1)

subset(x = titanic, subset = Survived == 1)

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
31 / 80
Functions

Quick intro to functions


Arguments are always enclosed in parentheses
Usually the first argument is the object you want to use the function
on, e.g. subset(titanic, ...)
Functions usually return values that you can store in an object, print
or use directly as an argument of another function. They rarely
modify an object in-place
We will explore these ideas in depth in a later session.

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
32 / 80
R objects

R objects
Objects are the building blocks of R programming. This section will
explore some of the most common classes, with a focus on data structures.
This will give you the foundation to explore your data and construct
analytical outputs.

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
33 / 80
R objects

What is an object?
An object is like a global or local, it’s something you can refer to
later in your code to get a value
But while you can only put a number or a string in a global, you can
put anything into an object: scalars, strings, dataframes, vectors,
plots, functions
Objects also have attributes that can be used to manipulate them

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
34 / 80
R objects

Object classes
Here are the object classes we will cover in this first session:
Vectors: an uni-dimensional object that stores a sequence of
values of the same class
Dataframes: a combination of different vectors of the same length
Lists: a multidimensional object that can store several objects of
different classes and dimensions

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
35 / 80
R objects - Vectors

Vectors
A vector is an uni-dimensional object composed by one or more elements
of the same type.
Use the following code to create vectors in two different ways
# Creating a vector with the c() function
v1 <- c(1,2,3,4,5)

# Alternative way to create an evenly spaced vector


v2 <- 1:5

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
36 / 80
R objects - Vectors

v1 <- c(1,2,3,4,5) # Creating a vector with the c() function


v2 <- 1:5 # Alternative way to create an evenly space

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
37 / 80
R objects - Vectors

You can use brackets for indexing vector elements


v2[4] # Prints the 4th element of the vector
v2[1:3] # Prints from the 1st to the 3rd element

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
38 / 80
R objects - Dataframes
Dataframes
The titanic and titanic1 objects are both dataframes. You can also
construct a new dataframe from scratch by combining vectors with the
same number of elements with the command [Link]().
Now, type the following code to create a new dataframe
# Dataframe created by biding vectors
df1 <- [Link](v1,v2)
df1

## v1 v2
## 1 1 1
## 2 2 2
## 3 3 3
## 4 4 4
## 5 5 5
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
39 / 80
R objects - Dataframes

df1 <- [Link](v1,v2) #creates a df by binding to existing


df1

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
40 / 80
R objects - Dataframes

Dataframes
Since a dataframe has two dimensions, you can use indices for both. The
first index indicates the row selection and the second indicates the column.
Numeric indexing
# The first column of titanic
whr[,1]

# The 45th row of titanic


tiitanic[45,]

# Or the 45th element of the first column


titanic[45,1]

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
41 / 80
R objects - Dataframes

titanic[,1] # The first column of titanic


titanic[45,] # The 45th row of titanic
titanic[45,1] # Or the 45th element of the first column

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
42 / 80
R objects - Dataframes

Dataframes
Alternatively, you can use the column names for indexing, which is the
same as using the $ sign.
Names indexing
# The 22th element of the country column
titanic[22,"Name"] # The same as titanic$Name[22]

## [1] "Beesley, Mr. Lawrence"

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
43 / 80
R objects - Dataframes

# The 22th element of the country column


titanic[22,"Name"] # The same as titanic$Name[22]

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
44 / 80
R objects - Dataframes

Vectors in dataframes
To R, each of the columns of the object titanic is a vector.
Calling a vector from a dataframe:
We use the $ character to extract vectors (variables) by their names in a
dataframe
For example:

# Create a vector with the values of the "year" variable


ticket_vector <- titanic$Ticket

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
45 / 80
R objects - Dataframes

ticket_vector <- titanic$Ticket


# creates a vector with the values of the "Ticket" variable

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
46 / 80
R objects - Dataframes

survivor_vector <- titanic$Survived


# creates a vector with the values of the "Survived" variable

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
47 / 80
R objects - Lists

Lists
Lists are more complex objects that can contain many objects of different
classes and dimensions.
The outputs of many functions, a regression for example, are similar to
lists (more on this in a later session).
Here’s a quick example:
Combine several objects of different types in a list
# Use the list() function
lst <- list(v1, df1, 45)

Print the list yourself to see how it looks like.

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
48 / 80
R objects - Lists

lst <- list(v1, df1, 45) # definition of lst


print(lst) # checking the content of lst

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
49 / 80
R objects - Lists

You can subset lists using single brackets ([]) or double brackets ([[]])

my_list[[i]] will return the actual item in the i-th position

my_list[i] will return a list with the item in the i-th position

Importantly, [] can be used to index elements with a numeric vector


indicating the positions of the elements to subset

[[]], on the other hand, only allows a single index

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
50 / 80
R objects - Lists

class: inverse, center, middle name: basic-types-of-data

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
51 / 80
Basic types of data

R has different kinds of data that can be recorded inside objects. They are
very similar to what you have in Stata, and the main types are string,
integer and numeric, factors, and boolean.
Let’s start with the simpler ones:
Strings
A sequence of characters that are usually represented between double
quotes. They can contain single letters, words, phrases or even some
longer text.

Integer and numeric


There are two different ways to store numbers. They are different because
they use memory differently. As default, R stores numbers in the numeric
format (double).

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
52 / 80
Basic types of data - Strings
Exercise 4: Concatenate strings (3 min)
1 Create the following vector of strings: str_vec <- c("R",
"Python", "SAS", "Excel", "Stata")
2 Create a scalar (a vector of one element) containing the phrase “can
be an option to” and call it str_scalar. Your code will be similar to
this: str_scalar <- "can be an option to"
3 Use the function paste() with 3 arguments separated by commas:
The first argument as the 1st element of str_vec.

The second argument as the str_scalar.

The third argument as the 5th element of str_vec.


1 If you’re not sure where to start, type:
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
53 / 80
Basic types of data - Strings

str_vec <- c("R", "Python", "SAS", "Excel", "Stata")


str_scalar <- "can be an option to" # creating str_scala
paste(str_vec[1], str_scalar, str_vec[5]) # using paste()

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
54 / 80
Advanced types of data

R also has other more complex ways of storing data. These are the most
used:
Factors
Factors are numeric categorical values with text labels. Turning strings
into factors makes it easier to run different analyses on them and also uses
less space in your memory.

Booleans
Booleans are logical binary variables, accepting either TRUE or FALSE as
values. They are automatically generated when performing logical
operations.

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
55 / 80
Advanced types of data
Booleans
Boolean data is the result of logical conditions. It can take two possible
values: TRUE or FALSE.
Another difference is that in R you can assign a boolean value to an
object:

# Storing boolean values:


boolean_true <- TRUE
boolean_false <- FALSE

# Printing:
boolean_true

## [1] TRUE

boolean_false
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
56 / 80
Advanced types of data - Booleans

boolean_true <- TRUE


boolean_false <- FALSE

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
57 / 80
Advanced types of data

Booleans

Exercise 5 ( 3 min)
Create a boolean vector with the condition of annual income below
average: view(titanic)

# Create vector
age_below_avg <- titanic$Age < mean(titanic$Age)

# See the 6 first elements of the vector


head(age_below_avg)

## [1] NA NA NA NA NA NA

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
58 / 80
Advanced types of data - Booleans

fare_below_avg <- titanic$Fare < mean(titanic$Fare) # Create v


head(fare_below_avg) # See the 6 first elements of the vector

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
59 / 80
Advanced types of data
Booleans
We can use boolean vectors to index elements:

# Creating a vector with 5 elements:


my_vector <- c("1st", "2nd", "3rd", "4th", "5th")
my_vector

## [1] "1st" "2nd" "3rd" "4th" "5th"

# Selecting and printing the first and last elements only:


boolean1 <- c(TRUE, FALSE, FALSE, FALSE, TRUE)
my_vector[boolean1]

## [1] "1st" "5th"

# Selecting and printing every element but the first:


boolean2 <- c(FALSE, TRUE, TRUE, TRUE, TRUE)
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
60 / 80
Advanced types of data - Booleans

my_vector <- c("1st", "2nd", "3rd", "4th", "5th")


boolean1 <- c(TRUE, FALSE, FALSE, FALSE, TRUE)
# We'll use this to select the first and last elements only
boolean2 <- c(FALSE, TRUE, TRUE, TRUE, TRUE)
# And this to select every element but the first

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
61 / 80
Advanced types of data
Booleans
Now let’s use the boolean vector age_below_avg to add a dummy
variable in the titanic dataframe for the same condition.
Exercise 6 (3 min)
Create a column in titanic containing zeros and call it rank_low.
You can do this by typing:

titanic$rank_low <- 0

Now use age_below_avg to index the lines of the age_low column


and replace all observations that meet the condition with the value 1.

titanic$rank_low[age_below_avg] <- 1

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
62 / 80
Important: Notice that titanic$rank_low[age_below_avg] is
subsetting the column titanic$rank_low to the observations that have a
value of TRUE in the boolean vector age_below_avg

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
63 / 80
Advanced types of data - Booleans

titanic$rank_low <- 0 # this creates a vector of zeros


titanic$rank_low[age_below_avg] <- 1
# this ˆ turns its values to 1, for the observations with a TR

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
64 / 80
Advanced types of data

Booleans
Instead of indexing the lines with the boolean vector age_below_avg, we
could also use the boolean condition itself:

# Replace with 1 those obs that meet the condition


titanic$rank_low[age_below_avg] <- 1
# is the same as
titanic$rank_low[titanic$Fare < mean(titanic$Fare)] <- 1

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
65 / 80
Thank you!

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
66 / 80
Appendix - R and RStudio Installation

Installation
This training requires that you have R and RStudio installed in your
computer:
Instructions
To install R, visit ([Link] and select a
Comprehensive R Archive Network (CRAN) mirror close to you.
To install RStudio, go to [Link] Note that you
need to install R first.

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
67 / 80
Appendix - R

R is object oriented:
R needs to load non-base commands (packages) at the beginning of
each session
R is less specialized, which means more flexibility and functionalities.
R has a much broader network of users:
More resources online, which makes using Google a lot easier. You’ll
never want to see Statalist again in your life!

Development of new features and bug fixes happen faster.

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
68 / 80
Appendix - R vs Stata

Here are some advantages of R:

R is a free and open source software, a huge advantage for open


science
It allows you to have several dataframes open simultaneously
No need to use keep, preserve, restore
It can run complex Geographic Information System (GIS) analyses
You can use it for web scrapping and APIs
You can easily run machine learning algorithms with it
You can create complex Markdown documents. This presentation, for
example, is entirely done in R
You can create interactive dashboards and online applications with
the Shiny package

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
69 / 80
Appendix - Syntax
R’s syntax is heavier than Stata’s:
Parentheses to separate function names from its arguments.

Commas to separate arguments.

For comments we use the # sign.

You can have line breaks inside function statements.

In R, functions can be treated much like any other object. Therefore,


they can be passed as arguments to other functions.
Similarly to Stata:
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
70 / 80
Appendix - RStudio interface

Script
Where you write your code. Just like a do file.

Console
Where your results and messages will be displayed. But you can also type
commands directly into the console, as in Stata.

Environment
What’s in R’s memory.

The 4th pane


Can display different things, including plots you create, packages loaded
and help files.

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
71 / 80
Appendix - RStudio vs R GUI
RStudio
RStudio is an integrated development environment for R
It’s a software that uses the base R installation of your computer and
provides an expanded interface that greatly facilitates R programming

R GUI
The basic R Graphic User Interface (GUI) can also be used to
program in R. You will find it in your computer with a name similar to
R<version>, as in R4.0.2
Opening the R GUI allows to work with R in a command line format,
where you introduce one R command and the interface executes it
and prints any message if needed
It’s very similar to the console panel of RStudio and it also allows to
open a script editor, but it will not show you a list of the variables
loaded on your environment
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
72 / 80
Appendix - Matrices

A matrix a bi-dimensional object composed by one or more vectors of the


same type.
Type the following code to test two different ways of creating matrices
# Matrix created by joining two vectors:
m1 <- cbind(v1,v1)

# Matrix using the


m2 <- matrix(c(1,1,2,3,5,8), ncol = 2)

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
73 / 80
Appendix - Matrices

Now use the following code to check the elements of these matrices by
indexing
# Matrix indexing: typing matrix[i,j] will give you
# the element in the ith row and jth column of that matrix
# m2[1,2]

# Matrix indexing: typing matrix[i,] will give you the


# ith row of that matrix
m1[1,]

# Matrix indexing: typing matrix[,j] will give you the


# jth column of that matrix (as a vector)
m1[,2]

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
74 / 80
Appendix - Advanced types of data - Factors

Factors

Create a factor vector using the following code


# Basic factor vector
num_vec <- c(1,2,2,3,1,2,3,3,1,2,3,3,1)
fac_vec <- factor(num_vec)

# A bit fancier factor vector


fac_vec <- factor(num_vec,labels=c("A","B","C"))

# Change labels
levels(fac_vec) = c('One','Two','Three')

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
75 / 80
Appendix - Numbers and integers

Two scalars, one with a round number the other with a fractional part:
# a numeric scalar with an integer number
int <- 13
num <- 12.99

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
76 / 80
Appendix - Numbers and integers
Now we can see the objects classes with the class() function and test it
with the [Link]() and [Link]() functions.
# you can see the number's format using the class function:
class(int)

## [1] "numeric"

class(num)

## [1] "numeric"

[Link](int)

## [1] FALSE

[Link](int)
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
77 / 80
Appendix - Numbers and integers
Numbers and integers
We can, however, coerce objects into different classes. We just need to be
careful because the result might not be what we’re expecting.
Use the [Link]() and round() functions on the num object to see
the difference:
[Link](num)

## [1] 12

# and

round(num)

## [1] 13

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
78 / 80
Appendix - Help, Google and Stack Overflow

Help in R works very much like in Stata: the help files usually start with a
brief description of the function, explain its syntax and arguments and list
a few examples. There are two ways to access help files:
Exercise 7: Use help
# You can use the help() function
help(summary)

# or its abbreviation
?summary

Assa Mulagha-Maganga, PhD Econ (Department


Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
79 / 80
Assa Mulagha-Maganga, PhD Econ (Department
Introduction
of Applied
to Data
Economics
ScienceLilongwe
Lecture University
3A - Introduction
of Monday
Agriculture
to R02 December,
and Natural2024
Resources)
80 / 80

You might also like