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 = 13623457800986
y = 256789088
vars = c(10,20,30,40,50,60,70,80,90,100) # This is a vector
vars[3] #This calls the third value in the vector vars
## [1] 30
vars[4] #This calls the fourth value in the vector vars
## [1] 40
vars[1:3] #This calls the first through third values in the vector vars
## [1] 10 20 30
vars[1:4] #This calls the first through fourth values in the vector vars
## [1] 10 20 30 40
vars #This calls the vector 
##  [1]  10  20  30  40  50  60  70  80  90 100

Common Arithmetic Operations

Below shows some simple arithmetic operations.

3*3
## [1] 9
100/10
## [1] 10
9^3
## [1] 729

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:"RED",'23.4'

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

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

v = FALSE
class(v)
## [1] "logical"
#Type: Factor
#Example: k a r a r 

v = as.factor(c("k", "a", "r"))
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

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]
DuPage-Lake
## [1] 472
DuPage+Lake
## [1] 77390
(DuPage+Lake)/2
## [1] 38695

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(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(3,6,9,12,15)
## [1]  3  6  9 12 15
# vector of logical values.
c(TRUE, FALSE, TRUE)
## [1]  TRUE FALSE  TRUE
# vector of character strings.
c("A+", "A-", "B+", "B", "B-")
## [1] "A+" "A-" "B+" "B"  "B-"

Lists

Defining a List

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

scores = c(90, 85, 80)  # vector of numeric values                   
grades = c("A+", "B+", "B-")  # vector of character strings.          

office_hours = c(TRUE, TRUE, TRUE) # vector of logical values.
student = list(scores,grades,office_hours) # list of vectors
student
## [[1]]
## [1] 90 85 80
## 
## [[2]]
## [1] "A+" "B+" "B-"
## 
## [[3]]
## [1] TRUE TRUE TRUE

List Slicing

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

student[2]     
## [[1]]
## [1] "A+" "B+" "B-"
student[3]
## [[1]]
## [1] TRUE TRUE TRUE
student[6]
## [[1]]
## NULL
# first two components of the list
student[1:2]
## [[1]]
## [1] 90 85 80
## 
## [[2]]
## [1] "A+" "B+" "B-"

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 80

First element of the Scores vector

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

First three elements of the Scores vector

grades[[1]][1:3]
## [1] "A+" 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 = list(scores = c(93, 85, 65), grades = c("A-", "B+", "D+"), office_hours = c(TRUE, FALSE, FALSE)) 

student
## $scores
## [1] 93 85 65
## 
## $grades
## [1] "A-" "B+" "D+"
## 
## $office_hours
## [1]  TRUE FALSE FALSE
student$scores
## [1] 93 85 65
student$grades
## [1] "A-" "B+" "D+"
student$office_hours
## [1]  TRUE FALSE FALSE

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("Earth", "Venus", "Saturn")
type = c("Terrestrial","Terrestrial", "Gas giant")
diameter = c(2, 0.634, 24.99)
rotation = c(1, 1.03, 0.41)
rings = c(FALSE, TRUE, 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    2.000     1.00 FALSE
## 2  Venus Terrestrial    0.634     1.03  TRUE
## 3 Saturn   Gas giant   24.990     0.41  TRUE

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.