0% found this document useful (0 votes)
8 views18 pages

Stat 131 R

The document provides an introduction to R, a software suite for data manipulation, calculation, and graphical display, detailing its history, basic functionalities, and the RStudio interface. It covers fundamental concepts such as assignment operators, atomic classes of objects, arithmetic operations, and data structures like vectors, lists, matrices, and data frames. Additionally, it explains how to create and access data frames, emphasizing their importance in data analysis.

Uploaded by

srroldan
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)
8 views18 pages

Stat 131 R

The document provides an introduction to R, a software suite for data manipulation, calculation, and graphical display, detailing its history, basic functionalities, and the RStudio interface. It covers fundamental concepts such as assignment operators, atomic classes of objects, arithmetic operations, and data structures like vectors, lists, matrices, and data frames. Additionally, it explains how to create and access data frames, emphasizing their importance in data analysis.

Uploaded by

srroldan
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

STAT 131 PARAMETRIC STATISTICAL INFERENCE

Introduction to R

I. R BASICS
What is R
R is an integrated suite of software facilities for data manipulation, calculation and graphical display. Among
other things it has
• an effective data handling and storage facility, a suite of operators for calculations on arrays,in particular
matrices,
• a large, coherent, integrated collection of intermediate tools for data analysis,
• graphical facilities for data analysis and display either directly at the computer or on hardcopy, and
• a well developed, simple and effective programming language (called ’S) which includes conditionals,
loops, user defined recursive functions and input and output facilities.

Brief History
R was created in 1993 by Ross Ihaka and Robert Gentleman at the University of Auckland as an
open-source alternative to the S programming language, developed in the 1970s at Bell Laboratories. It
gained popularity in the 2000s due to its free nature and powerful statistical capabilities. The R Foundation
was established in 2000 to support its development. Over time, R became a core tool in data science, with
the rise of packages like ggplot2 and dplyr. Today, R is widely used for statistical analysis, data visualization,
and data science.

R Windows
RStudio’s interface is organized into four primary panes/windows:
1. Source Window/ Text editor/ Script editor - this is where you write and edit your R scripts/codes
2. Console Window - a window where outputs are displayed and where codes are executed.
3. Environment/History Window - a multi-tabbed panes where the executed objects (e.g. variables,
vectors, lists, data frames, tables, matrices, etc.) and executed commands are stored
4. Files/Plots/Packages Window - a multi-tabbed panes that provides access to your file system,
displayed plots, installed packages, R help documentation, and a viewer for various outputs

The Assignment Operator


<- or = is use to assign a value or set of values to a variable/object. In practice, the variable/object names in
R must not start with numbers and must not contain any spaces. Of course, choose your variable names to
be meaningful so you can remember them.
x <- 3
x

## [1] 3
paste("The given number is", x)

## [1] "The given number is 3"

1
y = 4
y

## [1] 4
z <- "Hello World"
z

## [1] "Hello World"

Atomic Classes of Objects


R has five basic or “atomic” classes of objects:
1. Character -letters, words, or even whole sentences written with “ ” or ’ ’.
2. Numeric (real numbers) - numbers in R are generally treated as numeric objects (i.e., double
precision real numbers)
3. Integer - integer numbers, not double precision real numbers
4. Complex - numbers with imaginary value i
5. Logical or Boolean values - True (T) or False (F) values

char <- "Hello World"


char

1. Character
## [1] "Hello World"
firstname <-"Juan"
surname <- "Dela Cruz"
fullname <- paste(firstname,surname)
fullname

## [1] "Juan Dela Cruz"


class(char)

## [1] "character"
class(fullname)

## [1] "character"

num1 <-32
num2 <- [Link](num1)
class(num1)

2. Numeric
## [1] "numeric"
class(num2)

## [1] "integer"

int1 <- 3L
int2 <- 2L
int1+int2

2
3. Integer
## [1] 5
class(int1)

## [1] "integer"
class(int2)

## [1] "integer"
[Link](int1)

## [1] TRUE
[Link](int1)

## [1] TRUE
[Link](int1)

## [1] FALSE
[Link](int1)

## [1] FALSE
[Link](int1)

## [1] FALSE

comp <- 3+1i


class(comp)

4. Complex
## [1] "complex"

logi <- TRUE


logi1 <- T
logi2 <- F
class(logi)

5. Logical
## [1] "logical"
class(logi1)

## [1] "logical"

Arithmetic Operators and some Mathematical Functions in R R can be used to perform mathe-
matical operations using standard arithmetic operators and built-in functions, making it a powerful tool for
calculations and data analysis. Some arithmetic operators and built-in mathematical functions are:
• Addition: +
• Sum: sum()
• Subtraction: -
• Multiplication: *

3
• Division: /
• Square Root:sqrt()
• Natural Log:log()
• Exponentiation: ˆ
• Exponential function: exp()

14+15

Addition
## [1] 29
a<-223
b<-331
a+b

## [1] 554
sum(a,b)

## [1] 554

a<-223
b<-331
a-b

Subtraction
## [1] -108
b-a

## [1] 108

4*5

Multiplication
## [1] 20
a*b

## [1] 73813

100/4

Division
## [1] 25
a/b

## [1] 0.673716
b/2

## [1] 165.5

4
sqrt(81)

Square Root
## [1] 9
sqrt(4489)

## [1] 67
c <- 100
sqrt(c)

## [1] 10

log(1)

Natural Log
## [1] 0
log(100)

## [1] 4.60517

2ˆ4

Exponentiation
## [1] 16
9ˆ2

## [1] 81
3ˆ1

## [1] 3

exp(1)

Exponential function
## [1] 2.718282
exp(log(2))

## [1] 2
exp(a/3)

## [1] 1.91671e+32
2ˆexp(1)

## [1] 6.580886

5
R Objects
An object is a data structure that stores data and/or functions. A data structure is a way of organizing,
storing, and accessing data efficiently. Almost everything you work with in R, like vectors, data frames,
functions, or even models is considered an object.

1. Vectors A vector in R is an ordered collection of values, and is a data type that is fundamental to
how R functions. Vectors can only hold elements of the same data type (e.g., all numeric, all character). All
elements of an atomic vector must be the same type, so when you attempt to combine different types they will
be coerced to the most flexible type. Types from least to most flexible are: logical, integer, double (numeric),
complex, and character. Atomic vectors are usually created with c(), short for combine or concatenate.
vec <- c(32,22,52,43,12) #concatenate function c()
vec

## [1] 32 22 52 43 12
length(vec) # this returns the number of elements a vector contains

## [1] 5
vec2 <- c("John", "Juan", "Ben", "Anne", "Peter")
vec2

## [1] "John" "Juan" "Ben" "Anne" "Peter"


paste("The age of", vec2,"is",vec,sep=" ")

## [1] "The age of John is 32" "The age of Juan is 22" "The age of Ben is 52"
## [4] "The age of Anne is 43" "The age of Peter is 12"
To access elements in a vector, use square brackets [] with an index, where the index represents the element’s
position from left to right, starting from 1.
vec[1]

## [1] 32
vec[3]

## [1] 52
vec2[2]

## [1] "Juan"
vec2[6]

## [1] NA
We can also perform operations using the accessed elements of a vector by accessing individual elements using
their index and then performing calculations or manipulations on those values. Some examples:
vec[1]-vec[3]

## [1] -20
vec[5]/2

## [1] 6
sum(vec)

## [1] 161

6
1.1 Sequence of Numbers A sequence of numbers is an ordered list of numbers and can be generated
using functions like seq() or the colon operator :. In the context of R, sequences of elements are considered
vectors.
seq1 <- 1:99
seq1

## [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
## [26] 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
## [51] 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
## [76] 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
[Link](seq1)

## [1] TRUE
seq2 <- 5:16
seq2

## [1] 5 6 7 8 9 10 11 12 13 14 15 16
[Link](seq2)

## [1] TRUE
length(seq1)

## [1] 99
length(seq2)

## [1] 12

2. Lists A list is a data structure that can contain multiple items of different data types like numbers,
characters and also vectors and data [Link] construct lists by using list() instead of c().
list1 <-list("John", 18, "M", 165)
list1

## [[1]]
## [1] "John"
##
## [[2]]
## [1] 18
##
## [[3]]
## [1] "M"
##
## [[4]]
## [1] 165
Lists are sometimes called recursive vectors, because a list can contain other lists. This makes them
fundamentally different from vectors.
x <- list(1:3, "a", c(TRUE, FALSE, TRUE), c(2.3, 5.9))
str(x) # str() stands for "structure", this displays structures or contents of R objects

## List of 4
## $ : int [1:3] 1 2 3
## $ : chr "a"

7
## $ : logi [1:3] TRUE FALSE TRUE
## $ : num [1:2] 2.3 5.9

3. Matrices and Arrays Array can be thought of as an n-dimensional vector and a special case of the
array is the matrix, which has two dimensions. Matrices are used commonly as part of the mathematical
machinery of statistics. Arrays are much rarer, but worth being aware of. Matrices and arrays are created
with matrix() and array(), or by using the assignment form of dim():
# Array
arr <- array(1:12, c(2, 3, 2)) # here we have 3 dimensional array (row=2, column=3, layer=2)
arr

## , , 1
##
## [,1] [,2] [,3]
## [1,] 1 3 5
## [2,] 2 4 6
##
## , , 2
##
## [,1] [,2] [,3]
## [1,] 7 9 11
## [2,] 8 10 12
#Matrix
mat1 <- matrix(1:6, ncol = 3, nrow = 2)
mat1

## [,1] [,2] [,3]


## [1,] 1 3 5
## [2,] 2 4 6
We can see that the matrix is filled column-wise. This can be reversed to row-wise filling by passing TRUE
to the argument byrow.
mat1 <- matrix(1:6, ncol = 3, nrow = 2, byrow = TRUE)
mat1

## [,1] [,2] [,3]


## [1,] 1 2 3
## [2,] 4 5 6
mat2 <- 1:6
dim(mat2) <- c(3, 2)
mat2

## [,1] [,2]
## [1,] 1 4
## [2,] 2 5
## [3,] 3 6
dim(mat2) <- c(2, 3)
mat2

## [,1] [,2] [,3]


## [1,] 1 3 5
## [2,] 2 4 6

8
4. Data frame A data frame is the most common way of storing data in R, and if used systematicallymakes
data analysis easier. A data frame is a list of equal-length vectors. This makes it a 2-dimensional structure,
so it shares properties of both the matrix and the list. To create a data frame, use [Link](), which
takes named vectors as input.
4.1 Creation
name <- c("John","Agatha","Mark","Matthew","Anne","Mary","Elizabeth")
age <- c(18,20,19,20,17,19,18)
sex <- c("M","F","M","M","F","F","F")

data1 <- [Link](name,sex,age)


data1

## name sex age


## 1 John M 18
## 2 Agatha F 20
## 3 Mark M 19
## 4 Matthew M 20
## 5 Anne F 17
## 6 Mary F 19
## 7 Elizabeth F 18
4.2 Accessing of Columns, Rows, and Elements in a Data Frame
To access each column in a data frame, use [] operator and specify the column index. To access each row
in a [Link], use the same operator but with , after the index. The , means “all columns,” so you’re
selecting all columns for that specific row.
data1[1]

## name
## 1 John
## 2 Agatha
## 3 Mark
## 4 Matthew
## 5 Anne
## 6 Mary
## 7 Elizabeth
data1[3]

## age
## 1 18
## 2 20
## 3 19
## 4 20
## 5 17
## 6 19
## 7 18
data1[1,]

## name sex age


## 1 John M 18
data1[3,]

## name sex age


## 3 Mark M 19

9
To access the elements of a particular varible in a data frame, use $, following the syntax dataframe-
name$variablename.
data1$name

## [1] "John" "Agatha" "Mark" "Matthew" "Anne" "Mary"


## [7] "Elizabeth"
data1$sex

## [1] "M" "F" "M" "M" "F" "F" "F"


data1$age

## [1] 18 20 19 20 17 19 18
Attach Function
To avoid repeatedly typing the data frame name, use attach(). This function allows you to refer to the
column names of a [Link] directly by their names without needing to specify the data frame each time.
attach(data1)

name

## [1] "John" "Agatha" "Mark" "Matthew" "Anne" "Mary"


## [7] "Elizabeth"
sex

## [1] "M" "F" "M" "M" "F" "F" "F"


age

## [1] 18 20 19 20 17 19 18

[Link] STATISTICS IN R
A. Descriptive Measures
The cars dataset gives Speed and Stopping Distances of Cars. This dataset is a data frame with 50 rows and
2 variables. The rows refer to cars and the variables refer to speed (the numeric Speed in mph) and dist (the
numeric stopping distance in ft.)
data("cars")
head(cars) # to display the first few observations from the dataset

## speed dist
## 1 4 2
## 2 4 10
## 3 7 4
## 4 7 22
## 5 8 16
## 6 9 10
ncol(cars) # number of columns

## [1] 2
nrow(cars) # number of rows

## [1] 50

10
attach(cars)

mean(speed)

1. Measures of Central Tendency


## [1] 15.4
median(speed)

## [1] 15
#[Link]("DescTools")
library(DescTools)
Mode(speed)

## [1] 20
## attr(,"freq")
## [1] 5

lv <- min(speed)
hv <- max(speed)
range <- hv-lv
range

2. Measures of Dispersion
## [1] 21
var(speed) # variance

## [1] 27.95918
sqrt(var(speed)) # standard deviation

## [1] 5.287644
sd(speed) # standard deviation

## [1] 5.287644
CV <- mean(speed)/sd(speed)
CV

## [1] 2.91245

quantile(speed,probs =0.25) # First Quartile or 25th Percentile

3. Measures of Location
## 25%
## 12
quantile(speed,probs =0.04) # 4th Percentile

## 4%
## 6.88

11
quantile(speed,probs =c(0.25,0.50,0.75))

## 25% 50% 75%


## 12 15 19
summary(speed) # displays the min, Q1, Median, Mean, Q3, max

## Min. 1st Qu. Median Mean 3rd Qu. Max.


## 4.0 12.0 15.0 15.4 19.0 25.0

4. Measures of Skewness
The functions skewness() and kurtosis() are from the package “moments”. Install and load first the
package before using them.
#[Link]("moments")
library(moments)
skewness(speed)

## [1] -0.1139548
kurtosis(speed)

## [1] 2.422853

B. Visualizing Data in R
Data visualization plays a crucial role in understanding patterns, trends, and relationships within datasets.
In R programming, several built-in functions allow us to create basic yet powerful graphical presentations.
Some commonly used built-in plotting functions in R include:
• plot() – versatile base function for scatter plots and line graphs.
• hist() – for creating histograms
• barplot() – for bar charts
• boxplot() – to show distributions and outliers
• pie() – for pie charts

While these functions are useful and quick to implement, they often offer limited flexibility when it comes
to customization and [Link] is where the ggplot2 package comes in. Built on the Grammar of
Graphics, ggplot2 allows for more polished, professional, and layered visualizations. It provides an elegant
way to build plots by adding components like titles, legends, themes, and annotations in a modular fashion.

Throughout this section, we’ll explore how ggplot2 can transform basic plots into visually compelling data
stories. For discussion purposes, we will be using the mtcarsand Johnson & Johnson Quartely Earnings
per Sharedata sets The mtcars data was extracted from the 1974 Motor Trend US magazine, and comprises
fuel consumption and 10 aspects of automobile design and performance for 32 automobiles (1973–74 models).

Description of variables:
• mpg: Miles/(US) gallon
• cyl: Number of cylinders
• disp: Displacement ([Link].)
• hp: Gross horsepower
• drat: Rear axle ratio
• wt: Weight (1000 lbs)
• qsec: 1/4 mile time

12
• vs: V/S
• am: Transmission (0 = automatic, 1 = manual)
• gear: Number of forward gears
• carb: Number of carburetors
The Johnson & Johnson Quarterly Earnings per Share dataset provides a historical record of quarterly
earnings, measured in dollars, per Johnson & Johnson share from 1960 to 1980. This time series dataset is
commonly used for time series analysis and is sourced from “Time Series Analysis and its Applications” by
Shumway and Stoffer, Second Edition, published by Springer in 2000.
data("mtcars")
head(mtcars)

## mpg cyl disp hp drat wt qsec vs am gear carb


## Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
## Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
## Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
## Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
## Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
## Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
attach(mtcars)

Install and load ggplot2 package.


#[Link]("ggplot2")
library(ggplot2)

ggplot(mtcars, aes(x = mpg, y = hp)) +


geom_point(size = 2, color = "darkgreen") +
labs(title = "Scatter Plot of MPG vs Horsepower",
x = "Miles per Gallon", y = "Horsepower") +
theme_minimal() +
theme([Link] = element_text(size = 15),
[Link].x = element_text(size = 12),
[Link].y = element_text(size = 12))

B.1 Scatter Plots


Scatter Plot of MPG vs Horsepower

300
Horsepower

200

100

10 15 20 25 30 35
Miles per Gallon

13
# With factor
ggplot(mtcars, aes(x=mpg, y=hp, col=factor(cyl))) + geom_point(size=2) +
labs(title="Scatter Plot of MPG vs Horsepower", x="Miles per Gallon", y="Horsepower") +
scale_color_manual(name = "Number of Cylinders:",values=c("red", "blue", "green")) +
theme_minimal() +
theme([Link] = element_text(size = 15),
[Link].x = element_text(size = 12),
[Link].y = element_text(size = 12),
[Link] = "top",
[Link] = element_text(size = 9),
[Link] = unit(0.3, "cm"))

Scatter Plot of MPG vs Horsepower


Number of Cylinders: 4 6 8

300
Horsepower

200

100

10 15 20 25 30 35
Miles per Gallon

ggplot(mtcars, aes(x=mpg, y=hp)) +


geom_line(color = "darkgreen") +
labs(title="Line Plot of MPG vs Horsepower", x="Miles per Gallon", y="Horsepower") +
theme_minimal()

B.2 Line Graphs

14
Line Plot of MPG vs Horsepower

300

Horsepower

200

100

10 15 20 25 30 35
Miles per Gallon
Import The Johnson & Johnson Quarterly Earnings per Share dataset.
library(readr)
Johnson_Johnson <- read_csv("Datasets /Johnson&[Link]")
head(Johnson_Johnson)

## # A tibble: 6 x 4
## ...1 X time value
## <dbl> <dbl> <dbl> <dbl>
## 1 1 1 1960 0.71
## 2 2 2 1960. 0.63
## 3 3 3 1960. 0.85
## 4 4 4 1961. 0.44
## 5 5 5 1961 0.61
## 6 6 6 1961. 0.69
attach(Johnson_Johnson)

ggplot(Johnson_Johnson, aes(x=time, y=value)) +


geom_line(color="maroon") +
labs(title="Line Graph of Johnson and Johnson Quarterly Earnings", x="Time",
y="Earnings (in million $)") +
scale_x_continuous(breaks = seq(from = min(time), to = max(time), by = 1)
) + theme_minimal()

15
Line Graph of Johnson and Johnson Quarterly Earnings

15
Earnings (in million $)

10

0
1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980
Time

ggplot(mtcars, aes(x = factor(cyl))) +


geom_bar(fill = "darkblue") +
labs(title = "Bar Plot of the Number of Cylinders",
x = "Number of Cylinders",
y = "Count") +
theme_minimal()

B.3 Bar Plots


Bar Plot of the Number of Cylinders

10
Count

0
4 6 8
Number of Cylinders
ggplot(mtcars, aes(x = factor(cyl, ordered = TRUE), fill = factor(gear, ordered = TRUE))) +
geom_bar() +
labs(title = "Bar Plot of Cylinders by Gear",
x = "Number of Cylinders",
y = "Count") +
scale_fill_manual(name = "Gear", values = c("3" = "gold", "4" = "orange", "5" = "red")) +
theme_minimal()

16
Bar Plot of Cylinders by Gear

Count 10 Gear
3
4
5 5

0
4 6 8
Number of Cylinders

B.4 Histogram

ggplot(mtcars, aes(x=mpg, fill="red")) +


geom_histogram(binwidth=3, color="black", size=0.2) +
labs(title="Histogram of MPG", x="Miles per Gallon", y="Frequency") +
theme_minimal() +
theme([Link] = "none")

Histogram of MPG
8

6
Frequency

0
10 15 20 25 30 35
Miles per Gallon

B.5 Boxplots

ggplot(mtcars, aes(x = factor(cyl, ordered = TRUE), y = mpg, fill = factor(cyl, ordered = TRUE))) +
geom_boxplot() +
labs(title = "Box Plot of MPG by Cylinders",
x = "Number of Cylinders",
y = "Miles per Gallon") +
scale_fill_manual(values = c("4" = "red", "6" = "green", "8" = "blue")) + # Manually set colors
theme_minimal() +

17
theme([Link] = "none")

Box Plot of MPG by Cylinders


35

30
Miles per Gallon

25

20

15

10
4 6 8
Number of Cylinders

B.6 Pie Chart

#sample data
data <- [Link](category = c("Category A", "Category B", "Category C", "Category D",
"Category E"), value = factor( c(3,20,17,26,34),
ordered = TRUE))
ggplot(data, aes(x = "", y = value, fill = category)) +
geom_bar(stat = "identity", width = 1) + # Use bars with 100% width
coord_polar(theta = "y") + # Convert to polar coordinates to make a pie chart
labs(title = "Pie Chart", fill = "Legend") + # Change legend title here
theme_void() + # Remove axis and gridlines
geom_text(aes(label = paste(value, "%")), position = position_stack(vjust = 0.5)) +
scale_fill_manual(values = c("lightyellow", "yellow2", "gold", "orange", "red"))

Pie Chart

Legend
3%
17 % Category A
34 %
Category B
Category C
20 %
Category D
26 % Category E

18

You might also like