Introduction to R Language
DA 26, 28, 29, AI Eng 5, 6
What we are going to cover in R Language?
• Introduction to R and Rstudio • Data Manipulation with dplyr
• Overview of R Language • Introduction to the dplyr Package
• What is R and its Applications in Data • Installing and Loading dplyr
Analytics? • Basic Data Manipulation
• Installing R and Rstudio • Filtering Rows with filter()
• Introduction to the RStudio Interface • Selecting Columns with select()
• Basic R Syntax • Arranging Rows with arrange()
• Variables and Data Types • Mutating Data with mutate()
• Basic Operations • Summarizing Data with summarize()
• Data Structures in R • Basic Data Visualization with ggplot2
• Vectors, Matrices, Lists, and Data Frames • Introduction to ggplot2
• Creating and Manipulating Vectors • Installing and Loading ggplot2
• Understanding Matrices • Creating Basic Plots
• Working with Lists • Scatter Plots, Line Plots, Bar Plots
• Introduction to Data Frames • Customizing Plots
• Adding Titles, Labels, and Themes
[Link]
R Language
CRAN
How to install R
• [Link]
Introduction to Console
• Basic mathematical operator
• Variables
• <-, =, ->
• ^L to clear
Variables in R
• Definition: Variables are used to store data values, which can be
referenced and manipulated in R scripts.
• Naming Rules:
• Must start with a letter or a period (not followed by a number).
• Case-sensitive (e.g., age and Age are different variables).
• Cannot contain spaces or special characters (except underscores _).
• Assignment Operators:
• <- or = for assignment (e.g., x <- 10).
• Use <<- for global assignment within functions.
• Examples:
• x <- 42 (Numeric)
• name <- "John" (Character)
• is_active <- TRUE (Logical)
Data Types in R
• Numeric: Represents numbers with or without decimals. Example: 42, 3.14
• Integer: Whole numbers specified with an "L" suffix. Example: 5L
• Character: Text data enclosed in quotes. Example: "Hello, World!“
• Logical: Boolean values, either TRUE or FALSE.
• Complex: Numbers with real and imaginary parts. Example: 2 + 3i
• Factor: Categorical data, used for grouping. Example: factor(c("low", "medium", "high"))
• Date/Time: For dates and times. Example: [Link]("2024-09-01"), POSIXct for timestamps.
R Reserve Words
• Flow Control Keywords: • Special Constants:
• if, else • Inf (Infinity)
• repeat • NaN (Not a Number)
• while • NA (Missing Value)
• function • NA_integer_
• for • NA_real_
• in • NA_complex_
• next • NA_character_
• break • Operators & Assignment:
• Logical Constants: • return
• TRUE • ... (Ellipsis, used for passing
• FALSE multiple arguments in functions)
• NULL
R Reserve Words
• Language-Specific Keywords:
• Switch
• try
• tryCatch
• Stop
• warning
Operators in R
• Arithmetic Operators • Comparison Operators
• Addition (+) • Equal to (==)
• Subtraction (-) • Not equal to (!=)
• Multiplication (*) • Greater than (>)
• Division (/) • Less than (<)
• Exponentiation (^, **) • Greater than or equal to (>=)
• Modulo (%%) • Less than or equal to (<=)
• Integer Division (%/%) • Logical Operators
• Assignment Operators • Logical AND (&, &&)
• Assignment (<-, =, ->) • Logical OR (|, ||)
• Global Assignment (<<-, ->>) • Logical NOT (!)
• Miscellaneous Operators
• Sequence (:)
• Member Access ($)
Operator Precedence in R
Precedence Operators
1 (Highest) ()
2 ^, **
3 +, - (unary), !
4 *, /, %/%, %%
5 +, - (binary)
6 <, <=, >, >=, ==, !=
7 ! (logical NOT)
8 &, && (logical AND)
9 `
10 <-, =, ->, <<-, ->> (assignment)
11 (Lowest) $, : (member access, sequence)
Data Structures in R
Vectors: One-dimensional arrays that hold elements of the same type.
Syntax: c(element1, element2, ...)
Matrices: Two-dimensional arrays that hold elements of the same type.
Syntax: matrix(data, nrow, ncol)
Lists: Collections that can hold elements of different types.
Syntax: list(element1, element2, ...)
Data Frames: Two-dimensional, tabular data structures that can hold
different types.
Syntax: [Link](column1 = c(...), column2 = c(...))
Data Structures in R
# Vectors; vectors are array of the same data type # Lists
# Creating a numeric vector; C = Combine # Creating a list with different types of elements
numeric_vector <- c(1, 2, 3, 4, 5) list_example <- list(name = "Alice", age = 25, scores = c(85, 90, 88))
print("Numeric Vector:") print("List:")
print(numeric_vector) print(list_example)
# Creating a character vector # Data Frames
char_vector <- c("apple", "banana", "cherry") # Creating a data frame
print("Character Vector:") data_frame_example <- [Link](
print(char_vector) id = 1:3,
name = c("John", "Jane", "Doe"),
# Matrices score = c(88, 92, 95)
# Creating a 2x3 matrix )
matrix_example <- matrix(1:6, nrow = 2, ncol = 3) print("Data Frame:")
print("Matrix (2x3):") print(data_frame_example)
print(matrix_example)
Control Structures in R
• Conditional Statements:
• if (condition) { } else { }
• Loops:
• For Loop: for (variable in sequence) { }
• While Loop: while (condition) { }
• Repeat Loop:
• Repeat Loop: repeat { if (condition) break }
• Next and Break:
• break: Terminates the loop immediately: if (i == 3) break
• next: Skips the current iteration and moves to the next:if (i == 3) next
Using if statement
# Prompt the user to enter a number
number <- [Link](readline(prompt="Enter a number: "))
# Check the number and print appropriate messages using if statement
if ([Link](number)) {
print("You did not enter a valid number.")
} else if (number > 0) {
print("The number is positive.")
} else if (number < 0) {
print("The number is negative.")
} else {
print("The number is zero.")
}
Using for statement (loops)
## 1 to 10
for (x in 1:10) {
print (x)
}
## using sequence
from = 1
to = 5
for (x in seq(from, to)) {
print(x)
}
Using existing data
• data()
• USArrests
• ?USArrests
• Slido: Explore the available data, and which one is the most
appealing dataset to work on?
Basic Statistical Analysis
• mydata <- USArrests
• min(mydata$Assault)
• max(mydata$Assault)
• mean(mydata$Assault)
• mean(mydata$Assault, [Link] = TRUE)
• head(mydata)
• tail(mydata)
• summary(mydata)
dplyr Library
• Download [Link]
• This is ‘Billboard "The Hot 100" Songs’
• This dataset consists of over 330 thousand records
%>% Piping
First argument of
the function
x %>% function(y)
the above statement is equals to
=function(x, y)
If we want to put the piped
item to other than first arg
x %>% function(y, x)
the above statement is equals to
=function(y, x)
COLUMN: ROW: GROUP:
select() filter() group_by()
mutate() distinct() summarise()
arrange() count()
select(): Selecting specific columns from the
dataframe
# Define the file path
file_path <- "C:/R Projects/[Link]“
# Read the CSV file into a data frame
billboard100 <- [Link](file_path)
billboard100 %>%
select(date, rank, song, artist, '[Link]')
billboard100 %>%
select(date:artist, weeks_popular='[Link]')
billboard100 %>%
select(-'last-week', -'peak-rank')
Selecting
specific
columns
from the
dataframe
mutate(): Mutating means compute or
append one or more new columns
billboard100 %>%
mutate(rank_change = [Link]-rank) %>%
select(date, rank, song, rank_change)
filter(): Extract rows that meet logical criteria
billboard100 %>%
select(date:artist, weeks_popular='weeks-on-board’) %>%
filter(weeks_popular >= 20)
billboard100 %>%
select(date:artist, weeks_popular='weeks-on-board’) %>%
filter(weeks_popular >= 20, artist == 'Drake’)
billboard100 %>%
select(date:artist, weeks_popular='weeks-on-board’) %>%
filter(weeks_popular >= 20, artist == 'Drake’ | artist == 'Taylor Swift')
distinct(): Remove duplicate rows
billboard100 %>%
select(date:artist, weeks_popular='weeks-on-board’) %>%
filter(artist == ‘Drake’) %>%
distinct(song)
billboard100 %>%
select(date:artist, weeks_popular='weeks-on-board’) %>%
filter(artist == ‘Drake’) %>%
distinct(song) %>%
.$song
group_by(): Group data into rows with same value
billboard100 %>%
select(date:artist, weeks_popular='weeks-on-board’) %>%
filter(artist == ‘Drake’) %>%
group_by(song)
summarise(): Summarise data into rows of values
billboard100 %>%
select(date:artist, weeks_popular='weeks-on-board’) %>%
filter(artist == ‘Drake’) %>%
group_by(song) %>%
summarise(total_weeks_popular = max (weeks_popular))
arrange(): Order rows by values of a column (Low to High)
billboard100 %>%
select(date:artist, weeks_popular='weeks-on-board’) %>%
filter(artist == ‘Drake’) %>%
group_by(song) %>%
summarise(total_weeks_popular = max (weeks_popular)) %>%
arrange(total_weeks_popular)
billboard100 %>%
select(date:artist, weeks_popular='weeks-on-board’) %>%
filter(artist == ‘Drake’) %>%
group_by(song) %>%
summarise(total_weeks_popular = max (weeks_popular)) %>%
arrange(desc(total_weeks_popular), song)
billboard100 %>%
select(date:artist, weeks_popular='weeks-on-board’) %>%
filter(artist == ‘Drake’) %>%
group_by(song) %>%
summarise(total_weeks_popular = max (weeks_popular)) %>%
arrange(desc(total_weeks_popular), song) %>%
head(10)
count(): Count number of rows with each unique
value of variable
billboard100 %>%
select(date:artist, weeks_popular='weeks-on-board’) %>%
count(artist)
billboard100 %>%
select(date:artist, weeks_popular='weeks-on-board’) %>%
count(artist) %>%
arrange(desc(n))
Data Wrangling using dplyr
#"data plier" or "data manipulator" # Arrange rows by mpg in descending order
[Link]("dplyr") mtcars_arranged <- mtcars %>% arrange(desc(mpg))
library(dplyr) print(mtcars_arranged)
# Select only the mpg, cyl, and hp columns # Add a new column that calculates power-to-weight ratio
(hp/wt)
mtcars_selected <- mtcars %>% select(mpg, cyl, hp)
mtcars_mutated <- mtcars %>% mutate(power_to_weight =
print(mtcars_selected) hp / wt)
print(mtcars_mutated)
# Filter rows where mpg is greater than 20
mtcars_filtered <- mtcars %>% filter(mpg > 20) # Calculate the average mpg for each number of cylinders
print(mtcars_filtered) mtcars_summarized <- mtcars %>%
group_by(cyl) %>%
summarize(avg_mpg = mean(mpg, [Link] = TRUE))
print(mtcars_summarized)
Using ODBC to connect to SQL
# Install necessary packages # Fetch data
[Link]("DBI") query <- "SELECT * FROM actor"
[Link]("odbc") data <- dbGetQuery(con, query)
# Load the packages # Display the data
library(DBI) print(data)
library(odbc)
# Close the connection
# Set up the connection dbDisconnect(con)
con <- dbConnect(odbc::odbc(),
Driver = "SQL Server",
Server = "NOOR-PC\\SQLEXPRESS",
Database = "sakila",
Trusted_Connection = "Yes",
Port = 1433) # Default port for SQL Server
Line Plot
#[Link]("ggplot2")
library(ggplot2)
# Line plot with economics dataset
ggplot(data=economics, aes(x=date, y=pop)) +
geom_line() +
labs(title="Population Over Time",
x="Date",
y="Population")
Using existing data (data frames)
Simple Scatter Plot
# Install and load ggplot2
#[Link]("ggplot2")
library(ggplot2)
?mtcars
# Simple scatter plot with mtcars dataset
ggplot(data=mtcars, aes(x=wt, y=mpg)) +
geom_point() +
labs(title="Scatter Plot of Weight vs MPG",
x="Weight",
y="Miles per Gallon")
Scatter Plot with Color by Factor
# Install and load ggplot2
#[Link]("ggplot2")
library(ggplot2)
# Scatter plot with points colored by number of cylinders
ggplot(data=mtcars, aes(x=wt, y=mpg, color=factor(cyl))) +
geom_point() +
labs(title="Scatter Plot of Weight vs MPG",
x="Weight",
y="Miles per Gallon",
color="Cylinders")
Bar Chart
# Install and load ggplot2
#[Link]("ggplot2")
library(ggplot2)
# Bar chart with mtcars dataset
ggplot(data=mtcars, aes(x=factor(cyl))) +
geom_bar() +
labs(title="Count of Cars by Cylinder",
x="Number of Cylinders",
y="Count")
Bar Chart with Fill
# Install and load ggplot2
#[Link]("ggplot2")
library(ggplot2)
# Bar chart with fill by number of gears
ggplot(data=mtcars, aes(x=factor(cyl), fill=factor(gear))) +
geom_bar() +
labs(title="Count of Cars by Cylinder and Gear",
x="Number of Cylinders",
fill="Number of Gears")
Histogram
# Install and load ggplot2
#[Link]("ggplot2")
library(ggplot2)
# Histogram of MPG
ggplot(data=mtcars, aes(x=mpg)) +
geom_histogram(binwidth=2, fill="blue", color="black") +
labs(title="Histogram of MPG",
x="Miles per Gallon",
y="Frequency")
Boxplot
# Install and load ggplot2
#[Link]("ggplot2")
library(ggplot2)
# Boxplot of MPG by number of cylinders
ggplot(data=mtcars, aes(x=factor(cyl), y=mpg)) +
geom_boxplot() +
labs(title="Boxplot of MPG by Cylinder",
x="Number of Cylinders",
y="Miles per Gallon")
Mispriced Diamonds
Plotting diamonds
mydata <- [Link]([Link]())
[Link]("ggplot2")
ggplot(data=mydata, aes(x=carat, y=price)) + geom_point()
ggplot(data=mydata, aes(x=carat, y=price, colour=clarity)) + geom_point()
ggplot(data=mydata, aes(x=carat, y=price, colour=clarity)) + geom_point(alpha=0.1)
ggplot(data=mydata[mydata$carat<2.5,], aes(x=carat, y=price, colour=clarity)) +
geom_point(alpha=0.1)
ggplot(data=mydata[mydata$carat<2.5,], aes(x=carat, y=price, colour=clarity)) +
geom_point(alpha=0.1) + geom_smooth()
library(ggplot2)
diamond_data <- [Link]([Link]())
# Simple XY Chart black color
ggplot(data=diamond_data,
aes(x=carat, y=price)) +
geom_point()
# XY chart with legends
ggplot(data=diamond_data,
aes(x=carat, y=price, color=clarity)) +
geom_point()
# XY chart with legends alpha (to smooth the points)
ggplot(data=diamond_data,
aes(x=carat, y=price, color=clarity)) +
geom_point(alpha=0.1)
# XY chart with legends alpha (to smooth the points)
# restrict data to be below 2.5
ggplot(data=diamond_data[diamond_data$carat<2.5&diamond_data$carat>1.5,],
aes(x=carat, y=price, color=clarity)) +
geom_point(alpha=0.1)
# XY chart with legends alpha (to smooth the points)# restrict data to be below 2.5
# Smooth lines to idenfity trends
ggplot(data=diamond_data[diamond_data$carat<2.5,],
aes(x=carat, y=price, color=clarity)) +
geom_point(alpha=0.1) + geom_smooth()
Further Reading
• Animated Charts using ggplot
• [Link]
• Python vs. R
• [Link]
Thank you!