SlideShare une entreprise Scribd logo
1  sur  6
Télécharger pour lire hors ligne
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"])

Contenu connexe

Tendances

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
 

Tendances (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
 

Similaire à NCCU: Statistics in the Criminal Justice System, R basics and Simulation - Presented by Yawen Guan, Mar 24, 2018

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
 

Similaire à NCCU: Statistics in the Criminal Justice System, R basics and Simulation - Presented by Yawen Guan, Mar 24, 2018 (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
 

Plus de The Statistical and Applied Mathematical Sciences Institute

Plus 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...
 

Dernier

ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701bronxfugly43
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseAnaAcapella
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxAmanpreet Kaur
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxnegromaestrong
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 

Dernier (20)

ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 

NCCU: Statistics in the Criminal Justice System, R basics and Simulation - Presented by Yawen Guan, Mar 24, 2018

  • 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"])