About

R is a language and environment for statistical computing and graphics.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.

This notebook is a tutorial on how to use R.

Basics Operations

First we will begin with a few basic operations.

Variable assignment

A variable allows you to store values or an object (e.g. a function).

x = 2187
y = 81
vars = c(3,9,27,81,243,729,2187) # This is a vector 
#        1 2 3   4  5   6   7
vars[1] #This calls the first value in the vector vars
## [1] 3

[1] 3

vars[2] #This calls the second value in the vector vars
## [1] 9

[2] 9

vars[1:3] #This calls the first through third values in the vector vars
## [1]  3  9 27

[1:3] 3,9,27

vars #This calls the vector 
## [1]    3    9   27   81  243  729 2187

Common Arithmetic Operations

Below shows some simple arithmetic operations.

multiplication = 20*5
division = 2187/81
exponent = 9^3

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,6

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

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

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

Setting the Working Directory

Before starting to work with R, we need to set the working directory.

Importing Data and Variable Assignment

—Set Working Directory, Choose Directory

il_income = read.csv(file = "data/il_income.csv")
top_il_income = read.csv(file = "data/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]
subtraction = DuPage-Lake
addition = DuPage+Lake
average = (DuPage+Lake)/2

Basic Statistics

mean(il_income$per_capita_income)
## [1] 25164.14
# average of the numbers; a calculated central value of a set of numbers
median(il_income$per_capita_income)
## [1] 24808.5
# the middle number in a set of numbers in value order
quantile(il_income$per_capita_income)
##       0%      25%      50%      75%     100% 
## 14052.00 22666.00 24808.50 26899.75 38931.00
# cutpoints dividing the range of a probability distribution into contiguous intervals with equal probabilities

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 :24808     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  
## 

Vectors

Defining a Vector

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

# vector of numeric values
c(1, 2, 4, 7)
## [1] 1 2 4 7
# 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(90, 85, 65)  # 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] 90 85 65
## 
## [[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] 90 85 65
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] 90 85 65
## 
## [[2]]
## [1] "B"  "C"  "D-"

Member Reference

Using the double square bracket [[]] operator we can reference a member of the list directly.

student[[1]] # Components of the Scores Vector
## [1] 90 85 65

First element of the Scores vector

student[[1]][1]
## [1] 90

First three elements of the Scores vector

scores[[1]][1:3]
## [1] 90 NA NA

Named List Members

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

student = (office_hours = c(TRUE, FALSE, FALSE)) 

# student
# student$scores
# student$grades
# student$office_hours

Data Frames

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("Jupiter", "Earth", "Mars")
type = c( "Gas giant", "Terrestrial","Terrestrial")
diameter = c( 11.209, 1, 0.532)
rotation = c(0.41, 1, 1.03)
rings = c( TRUE, FALSE, FALSE)

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 Jupiter   Gas giant   11.209     0.41  TRUE
## 2   Earth Terrestrial    1.000     1.00 FALSE
## 3    Mars Terrestrial    0.532     1.03 FALSE

Exercises & Resources

Exercises

  • Datacamp - Learn Data Science from your browser:

  • R-tutor - An R intro to stats that explains basic R concepts:

Data Sources

  • “SELECTED ECONOMIC CHARACTERISTICS 2006-2010 American Community Survey 5-Year Estimates” - U.S. Census Bureau. Retrieved 2016-09-09.