x <- 24
x
## [1] 24
#x <- y this is wrong
y <- x
y <- 33
y = 77

z = c(1,4,66)
z[1]
## [1] 1
z[3]
## [1] 66
g = z[c(1,3)]
z[1:3]
## [1]  1  4 66
1:15
##  [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15
# In this we will talk about data types
v = "Hussam"
class(v)
## [1] "character"
v = 23
class(v)
## [1] "numeric"
v = TRUE
class(v)
## [1] "logical"
v = "TRUE"
class(v)
## [1] "character"
v = c("m","f", "m", "m", "z")
class(v)
## [1] "character"
v
## [1] "m" "f" "m" "m" "z"
v = as.factor(v)
v
## [1] m f m m z
## Levels: f m z
class(v)
## [1] "factor"
mean(c(1, 44, 600))
## [1] 215
sqrt(100)
## [1] 10
?mean()
## starting httpd help server ... done
mean(c(1, 44, 600)) + sqrt(100)
## [1] 225
?c()
il_income = read.csv(file = "il_income.csv")
head(il_income)
##   rank county per_capita_income population region
## 1    1   Cook             30468    5238216      1
## 2    2 DuPage             38931     933736      2
## 3    3   Lake             38459     703910      2
## 4    4   Will             30791     687263      2
## 5    5   Kane             30645     530847      2
## 6    6  Mason             23937     307343      2
top_il_income = read.csv(file = "top_il_income.csv")
DuPage = il_income$per_capita_income  [2]
DuPage
## [1] 38931
cook = il_income$per_capita_income [1]
DuPage + cook
## [1] 69399
mean(il_income$per_capita_income)
## [1] 25164.14
median(il_income$population)
## [1] 26610
quantile(il_income$population)
##         0%        25%        50%        75%       100% 
##    4135.00   14284.25   26610.00   53319.00 5238216.00
summary(il_income$per_capita_income)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##   14052   22666   24809   25164   26900   38931
h = c(33,2)
h = c("TRUE",FALSE)
# My friend the List
logic_vector = c(TRUE,FALSE,FALSE)
number_vector = c(99,33,23)
my_list = list(logic_vector, number_vector)
my_list
## [[1]]
## [1]  TRUE FALSE FALSE
## 
## [[2]]
## [1] 99 33 23
my_list = list(list_member_1 = logic_vector, list_member_2 = number_vector)
my_list
## $list_member_1
## [1]  TRUE FALSE FALSE
## 
## $list_member_2
## [1] 99 33 23
my_list[[2]] [2]
## [1] 33

About

The goal of this lab is to introduce you to R and RStudio, which you’ll be using throughout the course both to learn the statistical concepts discussed in class, and also to analyze real data and come to informed conclusions. To straighten out which is which: R is the name of the programming language itself , and RStudio is a convenient interface. R provides a wide variety of statistical (linear and nonlinear modelling, classical statistical tests, time-series analysis, classification, clustering, .) and graphical techniques, and is highly extensible.

As the labs progress, you are encouraged to explore beyond what the labs cover; a willingness to experiment will make you a much better programmer. Before we get to that stage, however, you need to build some basic fluency in R.

Setup

Remember to always set your working directory to the source file location. Go to ‘Session’, scroll down to ‘Set Working Directory’, and click ‘To Source File Location’. Read carefully the below and follow the instructions to complete the tasks and answer any questions. Submit your work in Sakai as detailed in previous notes.

Note

For your assignment you may be using different data sets than what is included here. Always read carefully the instructions provided, before executing any included code chunks and/or adding your own code. For clarity, tasks/questions to be completed/answered are highlighted in red color and numbered according to their particular placement in the task section. The red color is only apparent when in Preview mode. Quite often you will need to add your own code chunk.

xecute all code chunks (already included and own added), preview, check integrity, and submit final work (\(html\) file) in Sakai.


Basics Operations

First we will begin with a few basic operations.

Variable assignment

We assign values to variables using the assignment operator ‘=’. Another form of assignment, more general, is the ‘<-’ operator. A variable allows you to store values or an object (e.g. a function).

x = 128
y = 16
z <- 5
vars = c(2,4,8,16,32) # Creates a vector list using the generic combine function 'c' 
x # display value of variable x
## [1] 128
z # displays value of variable z
## [1] 5
vars[1] #This calls the first value in the vector vars
## [1] 2
vars[2] #This calls the second value in the vector vars
## [1] 4
vars[1:3] #This calls the first through third values in the vector vars
## [1] 2 4 8
vars #This calls the vector list
## [1]  2  4  8 16 32

Common Arithmetic Operations

Below shows some simple arithmetic operations.

12*6
## [1] 72
128/16
## [1] 8
9^2
## [1] 81

Basic Data Types

R works with numerous data types. Some of the most basic types are: numeric,integers, logical (Boolean-TRUE/FALSE) and characters (string-"TEXT").

#Type: Character                   
#Example:"TRUE",'23.4'

v = "TRUE"                       
class(v)                           
## [1] "character"
#Type: Numeric                
#Example: 12.3,5

v = 23.5                  
class(v)                   
## [1] "numeric"
#Type: Logical    
#Example: TRUE,FALSE

v = TRUE
class(v)
## [1] "logical"
#Type: Factor (nominal, categorical)
#Example: m f m f m

v = as.factor(c("m", "f", "m"))
class(v)
## [1] "factor"

Functions

R Functions are invoked by its name, followed by the parenthesis, and zero or more arguments.

# The following applies the function 'c' (seen earlier) to combine three numeric values into a vector 
c(1,2,3)
## [1] 1 2 3
# Example of function mean() to calcule the mean of three values
mean(c(5,6,7))
## [1] 6
# Square root of a number
sqrt(99)
## [1] 9.949874

Importing Data and Variable Assignment

# Here we are reading a file of type csv (comma seperated values) typical of many Excel files
il_income = read.csv(file = "il_income.csv")
top_il_income = read.csv(file = "top_il_income.csv")

Arithmetic Operations with Data

We can extract values from the dataset to perform calculations.

DuPage = top_il_income$per_capita_income[1]
Lake = top_il_income$per_capita_income[2]
DuPage-Lake
## [1] 472
DuPage+Lake
## [1] 77390
(DuPage+Lake)/2
## [1] 38695

##### 1) Repeat here the above arithmetic operations code chunk using instead the columns for McHenry and Sangamon counties

Basic Statistics

mean(il_income$per_capita_income)
## [1] 25164.14
median(il_income$per_capita_income)
## [1] 24808.5
quantile(il_income$per_capita_income)
##       0%      25%      50%      75%     100% 
## 14052.00 22666.00 24808.50 26899.75 38931.00
# Summary 
summary(il_income)
##       rank              county   per_capita_income   population     
##  Min.   :  1.00   Adams    : 1   Min.   :14052     Min.   :   4135  
##  1st Qu.: 26.25   Alexander: 1   1st Qu.:22666     1st Qu.:  14284  
##  Median : 51.50   Bond     : 1   Median :24809     Median :  26610  
##  Mean   : 51.50   Boone    : 1   Mean   :25164     Mean   : 126078  
##  3rd Qu.: 76.75   Brown    : 1   3rd Qu.:26900     3rd Qu.:  53319  
##  Max.   :102.00   Bureau   : 1   Max.   :38931     Max.   :5238216  
##                   (Other)  :96                                      
##      region     
##  Min.   :1.000  
##  1st Qu.:3.000  
##  Median :4.000  
##  Mean   :3.735  
##  3rd Qu.:5.000  
##  Max.   :5.000  
## 

##### 2) Repeat here the above basic statistics code chunk using instead the data from the file top_il_income

Vectors

Defining a Vector

A sequence of data elements of the same basic type is defined as a vector.

# vector of numeric values
c(2, 3, 5, 8)
## [1] 2 3 5 8
# vector of logical values.
c(TRUE, FALSE, TRUE)
## [1]  TRUE FALSE  TRUE
# vector of character strings.
c("A", "B", "B-", "C", "D")
## [1] "A"  "B"  "B-" "C"  "D"

Lists

Defining a List

Lists, as opposed to vectors, can hold components of different types.

scores = c(80, 75, 55)  # vector of numeric values                   
grades = c("B", "C", "D-")  # vector of character strings.          

office_hours = c(TRUE, FALSE, FALSE) # vector of logical values.
student = list(scores,grades,office_hours) # list of vectors
student
## [[1]]
## [1] 80 75 55
## 
## [[2]]
## [1] "B"  "C"  "D-"
## 
## [[3]]
## [1]  TRUE FALSE FALSE

List Slicing

We can retrieve components of the list with the single square bracket [] operator.

student[1]     
## [[1]]
## [1] 80 75 55
student[2]
## [[1]]
## [1] "B"  "C"  "D-"
student[3]
## [[1]]
## [1]  TRUE FALSE FALSE
# first two components of the list
student[1:2]
## [[1]]
## [1] 80 75 55
## 
## [[2]]
## [1] "B"  "C"  "D-"

Member Reference

Using the double square bracket [[]] operator we can reference a member of the list directly. Using one bracket [] would still reference the list but will not allow you to extract a particular member of the list.

student[[1]] # Components of the Scores Vector
## [1] 80 75 55

First element of the Scores vector

student[[1]][1]
## [1] 80

First three elements of the Scores vector

student[[1]][1:3]
## [1] 80 75 55

##### 3) Repeat here the above code chunk to extract instead the second element of the grades vector

Named List Members

It’s possible to assign names to list members and reference them by names instead of by numeric indexes.

student = list(myscores = scores, mygrades = grades , myoffice_hours = office_hours) 

student
## $myscores
## [1] 80 75 55
## 
## $mygrades
## [1] "B"  "C"  "D-"
## 
## $myoffice_hours
## [1]  TRUE FALSE FALSE
student$myscores
## [1] 80 75 55
student$mygrades
## [1] "B"  "C"  "D-"
student$myoffice_hours
## [1]  TRUE FALSE FALSE

Matrices

All columns in a matrix must have the same data type and the same length.

Create a numeric matrix of 5 rows and 4 columns made of sequential numbers 1:20

x_mat = matrix(1:20, nrow=5, ncol=4)
x_mat
##      [,1] [,2] [,3] [,4]
## [1,]    1    6   11   16
## [2,]    2    7   12   17
## [3,]    3    8   13   18
## [4,]    4    9   14   19
## [5,]    5   10   15   20

Retrieve the 4th column of matrix

x_mat[,4]
## [1] 16 17 18 19 20

Retrieve the 3rd row of matrix

x_mat[3,]
## [1]  3  8 13 18

Retrieve rows 2,3,4 of columns 1,2,3

x_mat[2:4,1:3]
##      [,1] [,2] [,3]
## [1,]    2    7   12
## [2,]    3    8   13
## [3,]    4    9   14

##### 4) Repeat here the above code chunk to extract instead the third row and thrid column of the matrix

x_mat[,3]
## [1] 11 12 13 14 15
x_mat[3,]
## [1]  3  8 13 18

Data Frames

A data frame is more general than a matrix, in that different columns can have different data types (numeric, character, logic, factor). It is a powerful way to work with mixed data structures.

Defining a Data Frame

When we need to store data in table form, we use data frames, which are created by combining lists of vectors of equal length. The variables of a data set are the columns and the observations are the rows.

The str() function helps us to display the internal structure of any R data structure or object to make sure that it’s correct.

str(il_income)
## 'data.frame':    102 obs. of  5 variables:
##  $ rank             : int  1 2 3 4 5 6 7 8 9 10 ...
##  $ county           : Factor w/ 102 levels "Adams","Alexander",..: 16 22 49 99 45 60 101 64 86 10 ...
##  $ per_capita_income: int  30468 38931 38459 30791 30645 23937 24802 30728 23279 26087 ...
##  $ population       : int  5238216 933736 703910 687263 530847 307343 287078 266209 264052 208861 ...
##  $ region           : int  1 2 2 2 2 2 2 5 5 3 ...

Creating a Data Frame

Snapshot of the solar system.

name = c("Earth", "Mars", "Jupiter")
type = c("Terrestrial","Terrestrial", "Gas giant")
diameter = c(1, 0.532, 11.209)
rotation = c(1, 1.03, 0.41)
rings = c(FALSE, FALSE, TRUE)

Now, by combining the vectors of equal size, we can create a data frame object.

planets_df = data.frame(name,type,diameter,rotation,rings)
planets_df
##      name        type diameter rotation rings
## 1   Earth Terrestrial    1.000     1.00 FALSE
## 2    Mars Terrestrial    0.532     1.03 FALSE
## 3 Jupiter   Gas giant   11.209     0.41  TRUE

Suggested Exercises & Resources

Exercises

Data Sources

Data samples used in this worksheet were downloaded from the U.S. Census Bureau American FactFinder site.