SlideShare a Scribd company logo
R 語⾔言與資料分析
objects (物件) & categorical variables
Vectorized Operations
Many operations in R are vectorized making code more efficient, concise, and easier to read.
> x <- 1:4; y <- 6:9
> x + y
[1] 7 9 11 13
> x > 2
[1] FALSE FALSE TRUE TRUE
> x >= 2
[1] FALSE TRUE TRUE TRUE
> y == 8
[1] FALSE FALSE TRUE FALSE
> x * y
[1] 6 14 24 36
> x / y
[1] 0.1666667 0.2857143 0.3750000 0.4444444
Vectorized MatrixOperations
> x <- matrix(1:4, 2, 2); y <- matrix(rep(10, 4), 2, 2)
> x * y ## element-wise multiplication
[,1] [,2]
[1,] 10 30
[2,] 20 40
> x / y
[,1] [,2]
[1,] 0.1 0.3
[2,] 0.2 0.4
> x %*% y
[,1] [,2]
[1,] 40 40
[2,] 60 60
Matrix:`colnames()`&`rownames()`
> temp <- matrix(c(rep(0,9), rep(c(0,1,0), c(3,3,3))), nrow = 2)
> temp
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
[1,] 0 0 0 0 0 0 1 1 0
[2,] 0 0 0 0 0 0 1 0 0
> temp <- matrix(c(rep(0,9), rep(c(0,1,0), c(3,3,3))), nrow = 2, byrow = T)
> temp
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
[1,] 0 0 0 0 0 0 0 0 0
[2,] 0 0 0 1 1 1 0 0 0
> baseball.score = temp
> rownames(baseball.score)
NULL
> colnames(baseball.score)
NULL
> rownames(baseball.score) <- c('guest', 'home')
> baseball.score
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
guest 0 0 0 0 0 0 0 0 0
home 0 0 0 1 1 1 0 0 0
> colnames(baseball.score) <- c('1st', '2nd', '3rd', '4th', '5th', '6th', '7th',
'8th', '9th')
> baseball.score
1st 2nd 3rd 4th 5th 6th 7th 8th 9th
guest 0 0 0 0 0 0 0 0 0
home 0 0 0 1 1 1 0 0 0
charactervectors
generate random samples of characters
> colors <- c("red", "orange", "yellow", "green", "blue", "indigo", "violet")
> length(colors) ### 計算 vector ⻑⾧長度
[1] 7
> colors[7] ### 回傳第七項
[1] "violet"
> colors[7] <- "purple" ### 把第七項換成 "purple"
> colors <- c("red", "orange", "yellow", "green", "blue", "indigo", "violet")
> sample(colors)
[1] "violet" "yellow" "orange" "blue" "green" "indigo" "red"
> sample(colors, size=5)
[1] "indigo" "red" "blue" "green" "violet"
> sample(colors, size=5, replace=TRUE)
[1] "violet" "yellow" "indigo" "violet" "violet"
sample(x) # randomly permute the entire vector of state names
sample(x, 4) # randomly picks four states
sample(x, replace=TRUE) # selection with replacement
charactermatrix
> gender <- sample(c("Male", "Female"), 20, rep=TRUE)
> gender
[1] "Male" "Male" "Female" "Male" "Female" "Female" "Female" "Female"
[9] "Female" "Female" "Female" "Male" "Male" "Female" "Male" "Male"
[17] "Female" "Female" "Female" "Male"
> blood.type <-sample(c("A", "B", "AB", "O"), 20, rep=TRUE)
> blood.type
[1] "B" "O" "A" "O" "O" "O" "A" "B" "O" "A" "AB" "O" "B" "B"
[15] "A" "O" "A" "AB" "O" "O"
> gender.blood.type <- cbind(gender, blood.type)
> gender.blood.type
gender blood.type
[1,] "Male" "B"
[2,] "Male" "O"
[3,] "Female" "A"
[4,] "Male" "O"
[5,] "Female" "O"
[6,] "Female" "O"
[7,] "Female" "A"
[8,] "Female" "B"
[9,] "Female" "O"
[10,] "Female" "A"
[11,] "Female" "AB"
[12,] "Male" "O"
[13,] "Male" "B"
[14,] "Female" "B"
[15,] "Male" "A"
[16,] "Male" "O"
[17,] "Female" "A"
[18,] "Female" "AB"
[19,] "Female" "O"
[20,] "Male" "O"
> xtabs( ~ gender + blood.type, data = gender.blood.type)
blood.type
gender A AB B O
Female 4 2 2 4
Male 1 0 2 5
charactermatrix(cont’d)
Factors
Factors are used to represent categorical data.
Factors can be unordered or ordered
A factor as an integer vector where each integer has a label.
Factors are treated specially by modelling functions like lm() and glm()
Using factors with labels is better than using integers because factors are self-describing
e.g., having a variable that has values “Male” and “Female” is better than a variable that has values 1 and 2.
> x <- factor(c("yes", "yes", "no", "yes", "no"))
> x
[1] yes yes no yes no
Levels: no yes
> table(x)
x
no yes
2 3
> unclass(x)
[1] 2 2 1 2 1
attr(,"levels")
[1] "no" "yes"
8
Factors
The order of the levels can be set using the levels argument to factor(). This can be important in
linear modelling because the first level is used as the baseline level.
> x <- factor(c("yes", "yes", "no", "yes", "no"),
levels = c("yes", "no"))
> x
[1] yes yes no yes no
Levels: yes no
> colors <- c("red", "orange", “yellow", "green", "blue", "indigo", "violet")
# 隨機抽出 colors 裡⾯面的單位 50 次,可重複。
# 計算各種名稱出現之次數
Factors
As an example of an ordered factor, consider data consisting of the names of months:
> mons = c("March","April","January","November","January",
+ "September","October","September","November","August",
+ "January","November","November","February","May","August",
+ "July","December","August","August","September","November",
+ "February","April")
> mons
[1] "March" "April" "January" "November" "January" "September" "October" "September"
[9] "November" "August" "January" "November" "November" "February" "May" "August"
[17] "July" "December" "August" "August" "September" "November" "February" "April"
> summary(mons)
Length Class Mode
24 character character
> mons = factor(mons)
> table(mons)
mons
April August December February January July March May November October
2 4 1 2 3 1 1 1 5 1
September
3
Factors (cont’d)
The order of months is not reflected in the output of the `table` function. Creating an order factor solves
this problem:
> mons = factor(mons,levels=c("January","February","March",
+ "April","May","June","July","August","September",
+ "October","November","December"),
+ ordered=TRUE)
> table(mons)
mons
January February March April May June July August September October
3 2 1 2 1 0 1 4 3 1
November December
5 1
> head(mons)
[1] March April January November January September
12 Levels: January < February < March < April < May < June < July < August < ... < December
> mons[1] < mons[2]
[1] TRUE
> mons[1] < mons[3]
[1] FALSE
> mons[3] == mons[5]
[1] TRUE

More Related Content

What's hot

Day 1c access, select ordering copy.pptx
Day 1c   access, select   ordering copy.pptxDay 1c   access, select   ordering copy.pptx
Day 1c access, select ordering copy.pptx
Adrien Melquiond
 
Day 2b i/o.pptx
Day 2b   i/o.pptxDay 2b   i/o.pptx
Day 2b i/o.pptx
Adrien Melquiond
 
PureScript & Pux
PureScript & PuxPureScript & Pux
PureScript & Pux
Arthur Xavier
 
Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語
ikdysfm
 
Python 2.5 reference card (2009)
Python 2.5 reference card (2009)Python 2.5 reference card (2009)
Python 2.5 reference card (2009)
gekiaruj
 
Tugas 3 oganisasi komputer 23510310
Tugas 3 oganisasi komputer 23510310Tugas 3 oganisasi komputer 23510310
Tugas 3 oganisasi komputer 23510310
Putu Shinoda
 
Data types
Data typesData types
Data types
Rajesh Kone
 
Basic operations by novi reandy sasmita
Basic operations by novi reandy sasmitaBasic operations by novi reandy sasmita
Basic operations by novi reandy sasmita
beasiswa
 
Python Puzzlers
Python PuzzlersPython Puzzlers
Python Puzzlers
Tendayi Mawushe
 
Constraint propagation
Constraint propagationConstraint propagation
Constraint propagation
Peet Denny
 
R programming
R programmingR programming
R programming
Pramodkumar Jha
 
Python data structures
Python data structuresPython data structures
Python data structures
Harry Potter
 
Object Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in PythonObject Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in PythonTendayi Mawushe
 
Python PCEP Tuples and Dictionaries
Python PCEP Tuples and DictionariesPython PCEP Tuples and Dictionaries
Python PCEP Tuples and Dictionaries
IHTMINSTITUTE
 

What's hot (16)

Python lecture 05
Python lecture 05Python lecture 05
Python lecture 05
 
Day 1c access, select ordering copy.pptx
Day 1c   access, select   ordering copy.pptxDay 1c   access, select   ordering copy.pptx
Day 1c access, select ordering copy.pptx
 
Day 2b i/o.pptx
Day 2b   i/o.pptxDay 2b   i/o.pptx
Day 2b i/o.pptx
 
PureScript & Pux
PureScript & PuxPureScript & Pux
PureScript & Pux
 
Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語
 
Python 2.5 reference card (2009)
Python 2.5 reference card (2009)Python 2.5 reference card (2009)
Python 2.5 reference card (2009)
 
Tugas 3 oganisasi komputer 23510310
Tugas 3 oganisasi komputer 23510310Tugas 3 oganisasi komputer 23510310
Tugas 3 oganisasi komputer 23510310
 
Data types
Data typesData types
Data types
 
Basic operations by novi reandy sasmita
Basic operations by novi reandy sasmitaBasic operations by novi reandy sasmita
Basic operations by novi reandy sasmita
 
Python Puzzlers
Python PuzzlersPython Puzzlers
Python Puzzlers
 
Constraint propagation
Constraint propagationConstraint propagation
Constraint propagation
 
Chapter 6 arrays part-1
Chapter 6   arrays part-1Chapter 6   arrays part-1
Chapter 6 arrays part-1
 
R programming
R programmingR programming
R programming
 
Python data structures
Python data structuresPython data structures
Python data structures
 
Object Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in PythonObject Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in Python
 
Python PCEP Tuples and Dictionaries
Python PCEP Tuples and DictionariesPython PCEP Tuples and Dictionaries
Python PCEP Tuples and Dictionaries
 

Similar to [1062BPY12001] Data analysis with R / week 3

[1062BPY12001] Data analysis with R / week 2
[1062BPY12001] Data analysis with R / week 2[1062BPY12001] Data analysis with R / week 2
[1062BPY12001] Data analysis with R / week 2
Kevin Chun-Hsien Hsu
 
Seminar PSU 09.04.2013 - 10.04.2013 MiFIT, Arbuzov Vyacheslav
Seminar PSU 09.04.2013 - 10.04.2013 MiFIT, Arbuzov VyacheslavSeminar PSU 09.04.2013 - 10.04.2013 MiFIT, Arbuzov Vyacheslav
Seminar PSU 09.04.2013 - 10.04.2013 MiFIT, Arbuzov VyacheslavVyacheslav Arbuzov
 
R Programming Intro
R Programming IntroR Programming Intro
R Programming Intro
062MayankSinghal
 
Ggplot2 v3
Ggplot2 v3Ggplot2 v3
Ggplot2 v3
Josh Doyle
 
R tutorial for a windows environment
R tutorial for a windows environmentR tutorial for a windows environment
R tutorial for a windows environment
Yogendra Chaubey
 
R programming language
R programming languageR programming language
R programming language
Alberto Minetti
 
Useful javascript
Useful javascriptUseful javascript
Useful javascriptLei Kang
 
ifelse.pptx
ifelse.pptxifelse.pptx
ifelse.pptx
JananiJ19
 
6. R data structures
6. R data structures6. R data structures
6. R data structures
ExternalEvents
 
Vectors data frames
Vectors data framesVectors data frames
Vectors data frames
FAO
 
Presentation R basic teaching module
Presentation R basic teaching modulePresentation R basic teaching module
Presentation R basic teaching module
Sander Timmer
 
R Basics
R BasicsR Basics
Pre-Bootcamp introduction to Elixir
Pre-Bootcamp introduction to ElixirPre-Bootcamp introduction to Elixir
Pre-Bootcamp introduction to Elixir
Paweł Dawczak
 
An overview of Python 2.7
An overview of Python 2.7An overview of Python 2.7
An overview of Python 2.7
decoupled
 
A tour of Python
A tour of PythonA tour of Python
A tour of Python
Aleksandar Veselinovic
 
Python
PythonPython
Programming in R
Programming in RProgramming in R
Programming in R
Smruti Sarangi
 

Similar to [1062BPY12001] Data analysis with R / week 3 (20)

[1062BPY12001] Data analysis with R / week 2
[1062BPY12001] Data analysis with R / week 2[1062BPY12001] Data analysis with R / week 2
[1062BPY12001] Data analysis with R / week 2
 
Seminar PSU 09.04.2013 - 10.04.2013 MiFIT, Arbuzov Vyacheslav
Seminar PSU 09.04.2013 - 10.04.2013 MiFIT, Arbuzov VyacheslavSeminar PSU 09.04.2013 - 10.04.2013 MiFIT, Arbuzov Vyacheslav
Seminar PSU 09.04.2013 - 10.04.2013 MiFIT, Arbuzov Vyacheslav
 
R Programming Intro
R Programming IntroR Programming Intro
R Programming Intro
 
Ggplot2 v3
Ggplot2 v3Ggplot2 v3
Ggplot2 v3
 
R tutorial for a windows environment
R tutorial for a windows environmentR tutorial for a windows environment
R tutorial for a windows environment
 
R programming language
R programming languageR programming language
R programming language
 
Useful javascript
Useful javascriptUseful javascript
Useful javascript
 
R learning by examples
R learning by examplesR learning by examples
R learning by examples
 
ifelse.pptx
ifelse.pptxifelse.pptx
ifelse.pptx
 
6. R data structures
6. R data structures6. R data structures
6. R data structures
 
Vectors data frames
Vectors data framesVectors data frames
Vectors data frames
 
Presentation R basic teaching module
Presentation R basic teaching modulePresentation R basic teaching module
Presentation R basic teaching module
 
R Basics
R BasicsR Basics
R Basics
 
Pre-Bootcamp introduction to Elixir
Pre-Bootcamp introduction to ElixirPre-Bootcamp introduction to Elixir
Pre-Bootcamp introduction to Elixir
 
An overview of Python 2.7
An overview of Python 2.7An overview of Python 2.7
An overview of Python 2.7
 
A tour of Python
A tour of PythonA tour of Python
A tour of Python
 
R교육1
R교육1R교육1
R교육1
 
bobok
bobokbobok
bobok
 
Python
PythonPython
Python
 
Programming in R
Programming in RProgramming in R
Programming in R
 

More from Kevin Chun-Hsien Hsu

[1062BPY12001] Data analysis with R / April 26
[1062BPY12001] Data analysis with R / April 26[1062BPY12001] Data analysis with R / April 26
[1062BPY12001] Data analysis with R / April 26
Kevin Chun-Hsien Hsu
 
[1062BPY12001] Data analysis with R / April 19
[1062BPY12001] Data analysis with R / April 19[1062BPY12001] Data analysis with R / April 19
[1062BPY12001] Data analysis with R / April 19
Kevin Chun-Hsien Hsu
 
[1062BPY12001] Data analysis with R / week 4
[1062BPY12001] Data analysis with R / week 4[1062BPY12001] Data analysis with R / week 4
[1062BPY12001] Data analysis with R / week 4
Kevin Chun-Hsien Hsu
 
語言議題
語言議題語言議題
語言議題
Kevin Chun-Hsien Hsu
 
Regression 0410
Regression 0410Regression 0410
Regression 0410
Kevin Chun-Hsien Hsu
 
Statistical computing 03
Statistical computing 03Statistical computing 03
Statistical computing 03
Kevin Chun-Hsien Hsu
 
Statistical computing 01
Statistical computing 01Statistical computing 01
Statistical computing 01
Kevin Chun-Hsien Hsu
 
Statistical computing 00
Statistical computing 00Statistical computing 00
Statistical computing 00
Kevin Chun-Hsien Hsu
 
Chi square
Chi squareChi square
Multiple regression
Multiple regressionMultiple regression
Multiple regression
Kevin Chun-Hsien Hsu
 
Model III ANOVA & Simple Main Effects
Model III ANOVA & Simple Main EffectsModel III ANOVA & Simple Main Effects
Model III ANOVA & Simple Main Effects
Kevin Chun-Hsien Hsu
 
Essentials of EEG/MEG
Essentials of EEG/MEGEssentials of EEG/MEG
Essentials of EEG/MEG
Kevin Chun-Hsien Hsu
 
repeated-measure-ANOVA
repeated-measure-ANOVArepeated-measure-ANOVA
repeated-measure-ANOVA
Kevin Chun-Hsien Hsu
 
Kirk' Experimental Design, Chapter 4
Kirk' Experimental Design, Chapter 4Kirk' Experimental Design, Chapter 4
Kirk' Experimental Design, Chapter 4
Kevin Chun-Hsien Hsu
 
Kirk' Experimental Design, Chapter 3
Kirk' Experimental Design, Chapter 3Kirk' Experimental Design, Chapter 3
Kirk' Experimental Design, Chapter 3
Kevin Chun-Hsien Hsu
 
APA style
APA styleAPA style
資料檢索
資料檢索資料檢索
資料檢索
Kevin Chun-Hsien Hsu
 
Kirk' Experimental Design, Chapter 5
Kirk' Experimental Design, Chapter 5Kirk' Experimental Design, Chapter 5
Kirk' Experimental Design, Chapter 5
Kevin Chun-Hsien Hsu
 
Kirk' Experimental Design, Chapter 2
Kirk' Experimental Design, Chapter 2Kirk' Experimental Design, Chapter 2
Kirk' Experimental Design, Chapter 2
Kevin Chun-Hsien Hsu
 
Kirk' Experimental Design, Chapter 1
Kirk' Experimental Design, Chapter 1Kirk' Experimental Design, Chapter 1
Kirk' Experimental Design, Chapter 1
Kevin Chun-Hsien Hsu
 

More from Kevin Chun-Hsien Hsu (20)

[1062BPY12001] Data analysis with R / April 26
[1062BPY12001] Data analysis with R / April 26[1062BPY12001] Data analysis with R / April 26
[1062BPY12001] Data analysis with R / April 26
 
[1062BPY12001] Data analysis with R / April 19
[1062BPY12001] Data analysis with R / April 19[1062BPY12001] Data analysis with R / April 19
[1062BPY12001] Data analysis with R / April 19
 
[1062BPY12001] Data analysis with R / week 4
[1062BPY12001] Data analysis with R / week 4[1062BPY12001] Data analysis with R / week 4
[1062BPY12001] Data analysis with R / week 4
 
語言議題
語言議題語言議題
語言議題
 
Regression 0410
Regression 0410Regression 0410
Regression 0410
 
Statistical computing 03
Statistical computing 03Statistical computing 03
Statistical computing 03
 
Statistical computing 01
Statistical computing 01Statistical computing 01
Statistical computing 01
 
Statistical computing 00
Statistical computing 00Statistical computing 00
Statistical computing 00
 
Chi square
Chi squareChi square
Chi square
 
Multiple regression
Multiple regressionMultiple regression
Multiple regression
 
Model III ANOVA & Simple Main Effects
Model III ANOVA & Simple Main EffectsModel III ANOVA & Simple Main Effects
Model III ANOVA & Simple Main Effects
 
Essentials of EEG/MEG
Essentials of EEG/MEGEssentials of EEG/MEG
Essentials of EEG/MEG
 
repeated-measure-ANOVA
repeated-measure-ANOVArepeated-measure-ANOVA
repeated-measure-ANOVA
 
Kirk' Experimental Design, Chapter 4
Kirk' Experimental Design, Chapter 4Kirk' Experimental Design, Chapter 4
Kirk' Experimental Design, Chapter 4
 
Kirk' Experimental Design, Chapter 3
Kirk' Experimental Design, Chapter 3Kirk' Experimental Design, Chapter 3
Kirk' Experimental Design, Chapter 3
 
APA style
APA styleAPA style
APA style
 
資料檢索
資料檢索資料檢索
資料檢索
 
Kirk' Experimental Design, Chapter 5
Kirk' Experimental Design, Chapter 5Kirk' Experimental Design, Chapter 5
Kirk' Experimental Design, Chapter 5
 
Kirk' Experimental Design, Chapter 2
Kirk' Experimental Design, Chapter 2Kirk' Experimental Design, Chapter 2
Kirk' Experimental Design, Chapter 2
 
Kirk' Experimental Design, Chapter 1
Kirk' Experimental Design, Chapter 1Kirk' Experimental Design, Chapter 1
Kirk' Experimental Design, Chapter 1
 

Recently uploaded

Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
timhan337
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
Peter Windle
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
CarlosHernanMontoyab2
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
Nguyen Thanh Tu Collection
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 

Recently uploaded (20)

Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 

[1062BPY12001] Data analysis with R / week 3

  • 2. Vectorized Operations Many operations in R are vectorized making code more efficient, concise, and easier to read. > x <- 1:4; y <- 6:9 > x + y [1] 7 9 11 13 > x > 2 [1] FALSE FALSE TRUE TRUE > x >= 2 [1] FALSE TRUE TRUE TRUE > y == 8 [1] FALSE FALSE TRUE FALSE > x * y [1] 6 14 24 36 > x / y [1] 0.1666667 0.2857143 0.3750000 0.4444444
  • 3. Vectorized MatrixOperations > x <- matrix(1:4, 2, 2); y <- matrix(rep(10, 4), 2, 2) > x * y ## element-wise multiplication [,1] [,2] [1,] 10 30 [2,] 20 40 > x / y [,1] [,2] [1,] 0.1 0.3 [2,] 0.2 0.4 > x %*% y [,1] [,2] [1,] 40 40 [2,] 60 60
  • 4. Matrix:`colnames()`&`rownames()` > temp <- matrix(c(rep(0,9), rep(c(0,1,0), c(3,3,3))), nrow = 2) > temp [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [1,] 0 0 0 0 0 0 1 1 0 [2,] 0 0 0 0 0 0 1 0 0 > temp <- matrix(c(rep(0,9), rep(c(0,1,0), c(3,3,3))), nrow = 2, byrow = T) > temp [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [1,] 0 0 0 0 0 0 0 0 0 [2,] 0 0 0 1 1 1 0 0 0 > baseball.score = temp > rownames(baseball.score) NULL > colnames(baseball.score) NULL > rownames(baseball.score) <- c('guest', 'home') > baseball.score [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] guest 0 0 0 0 0 0 0 0 0 home 0 0 0 1 1 1 0 0 0 > colnames(baseball.score) <- c('1st', '2nd', '3rd', '4th', '5th', '6th', '7th', '8th', '9th') > baseball.score 1st 2nd 3rd 4th 5th 6th 7th 8th 9th guest 0 0 0 0 0 0 0 0 0 home 0 0 0 1 1 1 0 0 0
  • 5. charactervectors generate random samples of characters > colors <- c("red", "orange", "yellow", "green", "blue", "indigo", "violet") > length(colors) ### 計算 vector ⻑⾧長度 [1] 7 > colors[7] ### 回傳第七項 [1] "violet" > colors[7] <- "purple" ### 把第七項換成 "purple" > colors <- c("red", "orange", "yellow", "green", "blue", "indigo", "violet") > sample(colors) [1] "violet" "yellow" "orange" "blue" "green" "indigo" "red" > sample(colors, size=5) [1] "indigo" "red" "blue" "green" "violet" > sample(colors, size=5, replace=TRUE) [1] "violet" "yellow" "indigo" "violet" "violet" sample(x) # randomly permute the entire vector of state names sample(x, 4) # randomly picks four states sample(x, replace=TRUE) # selection with replacement
  • 6. charactermatrix > gender <- sample(c("Male", "Female"), 20, rep=TRUE) > gender [1] "Male" "Male" "Female" "Male" "Female" "Female" "Female" "Female" [9] "Female" "Female" "Female" "Male" "Male" "Female" "Male" "Male" [17] "Female" "Female" "Female" "Male" > blood.type <-sample(c("A", "B", "AB", "O"), 20, rep=TRUE) > blood.type [1] "B" "O" "A" "O" "O" "O" "A" "B" "O" "A" "AB" "O" "B" "B" [15] "A" "O" "A" "AB" "O" "O" > gender.blood.type <- cbind(gender, blood.type) > gender.blood.type gender blood.type [1,] "Male" "B" [2,] "Male" "O" [3,] "Female" "A" [4,] "Male" "O" [5,] "Female" "O" [6,] "Female" "O" [7,] "Female" "A" [8,] "Female" "B" [9,] "Female" "O" [10,] "Female" "A" [11,] "Female" "AB" [12,] "Male" "O" [13,] "Male" "B" [14,] "Female" "B" [15,] "Male" "A" [16,] "Male" "O" [17,] "Female" "A" [18,] "Female" "AB" [19,] "Female" "O" [20,] "Male" "O" > xtabs( ~ gender + blood.type, data = gender.blood.type) blood.type gender A AB B O Female 4 2 2 4 Male 1 0 2 5 charactermatrix(cont’d)
  • 7. Factors Factors are used to represent categorical data. Factors can be unordered or ordered A factor as an integer vector where each integer has a label. Factors are treated specially by modelling functions like lm() and glm() Using factors with labels is better than using integers because factors are self-describing e.g., having a variable that has values “Male” and “Female” is better than a variable that has values 1 and 2. > x <- factor(c("yes", "yes", "no", "yes", "no")) > x [1] yes yes no yes no Levels: no yes > table(x) x no yes 2 3 > unclass(x) [1] 2 2 1 2 1 attr(,"levels") [1] "no" "yes"
  • 8. 8 Factors The order of the levels can be set using the levels argument to factor(). This can be important in linear modelling because the first level is used as the baseline level. > x <- factor(c("yes", "yes", "no", "yes", "no"), levels = c("yes", "no")) > x [1] yes yes no yes no Levels: yes no > colors <- c("red", "orange", “yellow", "green", "blue", "indigo", "violet") # 隨機抽出 colors 裡⾯面的單位 50 次,可重複。 # 計算各種名稱出現之次數
  • 9. Factors As an example of an ordered factor, consider data consisting of the names of months: > mons = c("March","April","January","November","January", + "September","October","September","November","August", + "January","November","November","February","May","August", + "July","December","August","August","September","November", + "February","April") > mons [1] "March" "April" "January" "November" "January" "September" "October" "September" [9] "November" "August" "January" "November" "November" "February" "May" "August" [17] "July" "December" "August" "August" "September" "November" "February" "April" > summary(mons) Length Class Mode 24 character character > mons = factor(mons) > table(mons) mons April August December February January July March May November October 2 4 1 2 3 1 1 1 5 1 September 3
  • 10. Factors (cont’d) The order of months is not reflected in the output of the `table` function. Creating an order factor solves this problem: > mons = factor(mons,levels=c("January","February","March", + "April","May","June","July","August","September", + "October","November","December"), + ordered=TRUE) > table(mons) mons January February March April May June July August September October 3 2 1 2 1 0 1 4 3 1 November December 5 1 > head(mons) [1] March April January November January September 12 Levels: January < February < March < April < May < June < July < August < ... < December > mons[1] < mons[2] [1] TRUE > mons[1] < mons[3] [1] FALSE > mons[3] == mons[5] [1] TRUE