Getting Started With
R
Ansley Kasambara
Lecturer in Statistics
Mathematics and Statistics Department
University of Malawi – The Polytechnic
1
What is R?
R is a free open source programming
language for statistical computing and
graphics.
Illustration . . .
Open R
#Create Vectors
x <- 1:5
y <- 6:10
plot(x,y)
Illustration . . .
What is in R’s memory?
‣ ask for this using the “ls()”
command.
ls()
What is RStudio?
R is a free open source integrated
development environment or IDE for R
[the statistical programming language]
RStudio helps keep R more organized
and add more functionality to it [through
additional menus].
Illustration . . .
Open RStudio
#Again, Create Vectors
x <- 1:5
y <- 6:10
plot(x,y)
Create and manage scripts in RStudio
Go to le then new le then RScript . . .
Let’s create and submit new commands
#Create a new variable
z <- 11:15
#Add up x, y, z
sum(x,y,z)
Click on “run” to submit commands.
We can save this le . . .
“save as” this is going to allow us to save this script so that
we can reproduce our analysis.
fi
fi
fi
Other Advantages of RStudio. . .
➡ You can see that you can also create “R
markdown . . .”
Go to le then new le then R markdown . .
➡ You can also create new project
Go to le then New Project
fi
fi
fi
Installing R and RStudio. . .
➡ R and RStudio are free and open source for Mac,
windows and Linux operating system’s.
➡ One should rst install R before RStudio.
➡ To download R, go to [Link]. [Browse the
page to learn more about R]
➡ Go to the CRAN (Comprehensive R Archive Network) link
to download R.
➡ Choose a server closest to your location. R will download
and after the download is complete, then install R.
fi
Installing R and RStudio. . .
➡ To d o w n l o a d S t u d i o , g o t o
[Link]. on this website click
“download” then “Download RStudio
Desktop”. (Select the operating system
and the recommended one is usually
adeqaute)
➡ Install RStudio . . .
Getting Started with R
Hands-on experience
➡ Assigning values to objects in R,
➡ Basic arithmetic functions and
➡ a few other handy things to know.
Hands-on experience . . .
➡ First we assign a value to an object using an equal sign.
‣ For instance, let's create an object x and store in it a
value 11.
x = 11
➡ To see what is stored in an object
print(x)
or
x
Hands-on experience . . .
➡ Instead of an equal to sign, we can
also use a less than and a dash.
‣ For instance, let's create an object
y and store in it a value 7.
y <- 7
y
Hands-on experience . . .
➡ R will easily overwrite values
‣ i.e. let's assign a value 9 to the
object y.
y <- 9
y
Hands-on experience . . .
➡ To see what is in R’s memory . . .
‣ Take a look at the workspace or
‣ Use the “ls( )” command
ls( )
Hands-on experience . . .
➡ Remove objects from R’s memory
using the “rm( )” command
rm(y)
y
Let put back ‘y’
y <- 9
Hands-on experience . . .
➡ Object names in R can include a number or a
period/full stop
For instance . . .
x.1<-14
x.1
➡ But numbers can not appear rst; i.e. . .
1x <- 22
1x
Hands-on experience . . .
➡ Assigning character values to objects by use
of “quotation marks”
For instance . . .
xx<-“ansley”
xx
This can also be done to numbers, i.e. . .
yy <- “1”
yy
Hands-on experience . . .
➡ We may also perform arithmetic operations in R
For instance . . .
11 + 14
7x9
The same operations may also be done on objects in R, i.e. . .
x
y
x+y
z <- x + y
z
Hands-on experience . . .
➡ Other operations in R . . .
x-y
x*y
x/y
x^2
x^2 + y^2
sqrt(y)
y^(1/2)
log(y)
exp(y)
log2(y)
abs(-14)
Hands-on experience . . .
➡ We can create a sequence of integer values
using colon
For instance . . .
2:7
➡ For more general sequences, we can use
“seq” command
For instance . . .
seq(from=1, to=7, by=1)
Hands-on experience . . .
➡ We can also create a sequence of
non-integer values
For instance . . .
seq(from=1, to=7, by=1/3)
➡ Or
seq(from=1, to=7, by=0.25)
Hands-on experience . . .
➡ We can use the “rep” command to
create a vector of repeated of
characters
For instance . . .
rep(1, times=10)
rep(“Kasambara”, times=5)
Hands-on experience . . .
➡ We may want to have a sequence repeated
multiple times
For instance . . .
rep(1:3, times=5)
➡ Or
rep(seq(from=2, to=5, by=0.25), times=5)
➡ Or
rep(c(“m”,”f”), times=5)
Hands-on experience . . .
➡ Let’s create a vector called x . . .
x<-1:5
x
➡ Also create a vector called y . . .
y<-c(1, 3, 5, 7, 9)
y
Helpful Tips in R
➡ Entering incomplete commands in R
i.e. . .
sqrt(y
➡ Using the arrow keys
➡ Comments in the code
e.g. . .
The code below is for . . .
Creating Vectors and Matrices
➡ We can create a vector in R using “c” [concatenate]
command
i.e. . .
x1 <- c(1, 3, 5, 7, 9)
x1
➡ We can also create a vector of character elements by
including quotation marks
e.g. . .
gender <- c(“male”, “female”)
gender
Vectors . . .
➡ We may extract elements of a vector
using square brackets.
➡ Recall vectors x and y . . .
i.e. . .
x
y
Vectors . . .
➡ Extracting the third element in vector y . . .
y[3]
➡ Extracting all elements except the third element . . .
y[-3]
➡ Extracting the rst three elements . . .
y[1:3]
➡ Extracting the rst and fth elements . . .
y[c(1:5)]
➡ Extracting only the elements that are less than 6 . . .
y[y<6]
fi
fi
fi
Matrices . . .
➡ We can construct a matrix of values using the “matrix”
command.
For instance . . .
matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow=3, byrow=TRUE)
and
matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow=3, byrow=FALSE)
➡ Let’s store the matrix in an object called “mat”. . .
mat <- matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow=3,
byrow=TRUE)
mat
Matrices . . .
➡ We can also use square brackets to
extract certain elements from this matrix.
For instance . . .
‣ mat[1, 2]
‣ mat[c(1, 3), 2]
‣ mat[2, ]
‣ mat[ , 1]
Matrices . . .
➡ We can perform element-wise
addition/ subtraction/ multiplication
and division.
For instance . . .
‣ mat*10
Other Manipulations . . .
➡ Consider the vectors x and y:
➡ We may add/ subtract/ multiply and divide a
value to each element in the vector.
For instance . . .
‣ x+10
‣ x-10
‣ x*10
‣ x/10
Other Manipulations . . .
➡ If two vectors are of the same length, we may add/
subtract/ multiply and divide corresponding element.
➡ Reconsider vectors x and y . . .
For instance . . .
‣x
‣y
‣ x+y
‣ x-y
‣ x*y
‣ x/y
Importing Data Into R
1. As much as we can use commands
such as “[Link]( )” command,
2. we can use the import data tab
Importing Data From Excel Into R
Two main options will be to save the data le as:
➡ Comma Separated Values; csv
➡ Tab Delimited Text File; txt
Saving as a csv le is easier and a better way to go:
Go to: File -> Save As -> [Dialog Box]; then
➡ Name: [Link]
➡ Where: Desktop
➡ Format: Comma Separated Values (.csv)
fi
Importing Data Into R
The rst option for importing data is to use the [Link]
command.
You can access the help menu of any command by typing
help([Link])
or
?[Link]
Importing data command:
data1<-[Link]( [Link](), header=TRUE)
fi
fi
Importing Data Into R
We can also import data using a more generic
command [Link]().
data2<-[Link]( [Link](), header=T, sep=“,”)
data2
fi
Importing Data Into R
Importing a text le - Tab Delimited Text File; txt
First save the data as a .txt:
Go to: File -> Save As -> [Dialog Box]; then
➡ Name: [Link]
➡ Where: Desktop
➡ Format: Tab Delimited Text File(.txt)
fi
Importing Data Into R
To import a tab-delimited text le, use the [Link]
command.
data3<-[Link]( [Link](), header=T)
data3
We can also import data using the [Link]
command.
data4<-[Link]( [Link](), header=T, sep=“\t”)
data4
fi
fi
Importing Excel Data File Into R
Using RStudio built-in readxl package and menu.
To import:
➡ Click on File -> Import Dataset -> From Excel
or
➡ Click on Import Dataset [in the workspace] -> From
Excel.
Use the browse and select your data le;
Excel Data File - ExcelData2
Under Import Options
i. Name: Excel_Data_File
ii. Sheet: Default
iii. Range:
iv. Max Rows:
v. Skip:
vi. NA:
vii. Final Two Options:
First Row as Names
Open Data viewer
Importing Excel Data File Into R
i. Name: OtherData
ii. Sheet: Another DataSet
iii. Range: B3:E11
Exporting Data From R
For Instance . . .
Suppose we would like to export data saved in an object named
DataToExport.
The most exible command for exporting data from R is
[Link] command.
We would like to save the le in our current working directory,
name it ExportedFileName and save it as a .csv le format.
[Link](DataToExport, le=“[Link]”, sep=“,”)
fl
fi
fi
Exporting Data From R . . .
For Instance . . .
[Link](DataToExport, le=“[Link]”,
[Link]=FALSE, sep=“,”)
Note: exporting this le using the same name as before
will overwrite the previous le without warning.
fi
fi
fi
Exporting Data From R . . .
Saving the le elsewhere.
For Instance . . .
[Link](DataToExport, le=“/users/Ansley/
Desktop/[Link]”, [Link]=FALSE)
fi
Exporting Data From R . . .
For instance . . .
We can save the le as a tab-delimited text le by adding
“.txt
[Link](DataToExport, le=“/users/Ansley/Desktop/
[Link]”, [Link]=F, sep=“\t”)
or save as a space-delimited by setting
[Link](DataToExport, le=“/users/Ansley/Desktop/
[Link]”, [Link]=F, sep=“ ”)
fi
fi
fi
Getting Started Working With Data in R
Option 1
data1 <— [Link]( le=“/users/Ansley/Desktop/MSE4 Data/
D a t a S e t s / C o n v e r t e d / L u n g C a p D a t a . t x t ”, h e a d e r = T,
stringsAsFactors = T, sep=“\t”)
Option 2
Does not require specifying the le path by using [Link]()
argument
data2 <— [Link]( [Link](), header=T, stringsAsFactors =
T, sep=“\t”) fi
fi
fi
Getting Started Working With Data in R . . .
Option 3
Use the import dataset menu from the workspace
Import dataset . . .
From Text File or
From the Web
Getting Started Working With Data in R . . .
Once the le is selected, we get another window to
specify the name.
Name: LungCapData
Head: Yes
Separator: Tab
Decimal: Period
Quote: Double Quote
fi
Getting Started Working With Data in R . . .
We now have the data saved in 3 different objects
in R, let’s remove data1 and data2 using rm()
command . . .
rm(data1)
rm(data2)
Getting Started Working With Data in R . . .
First command is the dim() command
For instance . . .
dim(LungCapData)
We can view portions of the data:
Using the head() command
head(LungCapData)
or
Using the tail() command
tail(LungCapData)
Getting Started Working With Data in R . . .
Another method of checking whether the data is
imported correctly in RStudio is to use square brackets.
LungCapData[c(5, 6, 7, 8, 9), ]
or use the colon to create a sequence
LungCapData[5:9, ]
or
LungCapData[-(4:722), ]
As already said, we will use this data for most of the
analyses.
Working With Variables and Data in R . . .
Suppose we would like to calculate the mean age in
our sample
mean(Age)
*we get an error message; object “Age” is not
found.
Working With Variables and Data in R . . .
Option 1: Using the Dollar Sign
Let’s demonstrate:
mean(LungCapData$Age)
For instance:
mean(Age)
*still gives an error: object not found
or
Age
*Age for everyone in the dataset: object not found
Working With Variables and Data in R . . .
If we would like to look at the age values, we need
to let R know where Age can be found
LungCapData$Age
Working With Variables and Data in R . . .
Option 2: attach the data
Let’s attach the data using the attach() command . . .
attach(LungCapData)
#attach the the LungCapData in R’a memory
Working With Variables and Data in R . . .
Finding the mean . . .
mean(Age)
Again just for demonstration . . .
Age
Removing the data from R’s memory . . .
detach(LungCapData)
Working With Variables and Data in R . . .
Check the type of variable or class of the variable using
the class() command in R
class(LungCap)
class(Age)
class(Height)
class(Smoke)
class(gender)
class(caesarean)
Working With Variables and Data in R . . .
Check the levels of the factor variables using the
levels() command in R
levels(smoke)
levels(gender)
levels(caesarean)
Working With Variables and Data in R . . .
Generic summary of the data using the summary()
command . . .
summary(LungCapData)
>LungCap, Age and Height - numeric, R summaries using
mean, median, quantiles and so on.
>Smoke, gender and caesarean - factors/ categorical are
summarized using frequencies.
Working With Variables and Data in R . . .
0 for non-smoker
1 for smoker
or
0 for male
1 for female
Example. . .
Let’s create a zeros and ones variable and save it in an object x.
x<—c(0, 1, 1, 1, 0, 0, 0, 0, 0, 0)
Working With Variables and Data in R . . .
Convert a quoted as numeric to categorical /factor
variable using the [Link]() command
For instance . . .
x<—[Link](x)
class(x)
summary(x)
Working With Variables and Data in R . . .
Review . . .
dim(LungCapData)
length(Age)
Age[11:14]
LungCapData[11:14, ]
Subsetting on another level . . .
mean(Age[Gender==“female”])
mean(Age[Gender==“male”])
Working With Variables and Data in R . . .
Create an object called FemData
FemData<—LungCapData[Gender==“female”, ]
Create an object MaleData
MaleData<—LungCapData[Gender==“male”, ]
Let’s con rm if R has indeed subsetted our data correctly
dim(FemData)
dim(MaleData)
fi
Working With Variables and Data in R . . .
Subsetting one step further . . .
MaleOver15 <—LungCapData[Gender==“male”
& Age>15, ]
dim(MaleOver15)
MaleOver15[1:4, ]
Logic Statements and A Few Other Random
Useful Commands in R
Let’s take a look at the rst ve observations
Age[1:5]
temp<—Age>15
temp[1:5]
Use [Link] command so that R returns 0’s and 1’s as
indicators
temp2<—[Link](Age>15)
temp2[1:5]
LungCapData[1:5, ]
fi
fi
Logic Statements and A Few Other Random
Useful Commands in R . . .
For instance: Create a vector indicating those who are female and
smoke
FemSmoke<—Gender==“female” & Smoke==“yes”
FemSmoke[1:5]
Attach the FemSmoke variable to the entire dataset using cbind()
command
MoreData<—cbind(LungCapData, FemSmoke)
MoreData[1:5, ]
Clearing the workspace
rm(list=ls())
Setting Up Your Current Working Directory in R
A working directory is one spot (ie folder 📁) that you
have created for saving saving all your work.
LungCapData <— [Link]( . . .)
attach(LungCapData)
names(LungCapData)
To nd out what current working directory is, use the
getwd() command
getwd()
fi
Setting Up Your Current Working Directory in R
Using setwd() command in R
You will need to specify the path to the folder. . .
setwd(“/users/Ansley/Desktop/MSE4 Data/Working Directory/
Project1”) or
setwd(“~/Desktop/MSE4 Data/Working Directory/Project1”)
Useful tip:
Create an object ProjectWD for working directory
ProjectWD <—“/users/Ansley/Desktop/MSE4 Data/Working
Directory/Project1”
Then set the working directory using this object ProjectWD
setwd(ProjectWD)
Setting Up Your Current Working Directory in R
Check if we have set the current working directory correctly. . .
getwd()
Now let’s do some work . . . create an object MeanAge
MeanAge<-mean(Age)
Let’s also create another object i.e. a vector x: x<-c(1,2,3,4,5)
Another object y: y<-14
And another object z which is a summary
z=summary(LungCapData)
Saving the work progress when done
[Link](“[Link]”)
Setting Up Your Current Working Directory in R
Load the workspace from Project1 from where we left off
➡ First set the working directory
setwd(“/users/Ansley/Desktop/MSE4 Data/Working
Directory/Project1”)
➡ Then check if we have set the working directory correctly
getwd()
➡ Then we can go ahead and load our workspace using the
load command
load(“[Link]”) or
➡ load the workspace image using the [Link] command
load( [Link]())
fi
Working with Scripts in R
➡ Code can be written in any text editor. However,
use scripts within RStudio.
➡ Create a new script using menus
➡ Go to File then New then Rscript. . .
➡ We may also open an existing Rscript
➡ Go to File. . .then Open File . . . an existing Rscript.
➡ Note: We can now see the Rscript on the top left
section called “Sources”
Working with Scripts in R . . .
Let’s load the previous workspace
load(“[Link]”)
To check all that is saved in the workspace
ls()
Calculate and save the mean age.
meanAge<-mean(Age)
make a histogram of Age
hist(Age)
Produce a summary of the data
summary(LungCapData)
Conduct a t-test for comparing mean LungCap of smokers and non-
smokers
[Link](LungCap ~ Smoke)
Installing Packages in R
R is a computing environment where statistical
techniques may be implemented.
Packages are add-ons that can extend R’s
functionality and perform speci c tasks covering a
wide range of modern statistics.
Installing Packages in R . . .
Install packages using the [Link] command
in R or by using the menus in R.
To access help . . .
help([Link])
Let’s install epiR package, we will use it later.
[Link](“epiR”)
Installing Packages in R . . .
Loading the library of commands for that package
For instance . . .
library(epiR)
Libraries disappear when ending an R session
Installing Packages in R . . .
Let’s go back to R . . .
To access the help menu for a particular package
help(package=epiR)
This shows a list of all the functions and commands built into epiR
and we can access help for each of those.
Delete / remove a package, we can do this using the
[Link] command.
For instance. . .
[Link](“epiR”)
Customizing the Look of RStudio
Click on Tools and the Options . . .
A dialogue box appears showing the different
customizations you can do, to change the look of
RStudio to what suits you.
Using The Apply Function in R
De nition: Apply functions are a set of loop functions
in R.
The main difference is that apply functions are more
ef cient than a “for loop”.
*Use stock data
fi
fi
Using The Apply Function in R . . .
The apply function has 3 main components or
arguments…
apply(X, margin, FUN, . . . )
Let’s calculate the mean price of each stock over the 10
days.
See attached script:
apply(X=stockData, margin=2, FUN=mean)
We can ask R to remove any missing values
apply(. . . , [Link]=TRUE)
Using The Apply Function in R . . .
We can store the means in an object
AVG<-apply(. . . )
AVG<-apply(StockData, 2, mean, [Link]=TRUE)
Specialized apply function to calculate the means for
each column using the colMeans command (See
Script)
Using The Apply Function in R . . .
We can store the means in an object
AVG<-apply(. . . )
AVG<-apply(StockData, 2, mean, [Link]=TRUE)
Specialized apply function to calculate the means for
each column using the colMeans command (See
Script)
Using The Apply Function in R . . .
We can store the means in an object
AVG<-apply(. . . )
AVG<-apply(StockData, 2, mean, [Link]=TRUE)
Specialized apply function to calculate the means for
each column using the colMeans command (See
Script)
colMeans(StockData, [Link]=TRUE)
Using The Apply Function in R . . .
Similarly there is a row means command for calculating the row-wise
means.
For example: we can calculate the max price for stock.
apply(X=StockData, MARGIN=2, FUN=max, [Link]=TRUE)
We can also calculate percentiles - calculating the 20th and 80th
percentile
apply(X=StockData, MARGIN=2, FUN=quantile, probs=c(0.2,
.80), [Link]=TRUE)
The apply function can be used to create a plot for each column (see
script)
apply(. . . , FUN=plot, type=“l”)
Making Barcharts Using R
These are useful for summarizing the distribution of a
categorical variable.
A Barchart can be produced using the barplot command
De nition: A bar chart is a visual display of frequency for
each category of a categorical variable or relative
frequency (%) of each category.
fi
Making Barcharts Using R . . .
The frequency table can be produced by using the table command.
Let’s make the frequency table for gender.
table(Gender)
count<-table(Gender)
count
We may also wish to express the barplot using relative frequencies
or percentages.
table(Gender)/725.
percent<-table(Gender)/725
percent
Making Barcharts Using R . . .
Now let’s produce a barchart using the barplot command
barplot(count)
We can also look at the barplot using percentages / relative frequencies
barplot(percent)
barplot(percent, main=“TITLE”, xlab=“Gender”, ylab=“Percent”)
barplot(percent, main=“TITLE”, xlab=“Gender”, ylab=“Percent”, las=1)
barplot(percent, main=“TITLE”, xlab=“Gender”, ylab=“Percent”, las=1,
[Link]=c(“Female”, “Male”))
barplot(percent, main=“TITLE”, xlab=“Gender”, ylab=“Percent”, las=1,
[Link]=c(“Female”, “Male”), horiz=TRUE)
Note: make sure to also change the x and y labels as the are going to appear on
opposite axes.
Making a PieChart in R
We can produce a piechart using the pie command.
For instance. . .
pie(count)
We can add a title using the main argument . . .
pie(count, main=“TITLE HERE”)
If desired, one can add a box to this plot using the box
command.
box()
Making Boxplot Using R
A boxplot is appropriate for summarizing the
distribution of a numerical variable.
We can produce a boxplot using the boxplot command.
Let’s produce a boxplot for the variable LungCap
boxplot(LungCap)
De nitely: A boxplot is a visual display of the ve
number summary.
fi
Making Boxplot Using R . . .
Let’s ask R for the minimum, rst quartile, median,
third quartile and maximum using the quantile
command
quantile(LungCap, probs=c(0, 0.25, 0.5, 0.75, 1)
Add a title for the chart and an x-axis title
boxplot(LungCap, main=“Boxplot”, ylab=“Lung
Capacity”)
Making Boxplot Using R . . .
Change the limits to the y-axis using ylim argument
boxplot(LungCap, main=“Boxplot”, ylab=“Lung
Capacity”, ylim=c(0, 16))
Rotate the values on the y-axis by the las argument
boxplot(LungCap, main=“Boxplot”, ylab=“Lung
Capacity”, ylim=c(0, 16), las=1)
Making Boxplot Using R . . .
Often we may wish to compare two or more boxplots that
are on the same scale.
For example; we may wish to compare the distribution of
Lung Capacities for female to males.
In simple terms; we would like to compare the distribution
of numeric variable for different groups that are formed by
a categorical variable.
This can be accomplished using boxplot command.
boxplot(LungCap ~ Gender)
Making Boxplot Using R . . .
Add a title to the box plot
boxplot(LungCap ~ Gender, main=“Boxplot by
Gender”)
We can also achieve this by subsetting the data using
square brackets
boxplot(LungCap[Gender==“female”],
LungCap[Gender==“male”])
Strati ed Boxplots in R . . .
Strati ed boxplots are useful for examining the relationship
between a categorical variable and a numeric variable within
strata or groups de ned by a third categorical variable.
For instance. . .
Examine the relationship between smoking and lung capacity
within age groups or age strata.
Create an AgeGroup variable
AgeGroups<-cut(Age, breaks=c(0, 13, 15, 17, 25),
labels=c(“<13”, “14/15”, “16/17”, “18+”))
fi
fi
fi
Strati ed Boxplots in R . . .
Check the rst 5 Ages and AgeGroups
Age[1:5]
AgeGroups[1:5]
levels(AgeGroups)
Create a boxplot for lung capacity
boxplot(LungCap, main=“Boxplot”, ylab=“Lung Capacity”, ylim=c(0,
16), las=1)
Boxplot for lung capacity for smokers and non-smokers
boxsplot(LungCap~Smoke, main=“Boxplot”, ylab=“Lung Capacity”,
ylim=c(0, 16), las=1)
fi
fi
Strati ed Boxplots in R . . .
A better way to explore this relationship is within age
groups or strata.
For example, we can look at this relationship for only 18
year olds or older.
We can use the square brackets to achieve this . . .
boxplot(LungCap[Age>=18]~Smoke[Age>=18],
ylab=“Lung Capacity”, main=“LingCap vs Smoke, 18+”,
las=1)
fi
Strati ed Boxplots in R . . .
Let’s produce boxplots to visualize the relationship between Lung Capacity and Smoking within each
Age strata.
Thus create boxplots of Lung capacity for Smokers and Non-smokers for: 13 or younger, 14 - 15, 16 -
17 & 18 or older
Use the command . . .
boxplot(LungCap~Smoke*AgeGroup, main=“Boxplot”, ylab=“LungCap vs Smoke, by
AgeGroup”, ylim=c(0, 16), las=1)
After submitting the command, notice that the labels on the x-axis are overlapping and we can’t see
them all.
Let’s rotate the values by setting “las=2”
We can now compare smokers and non-smokers within each Age strata by comparing boxplots that
are next to each other.
Finally, we can use colors to help separate the groups visually: color no. 4 or blue for non-smokers
and color no. 2 or red for smokers
boxsplot(LungCap~Smoke*AgeGroup, main=“Boxplot”, ylab=“LungCap vs Smoke, by
AgeGroup”, ylim=c(0, 16), las=2, col=c(4, 2))
Having selected only 2 colors for 8 boxplots, R will recycle the colors.
fi
Strati ed Boxplots in R . . .
Now we can see that within the age strata, smokers tend to ha e lower lung capacity than
when we rst examined the relationship between smoking and lung capacity ignoring age.
We can cleanup the the x-axis and strata names a little bit if we like.
#make the plot look nice, with changes x-axis names, legend, etc
First produce the Boxplot again . . .
boxsplot(LungCap~Smoke*AgeGroup, main=“Boxplot”, ylab=“LungCap vs Smoke, by
AgeGroup”, ylim=c(0, 16), las=2, col=c(“blue”, “red”), axes=F, xlab=“Age Strata”)
The add a box around it
box()
Relabel the y-axis
axis(2, at=seq(0, 20, 2), seq(0, 20, 2), las=1)
Relabel the x-axis
axis(1, at=c(1.5, 3.5, 5.5, 7.5), labels=c(“<13”, “14-15”, “16-17”, “18+”))
Add legend
legend(x=5.5, y=4.5, legend =c(“Non-smoke”, “Smoke”), col=c(4, 2), pch=15, cex=0.8)
fi
fi
Histograms in R
A histogram is appropriate for summarizing the distribution of a numeric
variable.
➡ Import the Lung Capacity data and attach it
➡ Check names and the rst 6 observations
We will produce a histogram using the hist command
To access the help menu
help(hist) or ?hist
Let’s produce a histogram for the variable Lung Capacity
hist(LungCap)
Note:
The default in R is to report frequencies
The default title given by R
And the bin width is determined by R
fi
Histograms in R . . .
Let’s change this plot from the default values
1. Change the y-axis to represent probability densities
hist(LungCap, freq=FALSE) or
hist(LungCap, prob=TRUE)
2. Change the y-limit to run from 0 to 0.2
hist(LungCap, prob=TRUE, ylim=c(0, 0.2))
3. Change the bin width using the breaks argument.
hist(LungCap, prob=TRUE, ylim=c(0, 0.2), breaks=7)
#resulting into 8 bins
or
hist(LungCap, prob=TRUE, ylim=c(0, 0.2), breaks=14)
#resulting into 15 bins
Histograms in R . . .
4. The breaks argument can also be used to specify the beak points themselves
hist(LungCap, prob=TRUE, ylim=c(0, 0.2), breaks=c(0, 2, 4, 6, 8, 10, 12, 14, 16))
This can also be done using the seq command
hist(LungCap, prob=TRUE, ylim=c(0, 0.2), breaks=seq(from=0, to=16, by=2))
5. Add a title using the main argument and label the axes
hist(LungCap, prob=TRUE, ylim=c(0, 0.2), breaks=seq(from=0, to=16, by=2),
main=“Histogram for Lung Capacity”, xlab=“Lung Capacity”, las=1)
6. The nal thing would be adding a density curve over this plot using the lines
command
lines(density(LungCap))
7. We can change the color of this line and the width of the line.
lines(density(LungCap), col=2, lwd=3)
Explore the help menu to learn about more things you can change on this plot.
fi
Scatterplots in R
Scatterplots are useful / appropriate for examining the relationship between 2 numeric variables.
➡ Import the Lung Capacity data and Attach the data
➡ Check names
➡ Check class for Age and Height
➡ Summary for Height
Let’s explore the relationship between Height and Age.
We can produce a scatterplot using the plot command
Get help for the command using
help(plot) or ?plot
Before constructing the plot, let’s calculate the Pearson’s correlation using the cor command
De nition: The Pearson’s correlation is used to examine the strength of the linear relationship
between 2 numeric variables.
cor(Age, Height)
#we get a fairly strong linear relationship.
fi
Scatterplots in R . . .
Then we can construct our scatterplot
plot(Age, Height)
#Add the main argument and the labels for the plot
plot(Age, Height, main=“Scatterplot”xlab=“Age”, ylab=“Height”)
#Rotating the values on the y-axis
plot(Age, Height, main=“Scatterplot”xlab=“Age”, ylab=“Height”, las=1)
#Changing the x-axis limits using xlim argument
plot(Age, Height, main=“Scatterplot”xlab=“Age”, ylab=“Height”, las=1, xlim=c(0, 25))
#changing the size of the plot points using cex argument
plot(Age, Height, main=“Scatterplot”xlab=“Age”, ylab=“Height”, las=1, xlim=c(0, 25)),
cex=0.5)
#alternatively, remove the cex argument and put the pch argument (plot character head)
plot(Age, Height, main=“Scatterplot”xlab=“Age”, ylab=“Height”, las=1, xlim=c(0, 25)), pch=8)
#Changing the color of the plot points using col argument
plot(Age, Height, main=“Scatterplot”xlab=“Age”, ylab=“Height”, las=1, xlim=c(0, 25)), pch=8,
col=2)
Scatterplots in R . . .
Even though we have not yet discussed linear regression, we can t the
regression line to the plot.
#predicting height using age
abline(lm(Height~Age))
#changing the color of the line
abline(lm(Height~Age), col=4)
We may wish to add a non-parametric smoother to the plot to describe the
relationship we are observing using splines command
lines([Link](Age, Height))
Note that a spline is just one of the many options for smoothness.
If we want we can change the line type using the lty argument
lines([Link](Age, Height), lty=2, lwd=5)
Explore the help menu to learn more about the plot command.