SlideShare ist ein Scribd-Unternehmen logo
1 von 10
Downloaden Sie, um offline zu lesen
R 語⾔言與資料分析
functions
Control Structures: if
x <- 2
if (x %% 2 == 0) {
print(“divisible by 2")
} else if (x %% 3 == 0) {
print("divisible by 3")
} else
print(“not divisible by 2 nor by 3")
Output
[1] "divisible by 2"
x <- 3
if (x %% 2 == 0) {
print(“divisible by 2")
} else if (x %% 3 == 0) {
print("divisible by 3")
} else
print(“not divisible by 2 nor by 3")
Output
[1] "divisible by 3"
x <- 6
if (x %% 2 == 0) {
print(“divisible by 2")
} else if (x %% 3 == 0) {
print("divisible by 3")
} else
print(“not divisible by 2 nor by 3")
Output
[1] "divisible by 2"
3
The“...”Argument
The ... argument is also necessary when the number of arguments passed to the function cannot be
known in advance.
> args(paste)
function (..., sep = " ", collapse = NULL)
> args(cat)
function (..., file = "", sep = " ", fill = FALSE,
labels = NULL, append = FALSE)
FunctionArguments
Functions have named arguments which potentially have default values.
· The formal arguments are the arguments included in the function definition
· The formals function returns a list of all the formal arguments of a function
· Not every function call in R makes use of all the formal arguments
· Function arguments can be missing or might have default values
> ?sd
> ?rnorm
> ?matrix
> ?sample
x a numeric vector or an R object which is coercible to one by
as.double(x).
na.rm logical. Should missing values be removed?
Description
This function computes the standard deviation of the values in x. If na.rm is TRUE then
missing values are removed before computation proceeds.
Usage
sd(x, na.rm = FALSE)
Arguments
求助範例
(conti.)
說明
語法
參數
回傳值
範例
6
Functions
Functions are created using the function() directive and are stored as R objects just like anything else.
In particular, they are R objects of class “function”.
my.function <- function(<arguments>) {
## body
}
add <- function(x, y = 1) {
x + y
}
> formals(add) # formal arguments
$x
$y
[1] 1
> body(add)
{
x + y
}
> environment(add)
<environment: R_GlobalEnv>
7
LazyEvaluation
Arguments to functions are evaluated lazily, so they are evaluated only as needed.
This function never actually uses the argument b, so calling f(2) will not produce an error because the 2
gets positionally matched to a.
f <- function(a, b) {
a^2
}
f(2)
## [1] 4
In addition to not specifying a default value, you can also set an argument value to NULL.
f <- function(a, b = 1, c = 2, d = NULL) {
}
8
The“...”Argument
The ... argument indicate a variable number of arguments that are usually passed on to other
functions.
· ... is often used when extending another function and you don’t want to copy the entire argument list
of the original function
myplot <- function(x, y, type = "l", ...)
{ plot(x, y, type = type, ...)
}
· Generic functions use ... so that extra arguments can be passed to methods (more on this later).
> mean
function (x, ...)
UseMethod("mean")
9
The“...”Argument
The ... argument is also necessary when the number of arguments passed to the function cannot be
known in advance.
> args(paste)
function (..., sep = " ", collapse = NULL)
> args(cat)
function (..., file = "", sep = " ", fill = FALSE,
labels = NULL, append = FALSE)
10
The“...”Argument
The ... argument is also necessary when the number of arguments passed to the function cannot be
known in advance.
> args(paste)
function (..., sep = " ", collapse = NULL)
> args(cat)
function (..., file = "", sep = " ", fill = FALSE,
labels = NULL, append = FALSE)

Weitere ähnliche Inhalte

Was ist angesagt?

C++ Course - Lesson 2
C++ Course - Lesson 2C++ Course - Lesson 2
C++ Course - Lesson 2
Mohamed Ahmed
 

Was ist angesagt? (18)

Apache Pig Relational Operators - II
Apache Pig Relational Operators - II Apache Pig Relational Operators - II
Apache Pig Relational Operators - II
 
React, Redux, ES2015 by Max Petruck
React, Redux, ES2015 by Max PetruckReact, Redux, ES2015 by Max Petruck
React, Redux, ES2015 by Max Petruck
 
Data Preparation- handling missing value
Data Preparation- handling missing valueData Preparation- handling missing value
Data Preparation- handling missing value
 
Python set
Python setPython set
Python set
 
Haskell 101
Haskell 101Haskell 101
Haskell 101
 
C++ Course - Lesson 2
C++ Course - Lesson 2C++ Course - Lesson 2
C++ Course - Lesson 2
 
Python List Comprehensions
Python List ComprehensionsPython List Comprehensions
Python List Comprehensions
 
Handling Missing Values
Handling Missing Values Handling Missing Values
Handling Missing Values
 
It6312 dbms lab-ex2
It6312 dbms lab-ex2It6312 dbms lab-ex2
It6312 dbms lab-ex2
 
Python programming Part -6
Python programming Part -6Python programming Part -6
Python programming Part -6
 
Cheat sheet python3
Cheat sheet python3Cheat sheet python3
Cheat sheet python3
 
Sql operator
Sql operatorSql operator
Sql operator
 
Python Spell Checker
Python Spell CheckerPython Spell Checker
Python Spell Checker
 
Python For Data Science Cheat Sheet
Python For Data Science Cheat SheetPython For Data Science Cheat Sheet
Python For Data Science Cheat Sheet
 
Merging tables using R
Merging tables using R Merging tables using R
Merging tables using R
 
Python_ 3 CheatSheet
Python_ 3 CheatSheetPython_ 3 CheatSheet
Python_ 3 CheatSheet
 
Python3 cheatsheet
Python3 cheatsheetPython3 cheatsheet
Python3 cheatsheet
 
Macrobrew: Clojure macros distilled
Macrobrew: Clojure macros distilledMacrobrew: Clojure macros distilled
Macrobrew: Clojure macros distilled
 

Ähnlich wie [1062BPY12001] Data analysis with R / April 26

Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013
Kurmendra Singh
 
Lecture 5: Functional Programming
Lecture 5: Functional ProgrammingLecture 5: Functional Programming
Lecture 5: Functional Programming
Eelco Visser
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
Eelco Visser
 
User defined functions
User defined functionsUser defined functions
User defined functions
shubham_jangid
 

Ähnlich wie [1062BPY12001] Data analysis with R / April 26 (20)

Loops and functions in r
Loops and functions in rLoops and functions in r
Loops and functions in r
 
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala
 
R code for data manipulation
R code for data manipulationR code for data manipulation
R code for data manipulation
 
R code for data manipulation
R code for data manipulationR code for data manipulation
R code for data manipulation
 
Lecture 3
Lecture 3Lecture 3
Lecture 3
 
A brief introduction to apply functions
A brief introduction to apply functionsA brief introduction to apply functions
A brief introduction to apply functions
 
Python : Functions
Python : FunctionsPython : Functions
Python : Functions
 
Functional object
Functional objectFunctional object
Functional object
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
 
Lecture 5: Functional Programming
Lecture 5: Functional ProgrammingLecture 5: Functional Programming
Lecture 5: Functional Programming
 
04_python_functions.ppt You can define functions to provide the required func...
04_python_functions.ppt You can define functions to provide the required func...04_python_functions.ppt You can define functions to provide the required func...
04_python_functions.ppt You can define functions to provide the required func...
 
Introduction to R programming
Introduction to R programmingIntroduction to R programming
Introduction to R programming
 
Basic R Data Manipulation
Basic R Data ManipulationBasic R Data Manipulation
Basic R Data Manipulation
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
 
User defined functions
User defined functionsUser defined functions
User defined functions
 
Relations and functions
Relations and functions Relations and functions
Relations and functions
 
Chapter 7 functions (c)
Chapter 7 functions (c)Chapter 7 functions (c)
Chapter 7 functions (c)
 

Mehr von Kevin Chun-Hsien Hsu

Mehr von Kevin Chun-Hsien Hsu (20)

[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
 
[1062BPY12001] Data analysis with R / week 3
[1062BPY12001] Data analysis with R / week 3[1062BPY12001] Data analysis with R / week 3
[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
 
語言議題
語言議題語言議題
語言議題
 
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
 

Kürzlich hochgeladen

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
AnaAcapella
 

Kürzlich hochgeladen (20)

ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
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.
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
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
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
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
 
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
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
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
 
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
 

[1062BPY12001] Data analysis with R / April 26

  • 2. Control Structures: if x <- 2 if (x %% 2 == 0) { print(“divisible by 2") } else if (x %% 3 == 0) { print("divisible by 3") } else print(“not divisible by 2 nor by 3") Output [1] "divisible by 2" x <- 3 if (x %% 2 == 0) { print(“divisible by 2") } else if (x %% 3 == 0) { print("divisible by 3") } else print(“not divisible by 2 nor by 3") Output [1] "divisible by 3" x <- 6 if (x %% 2 == 0) { print(“divisible by 2") } else if (x %% 3 == 0) { print("divisible by 3") } else print(“not divisible by 2 nor by 3") Output [1] "divisible by 2"
  • 3. 3 The“...”Argument The ... argument is also necessary when the number of arguments passed to the function cannot be known in advance. > args(paste) function (..., sep = " ", collapse = NULL) > args(cat) function (..., file = "", sep = " ", fill = FALSE, labels = NULL, append = FALSE)
  • 4. FunctionArguments Functions have named arguments which potentially have default values. · The formal arguments are the arguments included in the function definition · The formals function returns a list of all the formal arguments of a function · Not every function call in R makes use of all the formal arguments · Function arguments can be missing or might have default values > ?sd > ?rnorm > ?matrix > ?sample x a numeric vector or an R object which is coercible to one by as.double(x). na.rm logical. Should missing values be removed? Description This function computes the standard deviation of the values in x. If na.rm is TRUE then missing values are removed before computation proceeds. Usage sd(x, na.rm = FALSE) Arguments
  • 6. 6 Functions Functions are created using the function() directive and are stored as R objects just like anything else. In particular, they are R objects of class “function”. my.function <- function(<arguments>) { ## body } add <- function(x, y = 1) { x + y } > formals(add) # formal arguments $x $y [1] 1 > body(add) { x + y } > environment(add) <environment: R_GlobalEnv>
  • 7. 7 LazyEvaluation Arguments to functions are evaluated lazily, so they are evaluated only as needed. This function never actually uses the argument b, so calling f(2) will not produce an error because the 2 gets positionally matched to a. f <- function(a, b) { a^2 } f(2) ## [1] 4 In addition to not specifying a default value, you can also set an argument value to NULL. f <- function(a, b = 1, c = 2, d = NULL) { }
  • 8. 8 The“...”Argument The ... argument indicate a variable number of arguments that are usually passed on to other functions. · ... is often used when extending another function and you don’t want to copy the entire argument list of the original function myplot <- function(x, y, type = "l", ...) { plot(x, y, type = type, ...) } · Generic functions use ... so that extra arguments can be passed to methods (more on this later). > mean function (x, ...) UseMethod("mean")
  • 9. 9 The“...”Argument The ... argument is also necessary when the number of arguments passed to the function cannot be known in advance. > args(paste) function (..., sep = " ", collapse = NULL) > args(cat) function (..., file = "", sep = " ", fill = FALSE, labels = NULL, append = FALSE)
  • 10. 10 The“...”Argument The ... argument is also necessary when the number of arguments passed to the function cannot be known in advance. > args(paste) function (..., sep = " ", collapse = NULL) > args(cat) function (..., file = "", sep = " ", fill = FALSE, labels = NULL, append = FALSE)