SlideShare una empresa de Scribd logo
1 de 6
Descargar para leer sin conexión
R Basics and Simulation
https://www4.stat.ncsu.edu/~eceyhan/Forensic.html[3/27/2018 11:23:07 AM]
R Basics and Simulation
About R
R is a free software environment for statistical computing and graphics.
Provides a wide variety of statistical and graphical techniques
Many classical and modern statistical techniques have been implemented.
A few of these are built into the base R environment, but many are supplied as packages.
Convinient interface, RStudio. It is an integrated development environment (IDE) for R. It includes a
console, syntax-highlighting editor that supports direct code execution, as well as tools for plotting, history,
debugging and workspace management.
Open R Studio
Frequently Used Data Types and R-Objects
The variables are not declared as some data type.
The variables are assigned with R-Objects and the data type of the R-object becomes the data type of the
variable.
Data Type: Numeric, Integer, Character
## Numeric
## Assign a number to variable num
num <- 3.14
print(num)
## simple calculation by calling the variable
print(num + 1)
## Let's check the data type that has been assigned to num
print(class(num))
## Integer
## Assign the integer part variable num.int
num.int <- as.integer(num)
num.int
## Let's check the data type
class(num.int)
## Character
## Assign the integer part variable num.int
char <- "Hello"
R Basics and Simulation
https://www4.stat.ncsu.edu/~eceyhan/Forensic.html[3/27/2018 11:23:07 AM]
char
## Let's check the data type
class(char)
R-Objects: Vectors, Matrices, Data Frames
# Create a vector with more than one element
# We use c() function which means to combine the elements into a vector
# create a vector of characters
col <- c('red','green',"yellow")
col
# create a vector of numeric
num <- c(1,2,3)
num
# extract elements from vectors
num[1]
# Create a matrices of vectors
# Several way to do this
# Use cbind() function which means column combines
Mcol <- cbind(num,num,num)
Mcol
# Use rbind() function which means row combine
Mrow <- rbind(num,num,num)
Mrow
# Use matrix function to fill in each element
M <- matrix(1:9,nrow=3,ncol=3)
M
# Now lets try combining numeric vector and character vector into a matrix
Mtry <- rbind(num,col)
class(Mtry) # Do you notice what has been changed here?
# extract elements from a matrix
M[1,3]
# Create a data frame
df <- data.frame(x = col, y = num)
df
# extract element from data frame
df$x
df$y[3]
R Basics and Simulation
https://www4.stat.ncsu.edu/~eceyhan/Forensic.html[3/27/2018 11:23:07 AM]
Calculation with R: Multiplication, Log, Exponential ,Power, Square Root
and Some Useful Statistics
# for scaler
x <- 2
x*x
# for vector
num
num + num
y <- c(0,1,2,3,4)
log(y)
# for matrix
M <- matrix(1:9,ncol=3,nrow=3)
exp(M)
sqrt(M)
# for data frame
df
df^2 # why is there a warning message?
# Useful statistics
mean(M)
sum(M)
Simulate Random Variables in R
# generate uniform variable between 0,1
u <- runif(10)
# plot to see what it looks like
plot(u)
hist(u)
# generate more data
u <- runif(1000)
plot(u)
hist(u) # Do you see what has changed?
# sample from a vector
# Type help(sample) to see the function arguments
sampx = sample(x = 1:100, size=1, replace=F)
sampx
# sample 10 numbers from 1-100
R Basics and Simulation
https://www4.stat.ncsu.edu/~eceyhan/Forensic.html[3/27/2018 11:23:07 AM]
sampx = sample(x = 1:100, size=10, replace=F)
sampx
rank(sampx)
# Normal random variable, a very useful random variable used in statistics
n1 <- rnorm(1)
n1
n2 <- rnorm(1)
n2
# Generate a larger sample to see its distribution
n <- rnorm(1000)
plot(n)
hist(n)
plot(density(n), main="Density of n",xlab="n") # remember the shape of the distribution
# set seed to generate the same random number
set.seed(123)
n1 <- rnorm(1)
n1
set.seed(123)
n2 <- rnorm(1)
n2
Why is Normal Distribution so Useful?
# Let's look at some examples
# If we flip 10 coints and count the number of heads.
# what do you think the distribution of the count will look like.
# simulate 30 coin flips
x = sample(c("head","tail"),30,replace = T)
x
# count the number of heads
x == "head"
sum( x == "head" )
# repeat this 1000 times
headcount <- c() # create an empty vector
for (i in 1:1000){
x = sample(c("head","tail"),30,replace = T)
headcount[i] <- sum( x == "head" )
}
hist(headcount,main="Head Count in 30 Coin Flips") # plot the distribution, what do you see?
# How about we simulation from a different distribution?
# simulation from uniform distribution
x = runif(30)
sum(x)
R Basics and Simulation
https://www4.stat.ncsu.edu/~eceyhan/Forensic.html[3/27/2018 11:23:07 AM]
# repeat this 1000 times
sumunif <- c() # create an empty vector
for (i in 1:1000){
x = runif(30)
sumunif[i] <- sum(x)
}
hist(sumunif,main="Sum of Uniform Random Variables") # plot the distribution, what do you see?
# The beam machine
# install.packages("animation")
# library(animation)
# balls = 200
# layers = 15
# ani.options(nmax=balls+layers-2)
# quincunx(balls, layers)
Data Visualization to Classify Glass Fragment Found on “Crime Scene”
library(MASS)
data(fgl)
# See data description
help(fgl)
# Print out part of the data set
head(fgl)
# Plot each composition versus glass type
plot(RI ~ type, data=fgl, col=c(1:6))
plot(Al ~ type, data=fgl, col=c(1:6))
plot(K ~ type, data=fgl, col=c(1:6))
plot(Ca ~ type, data=fgl, col=c(1:6))
# visualize two compositions versus glass type.
# Pick two composition: "Ca" and "K"
# Pick two class types: vehical window glass "Veh", and vehicle hadlamps "Head"
# Can we distinguish these two types of glass based on these two compositions
fgl_subset = subset(fgl,type %in% c("WinNF", "Veh"))
cols = ifelse(fgl_subset[,"type"]=="Veh","blue","red")
set.seed(12)
# pick one observation, pretending that we don't know the glass type
test = 22
fgl_subset[test,c("Ca","K")]
# remake boxplot with a focus on these two type of glass
plot(Ca ~ type, data=fgl_subset, col=c("blue","red"))
abline(h=fgl_subset[test,c("Ca")])
plot(K ~ type, data=fgl_subset, col=c("blue","red"))
abline(h=fgl_subset[test,c("K")])
R Basics and Simulation
https://www4.stat.ncsu.edu/~eceyhan/Forensic.html[3/27/2018 11:23:07 AM]
plot(fgl_subset[-test,c("Ca","K")], col=cols, pch=19,main="Glass type by compositions")
# Add the data points that we left out to see where it lands.
points(fgl_subset[test,c("Ca","K")], col="black", pch=17,cex = 1.5)
legend("topright",col=c("red","blue","black"),legend=c("WinNF","Veh","test case"),pch=c(19,19,17))
# Based on these two composition of the test glass. Can you predict what type of glass it is?
print(fgl_subset[test,"type"])

Más contenido relacionado

La actualidad más candente

R scatter plots
R scatter plotsR scatter plots
R scatter plotsAbhik Seal
 
ggtimeseries-->ggplot2 extensions
ggtimeseries-->ggplot2 extensions ggtimeseries-->ggplot2 extensions
ggtimeseries-->ggplot2 extensions Dr. Volkan OBAN
 
Class 8b: Numpy & Matplotlib
Class 8b: Numpy & MatplotlibClass 8b: Numpy & Matplotlib
Class 8b: Numpy & MatplotlibMarc Gouw
 
simple linear regression
simple linear regressionsimple linear regression
simple linear regressionAkhilesh Joshi
 
A Survey Of R Graphics
A Survey Of R GraphicsA Survey Of R Graphics
A Survey Of R GraphicsDataspora
 
Data Visualization With R: Learn To Modify Font Of Graphical Parameters
Data Visualization With R: Learn To Modify Font Of Graphical ParametersData Visualization With R: Learn To Modify Font Of Graphical Parameters
Data Visualization With R: Learn To Modify Font Of Graphical ParametersRsquared Academy
 
Hive function-cheat-sheet
Hive function-cheat-sheetHive function-cheat-sheet
Hive function-cheat-sheetDr. Volkan OBAN
 
The matplotlib Library
The matplotlib LibraryThe matplotlib Library
The matplotlib LibraryHaim Michael
 
R Data Visualization: Learn To Add Text Annotations To Plots
R Data Visualization: Learn To Add Text Annotations To PlotsR Data Visualization: Learn To Add Text Annotations To Plots
R Data Visualization: Learn To Add Text Annotations To PlotsRsquared Academy
 
Data Visualization With R: Learn To Modify Color Of Plots
Data Visualization With R: Learn To Modify Color Of PlotsData Visualization With R: Learn To Modify Color Of Plots
Data Visualization With R: Learn To Modify Color Of PlotsRsquared Academy
 
random forest regression
random forest regressionrandom forest regression
random forest regressionAkhilesh Joshi
 

La actualidad más candente (20)

Excel/R
Excel/RExcel/R
Excel/R
 
R scatter plots
R scatter plotsR scatter plots
R scatter plots
 
Chapter 6 arrays part-1
Chapter 6   arrays part-1Chapter 6   arrays part-1
Chapter 6 arrays part-1
 
ggtimeseries-->ggplot2 extensions
ggtimeseries-->ggplot2 extensions ggtimeseries-->ggplot2 extensions
ggtimeseries-->ggplot2 extensions
 
Class 8b: Numpy & Matplotlib
Class 8b: Numpy & MatplotlibClass 8b: Numpy & Matplotlib
Class 8b: Numpy & Matplotlib
 
R-Excel Integration
R-Excel IntegrationR-Excel Integration
R-Excel Integration
 
simple linear regression
simple linear regressionsimple linear regression
simple linear regression
 
A Survey Of R Graphics
A Survey Of R GraphicsA Survey Of R Graphics
A Survey Of R Graphics
 
Data Visualization With R: Learn To Modify Font Of Graphical Parameters
Data Visualization With R: Learn To Modify Font Of Graphical ParametersData Visualization With R: Learn To Modify Font Of Graphical Parameters
Data Visualization With R: Learn To Modify Font Of Graphical Parameters
 
Hive function-cheat-sheet
Hive function-cheat-sheetHive function-cheat-sheet
Hive function-cheat-sheet
 
The matplotlib Library
The matplotlib LibraryThe matplotlib Library
The matplotlib Library
 
Python programing
Python programingPython programing
Python programing
 
R Data Visualization: Learn To Add Text Annotations To Plots
R Data Visualization: Learn To Add Text Annotations To PlotsR Data Visualization: Learn To Add Text Annotations To Plots
R Data Visualization: Learn To Add Text Annotations To Plots
 
An introduction to matlab
An introduction to matlabAn introduction to matlab
An introduction to matlab
 
Data Visualization With R: Learn To Modify Color Of Plots
Data Visualization With R: Learn To Modify Color Of PlotsData Visualization With R: Learn To Modify Color Of Plots
Data Visualization With R: Learn To Modify Color Of Plots
 
Uts
UtsUts
Uts
 
Data Visualization With R
Data Visualization With RData Visualization With R
Data Visualization With R
 
R studio
R studio R studio
R studio
 
random forest regression
random forest regressionrandom forest regression
random forest regression
 
WAP to add two given matrices in Java
WAP to add two given matrices in JavaWAP to add two given matrices in Java
WAP to add two given matrices in Java
 

Similar a R Basics and Simulation Guide

2. R-basics, Vectors, Arrays, Matrices, Factors
2. R-basics, Vectors, Arrays, Matrices, Factors2. R-basics, Vectors, Arrays, Matrices, Factors
2. R-basics, Vectors, Arrays, Matrices, Factorskrishna singh
 
R Programming.pptx
R Programming.pptxR Programming.pptx
R Programming.pptxkalai75
 
R programming & Machine Learning
R programming & Machine LearningR programming & Machine Learning
R programming & Machine LearningAmanBhalla14
 
R programming slides
R  programming slidesR  programming slides
R programming slidesPankaj Saini
 
R tutorial for a windows environment
R tutorial for a windows environmentR tutorial for a windows environment
R tutorial for a windows environmentYogendra Chaubey
 
Itroroduction to R language
Itroroduction to R languageItroroduction to R language
Itroroduction to R languagechhabria-nitesh
 
Poetry with R -- Dissecting the code
Poetry with R -- Dissecting the codePoetry with R -- Dissecting the code
Poetry with R -- Dissecting the codePeter Solymos
 
INFORMATIVE ESSAYThe purpose of the Informative Essay assignme.docx
INFORMATIVE ESSAYThe purpose of the Informative Essay assignme.docxINFORMATIVE ESSAYThe purpose of the Informative Essay assignme.docx
INFORMATIVE ESSAYThe purpose of the Informative Essay assignme.docxcarliotwaycave
 
Big Data Mining in Indian Economic Survey 2017
Big Data Mining in Indian Economic Survey 2017Big Data Mining in Indian Economic Survey 2017
Big Data Mining in Indian Economic Survey 2017Parth Khare
 

Similar a R Basics and Simulation Guide (20)

2. R-basics, Vectors, Arrays, Matrices, Factors
2. R-basics, Vectors, Arrays, Matrices, Factors2. R-basics, Vectors, Arrays, Matrices, Factors
2. R-basics, Vectors, Arrays, Matrices, Factors
 
Introduction to r
Introduction to rIntroduction to r
Introduction to r
 
R Programming.pptx
R Programming.pptxR Programming.pptx
R Programming.pptx
 
R basics
R basicsR basics
R basics
 
R Programming Intro
R Programming IntroR Programming Intro
R Programming Intro
 
R Language Introduction
R Language IntroductionR Language Introduction
R Language Introduction
 
R programming & Machine Learning
R programming & Machine LearningR programming & Machine Learning
R programming & Machine Learning
 
R programming slides
R  programming slidesR  programming slides
R programming slides
 
cluster(python)
cluster(python)cluster(python)
cluster(python)
 
R Basics
R BasicsR Basics
R Basics
 
R language introduction
R language introductionR language introduction
R language introduction
 
R tutorial for a windows environment
R tutorial for a windows environmentR tutorial for a windows environment
R tutorial for a windows environment
 
Itroroduction to R language
Itroroduction to R languageItroroduction to R language
Itroroduction to R language
 
Poetry with R -- Dissecting the code
Poetry with R -- Dissecting the codePoetry with R -- Dissecting the code
Poetry with R -- Dissecting the code
 
Ggplot2 v3
Ggplot2 v3Ggplot2 v3
Ggplot2 v3
 
INFORMATIVE ESSAYThe purpose of the Informative Essay assignme.docx
INFORMATIVE ESSAYThe purpose of the Informative Essay assignme.docxINFORMATIVE ESSAYThe purpose of the Informative Essay assignme.docx
INFORMATIVE ESSAYThe purpose of the Informative Essay assignme.docx
 
Big Data Mining in Indian Economic Survey 2017
Big Data Mining in Indian Economic Survey 2017Big Data Mining in Indian Economic Survey 2017
Big Data Mining in Indian Economic Survey 2017
 
proj1v2
proj1v2proj1v2
proj1v2
 
R programming
R programmingR programming
R programming
 
Decision Tree.pptx
Decision Tree.pptxDecision Tree.pptx
Decision Tree.pptx
 

Más de The Statistical and Applied Mathematical Sciences Institute

Más de The Statistical and Applied Mathematical Sciences Institute (20)

Causal Inference Opening Workshop - Latent Variable Models, Causal Inference,...
Causal Inference Opening Workshop - Latent Variable Models, Causal Inference,...Causal Inference Opening Workshop - Latent Variable Models, Causal Inference,...
Causal Inference Opening Workshop - Latent Variable Models, Causal Inference,...
 
2019 Fall Series: Special Guest Lecture - 0-1 Phase Transitions in High Dimen...
2019 Fall Series: Special Guest Lecture - 0-1 Phase Transitions in High Dimen...2019 Fall Series: Special Guest Lecture - 0-1 Phase Transitions in High Dimen...
2019 Fall Series: Special Guest Lecture - 0-1 Phase Transitions in High Dimen...
 
Causal Inference Opening Workshop - Causal Discovery in Neuroimaging Data - F...
Causal Inference Opening Workshop - Causal Discovery in Neuroimaging Data - F...Causal Inference Opening Workshop - Causal Discovery in Neuroimaging Data - F...
Causal Inference Opening Workshop - Causal Discovery in Neuroimaging Data - F...
 
Causal Inference Opening Workshop - Smooth Extensions to BART for Heterogeneo...
Causal Inference Opening Workshop - Smooth Extensions to BART for Heterogeneo...Causal Inference Opening Workshop - Smooth Extensions to BART for Heterogeneo...
Causal Inference Opening Workshop - Smooth Extensions to BART for Heterogeneo...
 
Causal Inference Opening Workshop - A Bracketing Relationship between Differe...
Causal Inference Opening Workshop - A Bracketing Relationship between Differe...Causal Inference Opening Workshop - A Bracketing Relationship between Differe...
Causal Inference Opening Workshop - A Bracketing Relationship between Differe...
 
Causal Inference Opening Workshop - Testing Weak Nulls in Matched Observation...
Causal Inference Opening Workshop - Testing Weak Nulls in Matched Observation...Causal Inference Opening Workshop - Testing Weak Nulls in Matched Observation...
Causal Inference Opening Workshop - Testing Weak Nulls in Matched Observation...
 
Causal Inference Opening Workshop - Difference-in-differences: more than meet...
Causal Inference Opening Workshop - Difference-in-differences: more than meet...Causal Inference Opening Workshop - Difference-in-differences: more than meet...
Causal Inference Opening Workshop - Difference-in-differences: more than meet...
 
Causal Inference Opening Workshop - New Statistical Learning Methods for Esti...
Causal Inference Opening Workshop - New Statistical Learning Methods for Esti...Causal Inference Opening Workshop - New Statistical Learning Methods for Esti...
Causal Inference Opening Workshop - New Statistical Learning Methods for Esti...
 
Causal Inference Opening Workshop - Bipartite Causal Inference with Interfere...
Causal Inference Opening Workshop - Bipartite Causal Inference with Interfere...Causal Inference Opening Workshop - Bipartite Causal Inference with Interfere...
Causal Inference Opening Workshop - Bipartite Causal Inference with Interfere...
 
Causal Inference Opening Workshop - Bridging the Gap Between Causal Literatur...
Causal Inference Opening Workshop - Bridging the Gap Between Causal Literatur...Causal Inference Opening Workshop - Bridging the Gap Between Causal Literatur...
Causal Inference Opening Workshop - Bridging the Gap Between Causal Literatur...
 
Causal Inference Opening Workshop - Some Applications of Reinforcement Learni...
Causal Inference Opening Workshop - Some Applications of Reinforcement Learni...Causal Inference Opening Workshop - Some Applications of Reinforcement Learni...
Causal Inference Opening Workshop - Some Applications of Reinforcement Learni...
 
Causal Inference Opening Workshop - Bracketing Bounds for Differences-in-Diff...
Causal Inference Opening Workshop - Bracketing Bounds for Differences-in-Diff...Causal Inference Opening Workshop - Bracketing Bounds for Differences-in-Diff...
Causal Inference Opening Workshop - Bracketing Bounds for Differences-in-Diff...
 
Causal Inference Opening Workshop - Assisting the Impact of State Polcies: Br...
Causal Inference Opening Workshop - Assisting the Impact of State Polcies: Br...Causal Inference Opening Workshop - Assisting the Impact of State Polcies: Br...
Causal Inference Opening Workshop - Assisting the Impact of State Polcies: Br...
 
Causal Inference Opening Workshop - Experimenting in Equilibrium - Stefan Wag...
Causal Inference Opening Workshop - Experimenting in Equilibrium - Stefan Wag...Causal Inference Opening Workshop - Experimenting in Equilibrium - Stefan Wag...
Causal Inference Opening Workshop - Experimenting in Equilibrium - Stefan Wag...
 
Causal Inference Opening Workshop - Targeted Learning for Causal Inference Ba...
Causal Inference Opening Workshop - Targeted Learning for Causal Inference Ba...Causal Inference Opening Workshop - Targeted Learning for Causal Inference Ba...
Causal Inference Opening Workshop - Targeted Learning for Causal Inference Ba...
 
Causal Inference Opening Workshop - Bayesian Nonparametric Models for Treatme...
Causal Inference Opening Workshop - Bayesian Nonparametric Models for Treatme...Causal Inference Opening Workshop - Bayesian Nonparametric Models for Treatme...
Causal Inference Opening Workshop - Bayesian Nonparametric Models for Treatme...
 
2019 Fall Series: Special Guest Lecture - Adversarial Risk Analysis of the Ge...
2019 Fall Series: Special Guest Lecture - Adversarial Risk Analysis of the Ge...2019 Fall Series: Special Guest Lecture - Adversarial Risk Analysis of the Ge...
2019 Fall Series: Special Guest Lecture - Adversarial Risk Analysis of the Ge...
 
2019 Fall Series: Professional Development, Writing Academic Papers…What Work...
2019 Fall Series: Professional Development, Writing Academic Papers…What Work...2019 Fall Series: Professional Development, Writing Academic Papers…What Work...
2019 Fall Series: Professional Development, Writing Academic Papers…What Work...
 
2019 GDRR: Blockchain Data Analytics - Machine Learning in/for Blockchain: Fu...
2019 GDRR: Blockchain Data Analytics - Machine Learning in/for Blockchain: Fu...2019 GDRR: Blockchain Data Analytics - Machine Learning in/for Blockchain: Fu...
2019 GDRR: Blockchain Data Analytics - Machine Learning in/for Blockchain: Fu...
 
2019 GDRR: Blockchain Data Analytics - QuTrack: Model Life Cycle Management f...
2019 GDRR: Blockchain Data Analytics - QuTrack: Model Life Cycle Management f...2019 GDRR: Blockchain Data Analytics - QuTrack: Model Life Cycle Management f...
2019 GDRR: Blockchain Data Analytics - QuTrack: Model Life Cycle Management f...
 

Último

ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 

Último (20)

ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 

R Basics and Simulation Guide

  • 1. R Basics and Simulation https://www4.stat.ncsu.edu/~eceyhan/Forensic.html[3/27/2018 11:23:07 AM] R Basics and Simulation About R R is a free software environment for statistical computing and graphics. Provides a wide variety of statistical and graphical techniques Many classical and modern statistical techniques have been implemented. A few of these are built into the base R environment, but many are supplied as packages. Convinient interface, RStudio. It is an integrated development environment (IDE) for R. It includes a console, syntax-highlighting editor that supports direct code execution, as well as tools for plotting, history, debugging and workspace management. Open R Studio Frequently Used Data Types and R-Objects The variables are not declared as some data type. The variables are assigned with R-Objects and the data type of the R-object becomes the data type of the variable. Data Type: Numeric, Integer, Character ## Numeric ## Assign a number to variable num num <- 3.14 print(num) ## simple calculation by calling the variable print(num + 1) ## Let's check the data type that has been assigned to num print(class(num)) ## Integer ## Assign the integer part variable num.int num.int <- as.integer(num) num.int ## Let's check the data type class(num.int) ## Character ## Assign the integer part variable num.int char <- "Hello"
  • 2. R Basics and Simulation https://www4.stat.ncsu.edu/~eceyhan/Forensic.html[3/27/2018 11:23:07 AM] char ## Let's check the data type class(char) R-Objects: Vectors, Matrices, Data Frames # Create a vector with more than one element # We use c() function which means to combine the elements into a vector # create a vector of characters col <- c('red','green',"yellow") col # create a vector of numeric num <- c(1,2,3) num # extract elements from vectors num[1] # Create a matrices of vectors # Several way to do this # Use cbind() function which means column combines Mcol <- cbind(num,num,num) Mcol # Use rbind() function which means row combine Mrow <- rbind(num,num,num) Mrow # Use matrix function to fill in each element M <- matrix(1:9,nrow=3,ncol=3) M # Now lets try combining numeric vector and character vector into a matrix Mtry <- rbind(num,col) class(Mtry) # Do you notice what has been changed here? # extract elements from a matrix M[1,3] # Create a data frame df <- data.frame(x = col, y = num) df # extract element from data frame df$x df$y[3]
  • 3. R Basics and Simulation https://www4.stat.ncsu.edu/~eceyhan/Forensic.html[3/27/2018 11:23:07 AM] Calculation with R: Multiplication, Log, Exponential ,Power, Square Root and Some Useful Statistics # for scaler x <- 2 x*x # for vector num num + num y <- c(0,1,2,3,4) log(y) # for matrix M <- matrix(1:9,ncol=3,nrow=3) exp(M) sqrt(M) # for data frame df df^2 # why is there a warning message? # Useful statistics mean(M) sum(M) Simulate Random Variables in R # generate uniform variable between 0,1 u <- runif(10) # plot to see what it looks like plot(u) hist(u) # generate more data u <- runif(1000) plot(u) hist(u) # Do you see what has changed? # sample from a vector # Type help(sample) to see the function arguments sampx = sample(x = 1:100, size=1, replace=F) sampx # sample 10 numbers from 1-100
  • 4. R Basics and Simulation https://www4.stat.ncsu.edu/~eceyhan/Forensic.html[3/27/2018 11:23:07 AM] sampx = sample(x = 1:100, size=10, replace=F) sampx rank(sampx) # Normal random variable, a very useful random variable used in statistics n1 <- rnorm(1) n1 n2 <- rnorm(1) n2 # Generate a larger sample to see its distribution n <- rnorm(1000) plot(n) hist(n) plot(density(n), main="Density of n",xlab="n") # remember the shape of the distribution # set seed to generate the same random number set.seed(123) n1 <- rnorm(1) n1 set.seed(123) n2 <- rnorm(1) n2 Why is Normal Distribution so Useful? # Let's look at some examples # If we flip 10 coints and count the number of heads. # what do you think the distribution of the count will look like. # simulate 30 coin flips x = sample(c("head","tail"),30,replace = T) x # count the number of heads x == "head" sum( x == "head" ) # repeat this 1000 times headcount <- c() # create an empty vector for (i in 1:1000){ x = sample(c("head","tail"),30,replace = T) headcount[i] <- sum( x == "head" ) } hist(headcount,main="Head Count in 30 Coin Flips") # plot the distribution, what do you see? # How about we simulation from a different distribution? # simulation from uniform distribution x = runif(30) sum(x)
  • 5. R Basics and Simulation https://www4.stat.ncsu.edu/~eceyhan/Forensic.html[3/27/2018 11:23:07 AM] # repeat this 1000 times sumunif <- c() # create an empty vector for (i in 1:1000){ x = runif(30) sumunif[i] <- sum(x) } hist(sumunif,main="Sum of Uniform Random Variables") # plot the distribution, what do you see? # The beam machine # install.packages("animation") # library(animation) # balls = 200 # layers = 15 # ani.options(nmax=balls+layers-2) # quincunx(balls, layers) Data Visualization to Classify Glass Fragment Found on “Crime Scene” library(MASS) data(fgl) # See data description help(fgl) # Print out part of the data set head(fgl) # Plot each composition versus glass type plot(RI ~ type, data=fgl, col=c(1:6)) plot(Al ~ type, data=fgl, col=c(1:6)) plot(K ~ type, data=fgl, col=c(1:6)) plot(Ca ~ type, data=fgl, col=c(1:6)) # visualize two compositions versus glass type. # Pick two composition: "Ca" and "K" # Pick two class types: vehical window glass "Veh", and vehicle hadlamps "Head" # Can we distinguish these two types of glass based on these two compositions fgl_subset = subset(fgl,type %in% c("WinNF", "Veh")) cols = ifelse(fgl_subset[,"type"]=="Veh","blue","red") set.seed(12) # pick one observation, pretending that we don't know the glass type test = 22 fgl_subset[test,c("Ca","K")] # remake boxplot with a focus on these two type of glass plot(Ca ~ type, data=fgl_subset, col=c("blue","red")) abline(h=fgl_subset[test,c("Ca")]) plot(K ~ type, data=fgl_subset, col=c("blue","red")) abline(h=fgl_subset[test,c("K")])
  • 6. R Basics and Simulation https://www4.stat.ncsu.edu/~eceyhan/Forensic.html[3/27/2018 11:23:07 AM] plot(fgl_subset[-test,c("Ca","K")], col=cols, pch=19,main="Glass type by compositions") # Add the data points that we left out to see where it lands. points(fgl_subset[test,c("Ca","K")], col="black", pch=17,cex = 1.5) legend("topright",col=c("red","blue","black"),legend=c("WinNF","Veh","test case"),pch=c(19,19,17)) # Based on these two composition of the test glass. Can you predict what type of glass it is? print(fgl_subset[test,"type"])