SlideShare a Scribd company logo
1 of 22
Download to read offline
R 語⾔言與資料分析
function, packages, and control flow
求助範例
(conti.)
說明
語法
參數
回傳值
範例
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
Argument Matching
R functions arguments can be matched positionally or by name.
The following calls to sd are all equivalent
> mydata <- rnorm(100)
> sd(mydata)
> sd(x = mydata)
> sd(x = mydata, na.rm = FALSE)
> sd(na.rm = FALSE, x = mydata)
> sd(na.rm = FALSE, mydata)
Argument Matching
You can mix positional matching with matching by name. When an argument is matched by name, it is
“taken out” of the argument list and the remaining unnamed arguments are matched in the order that
they are listed in the function definition.
The following two calls are equivalent.
> args(lm)
function (formula, data, subset, weights, na.action,
method = "qr", model = TRUE, x = FALSE,
y = FALSE, qr = TRUE, singular.ok = TRUE,
contrasts = NULL, offset, ...)
> x = seq(1, 200, 1)
> e = rnorm(200)*50
> y = x * 5 + e
> mydata = data.frame(x, y)
> lm(data = mydata, y ~ x, model = FALSE,1:100)
> lm(y ~ x, mydata, 1:100, model = FALSE)
Practice:subseting&descriptivestatistics
> rm(list = ls())
> iris <- iris # data frame
> iris.1 <- iris$Species == “setosa" # `iris.1`: logical vector
> iris.setosa <- iris[iris.1,] # data frame of `setosa`
> iris.3 <- iris$Species == “virginica" # `iris.3`: logical vector
> iris.virginica <- iris[iris.3,] # data frame of `virginica`
> mean(iris.setosa[,1])
[1] 5.006
> mean(iris.setosa[,2])
[1] 3.428
> mean(iris.setosa[,3])
[1] 1.462
> mean(iris.setosa[,4])
[1] 0.246
> sd(iris.setosa[,1])
[1] 0.3524897
> sd(iris.setosa[,2])
[1] 0.3790644
> sd(iris.setosa[,3])
[1] 0.173664
> sd(iris.setosa[,4])
[1] 0.1053856
Practice:subseting&descriptivestatistics
> mean(iris.setosa[,1])
[1] 5.006
> mean(iris.setosa[,2])
[1] 3.428
> mean(iris.setosa[,3])
[1] 1.462
> mean(iris.setosa[,4])
[1] 0.246
> sd(iris.setosa[,1])
[1] 0.3524897
> sd(iris.setosa[,2])
[1] 0.3790644
> sd(iris.setosa[,3])
[1] 0.173664
> sd(iris.setosa[,4])
[1] 0.1053856
> colMeans(iris.setosa[,-5])
Sepal.Length Sepal.Width Petal.Length Petal.Width
5.006 3.428 1.462 0.246
> apply(iris.setosa[,-5], 2, FUN = mean)
Sepal.Length Sepal.Width Petal.Length Petal.Width
5.006 3.428 1.462 0.246
> apply(iris.setosa[,-5], 2, FUN = sd) # try `min`, `max`, and `length`
Sepal.Length Sepal.Width Petal.Length Petal.Width
0.3524897 0.3790644 0.1736640 0.1053856
R Packages
•・ Select repositories... => 選擇套件所在資源庫 => OK
•・ Packages => Install package(s) => CRAN mirror => installr, rgl,
scatterplot3d (按Ctrl可多重選取) => OK
> install.packages(c(“rgl","scatterplot3d","Rcmdr"))
> install.packages("foreign", repos = "http://cran.csie.ntu.edu.tw")
> library(rgl) # 載⼊入套件,same as > library("rgl")
> detach(package:rgl) # 卸載套件
> remove.packages("rgl") # 移除套件
> .libPaths() # 列出library安裝⽬目錄
R Packages/helps
•・ library(help=“[package name]”) # 檢視套件內容
> library(help=“stats")
•・ ?[package name] # 簡略說明
> ?stats
•・ ?[package name]::[function name] # 函數使⽤用說明
> ?stats::lm
Practice:`psych`package
> library(psych)
> describeBy(iris, group=iris[,5])
Descriptive statistics by group
group: setosa
vars n mean sd median trimmed mad min max range skew kurtosis se
Sepal.Length 1 50 5.01 0.35 5.0 5.00 0.30 4.3 5.8 1.5 0.11 -0.45 0.05
Sepal.Width 2 50 3.43 0.38 3.4 3.42 0.37 2.3 4.4 2.1 0.04 0.60 0.05
Petal.Length 3 50 1.46 0.17 1.5 1.46 0.15 1.0 1.9 0.9 0.10 0.65 0.02
Petal.Width 4 50 0.25 0.11 0.2 0.24 0.00 0.1 0.6 0.5 1.18 1.26 0.01
Species* 5 50 1.00 0.00 1.0 1.00 0.00 1.0 1.0 0.0 NaN NaN 0.00
---------------------------------------------------------------------------
group: versicolor
vars n mean sd median trimmed mad min max range skew kurtosis se
Sepal.Length 1 50 5.94 0.52 5.90 5.94 0.52 4.9 7.0 2.1 0.10 -0.69 0.07
Sepal.Width 2 50 2.77 0.31 2.80 2.78 0.30 2.0 3.4 1.4 -0.34 -0.55 0.04
Petal.Length 3 50 4.26 0.47 4.35 4.29 0.52 3.0 5.1 2.1 -0.57 -0.19 0.07
Petal.Width 4 50 1.33 0.20 1.30 1.32 0.22 1.0 1.8 0.8 -0.03 -0.59 0.03
Species* 5 50 2.00 0.00 2.00 2.00 0.00 2.0 2.0 0.0 NaN NaN 0.00
---------------------------------------------------------------------------
group: virginica
vars n mean sd median trimmed mad min max range skew kurtosis se
Sepal.Length 1 50 6.59 0.64 6.50 6.57 0.59 4.9 7.9 3.0 0.11 -0.20 0.09
Sepal.Width 2 50 2.97 0.32 3.00 2.96 0.30 2.2 3.8 1.6 0.34 0.38 0.05
Petal.Length 3 50 5.55 0.55 5.55 5.51 0.67 4.5 6.9 2.4 0.52 -0.37 0.08
Petal.Width 4 50 2.03 0.27 2.00 2.03 0.30 1.4 2.5 1.1 -0.12 -0.75 0.04
Species* 5 50 3.00 0.00 3.00 3.00 0.00 3.0 3.0 0.0 NaN NaN 0.00
> library(psych)
> describeBy(iris[,-5], group=iris[,5])
Descriptive statistics by group
group: setosa
vars n mean sd median trimmed mad min max range skew kurtosis se
Sepal.Length 1 50 5.01 0.35 5.0 5.00 0.30 4.3 5.8 1.5 0.11 -0.45 0.05
Sepal.Width 2 50 3.43 0.38 3.4 3.42 0.37 2.3 4.4 2.1 0.04 0.60 0.05
Petal.Length 3 50 1.46 0.17 1.5 1.46 0.15 1.0 1.9 0.9 0.10 0.65 0.02
Petal.Width 4 50 0.25 0.11 0.2 0.24 0.00 0.1 0.6 0.5 1.18 1.26 0.01
---------------------------------------------------------------------------
group: versicolor
vars n mean sd median trimmed mad min max range skew kurtosis se
Sepal.Length 1 50 5.94 0.52 5.90 5.94 0.52 4.9 7.0 2.1 0.10 -0.69 0.07
Sepal.Width 2 50 2.77 0.31 2.80 2.78 0.30 2.0 3.4 1.4 -0.34 -0.55 0.04
Petal.Length 3 50 4.26 0.47 4.35 4.29 0.52 3.0 5.1 2.1 -0.57 -0.19 0.07
Petal.Width 4 50 1.33 0.20 1.30 1.32 0.22 1.0 1.8 0.8 -0.03 -0.59 0.03
---------------------------------------------------------------------------
group: virginica
vars n mean sd median trimmed mad min max range skew kurtosis se
Sepal.Length 1 50 6.59 0.64 6.50 6.57 0.59 4.9 7.9 3.0 0.11 -0.20 0.09
Sepal.Width 2 50 2.97 0.32 3.00 2.96 0.30 2.2 3.8 1.6 0.34 0.38 0.05
Petal.Length 3 50 5.55 0.55 5.55 5.51 0.67 4.5 6.9 2.4 0.52 -0.37 0.08
Petal.Width 4 50 2.03 0.27 2.00 2.03 0.30 1.4 2.5 1.1 -0.12 -0.75 0.04
Practice:`psych`package
Practice:`psych`package
> library(psych)
> describeBy(iris, group=iris[,5])
Descriptive statistics by group
group: setosa
vars n mean sd median trimmed mad min max range skew kurtosis se
Sepal.Length 1 50 5.01 0.35 5.0 5.00 0.30 4.3 5.8 1.5 0.11 -0.45 0.05
Sepal.Width 2 50 3.43 0.38 3.4 3.42 0.37 2.3 4.4 2.1 0.04 0.60 0.05
Petal.Length 3 50 1.46 0.17 1.5 1.46 0.15 1.0 1.9 0.9 0.10 0.65 0.02
Petal.Width 4 50 0.25 0.11 0.2 0.24 0.00 0.1 0.6 0.5 1.18 1.26 0.01
Species* 5 50 1.00 0.00 1.0 1.00 0.00 1.0 1.0 0.0 NaN NaN 0.00
---------------------------------------------------------------------------
group: versicolor
vars n mean sd median trimmed mad min max range skew kurtosis se
Sepal.Length 1 50 5.94 0.52 5.90 5.94 0.52 4.9 7.0 2.1 0.10 -0.69 0.07
Sepal.Width 2 50 2.77 0.31 2.80 2.78 0.30 2.0 3.4 1.4 -0.34 -0.55 0.04
Petal.Length 3 50 4.26 0.47 4.35 4.29 0.52 3.0 5.1 2.1 -0.57 -0.19 0.07
Petal.Width 4 50 1.33 0.20 1.30 1.32 0.22 1.0 1.8 0.8 -0.03 -0.59 0.03
Species* 5 50 2.00 0.00 2.00 2.00 0.00 2.0 2.0 0.0 NaN NaN 0.00
---------------------------------------------------------------------------
group: virginica
vars n mean sd median trimmed mad min max range skew kurtosis se
Sepal.Length 1 50 6.59 0.64 6.50 6.57 0.59 4.9 7.9 3.0 0.11 -0.20 0.09
Sepal.Width 2 50 2.97 0.32 3.00 2.96 0.30 2.2 3.8 1.6 0.34 0.38 0.05
Petal.Length 3 50 5.55 0.55 5.55 5.51 0.67 4.5 6.9 2.4 0.52 -0.37 0.08
Petal.Width 4 50 2.03 0.27 2.00 2.03 0.30 1.4 2.5 1.1 -0.12 -0.75 0.04
Species* 5 50 3.00 0.00 3.00 3.00 0.00 3.0 3.0 0.0 NaN NaN 0.00
Practice:`psych`package
> pairs.panels(iris)
Practice:`psych`package
> ppairs.panels(iris,bg=c("red","yellow","blue")[iris$Species],pch=21,main="Fisher
Iris data by Species”)
Control Structures
Control structures in R allow you to control the flow of execution of the program, depending on
runtime conditions. Common structures are
· if,else:testingacondition
· for:executealoopafixednumberoftimes
· while:executealoopwhileaconditionistrue
· repeat:executeaninfiniteloop
· break:breaktheexecutionofaloop
· next:skipaninterationofaloop
· return:exitafunction
Most control structures are not used in interactive sessions, but rather when writing functions or
longer expresisons.
for
for loops take an interator variable and assign it successive values from a sequence or vector. For loops
are most commonly used for iterating over the elements of an object (list, vector, etc.)
This loop takes the i variable and in each iteration of the loop gives it values 1, 2, 3, ..., 10, and then
exits.
for(i in 1:10) {
print(i)
}
for
These three loops have the same behavior.
x <- c("a", "b", "c", "d")
for(i in 1:4) {
print(x[i])
}
for(i in seq_along(x)) {
print(x[i])
}
for(letter in x) {
print(letter)
}
for(i in 1:4) print(x[i])
Nested for loops
for loops can be nested.
Be careful with nesting though. Nesting beyond 2–3 levels is often very difficult to read/understand.
x <- matrix(1:6, 2, 3)
for(i in seq_len(nrow(x))) {
for(j in seq_len(ncol(x))) {
print(x[i, j])
}
}
for
> print(paste("The year is", 2011))
[1] "The year is 2011"
> print(paste("The year is", 2012))
[1] "The year is 2012"
> print(paste("The year is", 2013))
[1] "The year is 2013"
> print(paste("The year is", 2014))
[1] "The year is 2014"
> print(paste("The year is", 2015))
[1] "The year is 2015”
...
...
for (i in 2010:2015){
print(paste("The year is", i))
}
for (year in c(2010,2011,2012,2013,2014,2015)){
print(paste("The year is", year))
}
if(<condition>) {
## do something
}
Example: if statement
x <- 5
if(x > 0){
print("Positive number")
}
Output
[1] "Positive number"
Control Structures: if
Control Structures: if
if...else statement
The syntax of if...else statement is:
if (test_expression) {
## do something
} else {
## do something else
}
x <- -5
if(x > 0){
print("Non-negative number")
} else {
print("Negative number")
}
Output
[1] "Negative number" 如果執⾏行的指令只有⼀一⾏行,⽐比較優雅的寫法如下:
if(x > 0) print("Non-negative number") else print("Negative number”)
x <- -5
y <- if(x > 0) 5 else 6
y
[1] 6
x <- 0
if (x < 0) {
print("Negative number")
} else if (x > 0) {
print("Positive number")
} else
print("Zero")
Output
[1] "Zero"
Control Structures: if
if(test_expression1) {
## do something
} else if(test_expression2){
## do something different
} else {
## do something different
}

More Related Content

What's hot

Ludo mini project in c++
Ludo mini project in c++Ludo mini project in c++
Ludo mini project in c++Mauryasuraj98
 
The MySQL Query Optimizer Explained Through Optimizer Trace
The MySQL Query Optimizer Explained Through Optimizer TraceThe MySQL Query Optimizer Explained Through Optimizer Trace
The MySQL Query Optimizer Explained Through Optimizer Traceoysteing
 
S1 3 derivadas_resueltas
S1 3 derivadas_resueltasS1 3 derivadas_resueltas
S1 3 derivadas_resueltasjesquerrev1
 
Merge sort: illustrated step-by-step walk through
Merge sort: illustrated step-by-step walk throughMerge sort: illustrated step-by-step walk through
Merge sort: illustrated step-by-step walk throughYoshi Watanabe
 

What's hot (6)

Ludo mini project in c++
Ludo mini project in c++Ludo mini project in c++
Ludo mini project in c++
 
The MySQL Query Optimizer Explained Through Optimizer Trace
The MySQL Query Optimizer Explained Through Optimizer TraceThe MySQL Query Optimizer Explained Through Optimizer Trace
The MySQL Query Optimizer Explained Through Optimizer Trace
 
S1 3 derivadas_resueltas
S1 3 derivadas_resueltasS1 3 derivadas_resueltas
S1 3 derivadas_resueltas
 
Merge sort: illustrated step-by-step walk through
Merge sort: illustrated step-by-step walk throughMerge sort: illustrated step-by-step walk through
Merge sort: illustrated step-by-step walk through
 
Programação funcional em Python
Programação funcional em PythonProgramação funcional em Python
Programação funcional em Python
 
Merge sort
Merge sortMerge sort
Merge sort
 

Similar to [1062BPY12001] Data analysis with R / April 19

01_introduction_lab.pdf
01_introduction_lab.pdf01_introduction_lab.pdf
01_introduction_lab.pdfzehiwot hone
 
YamadaiR(Categorical Factor Analysis)
YamadaiR(Categorical Factor Analysis)YamadaiR(Categorical Factor Analysis)
YamadaiR(Categorical Factor Analysis)考司 小杉
 
Gotcha! Ruby things that will come back to bite you.
Gotcha! Ruby things that will come back to bite you.Gotcha! Ruby things that will come back to bite you.
Gotcha! Ruby things that will come back to bite you.David Tollmyr
 
Table of Useful R commands.
Table of Useful R commands.Table of Useful R commands.
Table of Useful R commands.Dr. Volkan OBAN
 
Fingerprinting Chemical Structures
Fingerprinting Chemical StructuresFingerprinting Chemical Structures
Fingerprinting Chemical StructuresRajarshi Guha
 
SUEC 高中 Adv Maths (Statistic).pptx
SUEC 高中 Adv Maths (Statistic).pptxSUEC 高中 Adv Maths (Statistic).pptx
SUEC 高中 Adv Maths (Statistic).pptxtungwc
 
6. Vectors – Data Frames
6. Vectors – Data Frames6. Vectors – Data Frames
6. Vectors – Data FramesFAO
 
Cloudera - A Taste of random decision forests
Cloudera - A Taste of random decision forestsCloudera - A Taste of random decision forests
Cloudera - A Taste of random decision forestsDataconomy Media
 
RDataMining slides-data-exploration-visualisation
RDataMining slides-data-exploration-visualisationRDataMining slides-data-exploration-visualisation
RDataMining slides-data-exploration-visualisationYanchang Zhao
 
جلسه سوم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه سوم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲جلسه سوم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه سوم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲Mohammad Reza Kamalifard
 
Rpartii 131126003007-phpapp01
Rpartii 131126003007-phpapp01Rpartii 131126003007-phpapp01
Rpartii 131126003007-phpapp01Sunil0108
 
Itroroduction to R language
Itroroduction to R languageItroroduction to R language
Itroroduction to R languagechhabria-nitesh
 
unsupervised classification.pdf
unsupervised classification.pdfunsupervised classification.pdf
unsupervised classification.pdfsurjeetkoli900
 
TAO Fayan_Report on Top 10 data mining algorithms applications with R
TAO Fayan_Report on Top 10 data mining algorithms applications with RTAO Fayan_Report on Top 10 data mining algorithms applications with R
TAO Fayan_Report on Top 10 data mining algorithms applications with RFayan TAO
 

Similar to [1062BPY12001] Data analysis with R / April 19 (20)

01_introduction_lab.pdf
01_introduction_lab.pdf01_introduction_lab.pdf
01_introduction_lab.pdf
 
YamadaiR(Categorical Factor Analysis)
YamadaiR(Categorical Factor Analysis)YamadaiR(Categorical Factor Analysis)
YamadaiR(Categorical Factor Analysis)
 
Gotcha! Ruby things that will come back to bite you.
Gotcha! Ruby things that will come back to bite you.Gotcha! Ruby things that will come back to bite you.
Gotcha! Ruby things that will come back to bite you.
 
Table of Useful R commands.
Table of Useful R commands.Table of Useful R commands.
Table of Useful R commands.
 
Fingerprinting Chemical Structures
Fingerprinting Chemical StructuresFingerprinting Chemical Structures
Fingerprinting Chemical Structures
 
Welcome to python
Welcome to pythonWelcome to python
Welcome to python
 
Python.pdf
Python.pdfPython.pdf
Python.pdf
 
R intro 20140716-advance
R intro 20140716-advanceR intro 20140716-advance
R intro 20140716-advance
 
SUEC 高中 Adv Maths (Statistic).pptx
SUEC 高中 Adv Maths (Statistic).pptxSUEC 高中 Adv Maths (Statistic).pptx
SUEC 高中 Adv Maths (Statistic).pptx
 
6. Vectors – Data Frames
6. Vectors – Data Frames6. Vectors – Data Frames
6. Vectors – Data Frames
 
20100528
2010052820100528
20100528
 
20100528
2010052820100528
20100528
 
Cloudera - A Taste of random decision forests
Cloudera - A Taste of random decision forestsCloudera - A Taste of random decision forests
Cloudera - A Taste of random decision forests
 
RDataMining slides-data-exploration-visualisation
RDataMining slides-data-exploration-visualisationRDataMining slides-data-exploration-visualisation
RDataMining slides-data-exploration-visualisation
 
جلسه سوم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه سوم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲جلسه سوم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه سوم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
 
R part II
R part IIR part II
R part II
 
Rpartii 131126003007-phpapp01
Rpartii 131126003007-phpapp01Rpartii 131126003007-phpapp01
Rpartii 131126003007-phpapp01
 
Itroroduction to R language
Itroroduction to R languageItroroduction to R language
Itroroduction to R language
 
unsupervised classification.pdf
unsupervised classification.pdfunsupervised classification.pdf
unsupervised classification.pdf
 
TAO Fayan_Report on Top 10 data mining algorithms applications with R
TAO Fayan_Report on Top 10 data mining algorithms applications with RTAO Fayan_Report on Top 10 data mining algorithms applications with R
TAO Fayan_Report on Top 10 data mining algorithms applications with 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 26Kevin 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 4Kevin Chun-Hsien Hsu
 
[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 3Kevin Chun-Hsien Hsu
 
[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 2Kevin 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 EffectsKevin Chun-Hsien Hsu
 
Kirk' Experimental Design, Chapter 4
Kirk' Experimental Design, Chapter 4Kirk' Experimental Design, Chapter 4
Kirk' Experimental Design, Chapter 4Kevin Chun-Hsien Hsu
 
Kirk' Experimental Design, Chapter 3
Kirk' Experimental Design, Chapter 3Kirk' Experimental Design, Chapter 3
Kirk' Experimental Design, Chapter 3Kevin Chun-Hsien Hsu
 
Kirk' Experimental Design, Chapter 5
Kirk' Experimental Design, Chapter 5Kirk' Experimental Design, Chapter 5
Kirk' Experimental Design, Chapter 5Kevin Chun-Hsien Hsu
 
Kirk' Experimental Design, Chapter 2
Kirk' Experimental Design, Chapter 2Kirk' Experimental Design, Chapter 2
Kirk' Experimental Design, Chapter 2Kevin 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 / 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
 

Recently uploaded

Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...PsychoTech Services
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 

Recently uploaded (20)

Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 

[1062BPY12001] Data analysis with R / April 19

  • 3. 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
  • 4. Argument Matching R functions arguments can be matched positionally or by name. The following calls to sd are all equivalent > mydata <- rnorm(100) > sd(mydata) > sd(x = mydata) > sd(x = mydata, na.rm = FALSE) > sd(na.rm = FALSE, x = mydata) > sd(na.rm = FALSE, mydata)
  • 5. Argument Matching You can mix positional matching with matching by name. When an argument is matched by name, it is “taken out” of the argument list and the remaining unnamed arguments are matched in the order that they are listed in the function definition. The following two calls are equivalent. > args(lm) function (formula, data, subset, weights, na.action, method = "qr", model = TRUE, x = FALSE, y = FALSE, qr = TRUE, singular.ok = TRUE, contrasts = NULL, offset, ...) > x = seq(1, 200, 1) > e = rnorm(200)*50 > y = x * 5 + e > mydata = data.frame(x, y) > lm(data = mydata, y ~ x, model = FALSE,1:100) > lm(y ~ x, mydata, 1:100, model = FALSE)
  • 6. Practice:subseting&descriptivestatistics > rm(list = ls()) > iris <- iris # data frame > iris.1 <- iris$Species == “setosa" # `iris.1`: logical vector > iris.setosa <- iris[iris.1,] # data frame of `setosa` > iris.3 <- iris$Species == “virginica" # `iris.3`: logical vector > iris.virginica <- iris[iris.3,] # data frame of `virginica` > mean(iris.setosa[,1]) [1] 5.006 > mean(iris.setosa[,2]) [1] 3.428 > mean(iris.setosa[,3]) [1] 1.462 > mean(iris.setosa[,4]) [1] 0.246 > sd(iris.setosa[,1]) [1] 0.3524897 > sd(iris.setosa[,2]) [1] 0.3790644 > sd(iris.setosa[,3]) [1] 0.173664 > sd(iris.setosa[,4]) [1] 0.1053856
  • 7. Practice:subseting&descriptivestatistics > mean(iris.setosa[,1]) [1] 5.006 > mean(iris.setosa[,2]) [1] 3.428 > mean(iris.setosa[,3]) [1] 1.462 > mean(iris.setosa[,4]) [1] 0.246 > sd(iris.setosa[,1]) [1] 0.3524897 > sd(iris.setosa[,2]) [1] 0.3790644 > sd(iris.setosa[,3]) [1] 0.173664 > sd(iris.setosa[,4]) [1] 0.1053856 > colMeans(iris.setosa[,-5]) Sepal.Length Sepal.Width Petal.Length Petal.Width 5.006 3.428 1.462 0.246 > apply(iris.setosa[,-5], 2, FUN = mean) Sepal.Length Sepal.Width Petal.Length Petal.Width 5.006 3.428 1.462 0.246 > apply(iris.setosa[,-5], 2, FUN = sd) # try `min`, `max`, and `length` Sepal.Length Sepal.Width Petal.Length Petal.Width 0.3524897 0.3790644 0.1736640 0.1053856
  • 8. R Packages •・ Select repositories... => 選擇套件所在資源庫 => OK •・ Packages => Install package(s) => CRAN mirror => installr, rgl, scatterplot3d (按Ctrl可多重選取) => OK > install.packages(c(“rgl","scatterplot3d","Rcmdr")) > install.packages("foreign", repos = "http://cran.csie.ntu.edu.tw") > library(rgl) # 載⼊入套件,same as > library("rgl") > detach(package:rgl) # 卸載套件 > remove.packages("rgl") # 移除套件 > .libPaths() # 列出library安裝⽬目錄
  • 9. R Packages/helps •・ library(help=“[package name]”) # 檢視套件內容 > library(help=“stats") •・ ?[package name] # 簡略說明 > ?stats •・ ?[package name]::[function name] # 函數使⽤用說明 > ?stats::lm
  • 10. Practice:`psych`package > library(psych) > describeBy(iris, group=iris[,5]) Descriptive statistics by group group: setosa vars n mean sd median trimmed mad min max range skew kurtosis se Sepal.Length 1 50 5.01 0.35 5.0 5.00 0.30 4.3 5.8 1.5 0.11 -0.45 0.05 Sepal.Width 2 50 3.43 0.38 3.4 3.42 0.37 2.3 4.4 2.1 0.04 0.60 0.05 Petal.Length 3 50 1.46 0.17 1.5 1.46 0.15 1.0 1.9 0.9 0.10 0.65 0.02 Petal.Width 4 50 0.25 0.11 0.2 0.24 0.00 0.1 0.6 0.5 1.18 1.26 0.01 Species* 5 50 1.00 0.00 1.0 1.00 0.00 1.0 1.0 0.0 NaN NaN 0.00 --------------------------------------------------------------------------- group: versicolor vars n mean sd median trimmed mad min max range skew kurtosis se Sepal.Length 1 50 5.94 0.52 5.90 5.94 0.52 4.9 7.0 2.1 0.10 -0.69 0.07 Sepal.Width 2 50 2.77 0.31 2.80 2.78 0.30 2.0 3.4 1.4 -0.34 -0.55 0.04 Petal.Length 3 50 4.26 0.47 4.35 4.29 0.52 3.0 5.1 2.1 -0.57 -0.19 0.07 Petal.Width 4 50 1.33 0.20 1.30 1.32 0.22 1.0 1.8 0.8 -0.03 -0.59 0.03 Species* 5 50 2.00 0.00 2.00 2.00 0.00 2.0 2.0 0.0 NaN NaN 0.00 --------------------------------------------------------------------------- group: virginica vars n mean sd median trimmed mad min max range skew kurtosis se Sepal.Length 1 50 6.59 0.64 6.50 6.57 0.59 4.9 7.9 3.0 0.11 -0.20 0.09 Sepal.Width 2 50 2.97 0.32 3.00 2.96 0.30 2.2 3.8 1.6 0.34 0.38 0.05 Petal.Length 3 50 5.55 0.55 5.55 5.51 0.67 4.5 6.9 2.4 0.52 -0.37 0.08 Petal.Width 4 50 2.03 0.27 2.00 2.03 0.30 1.4 2.5 1.1 -0.12 -0.75 0.04 Species* 5 50 3.00 0.00 3.00 3.00 0.00 3.0 3.0 0.0 NaN NaN 0.00
  • 11. > library(psych) > describeBy(iris[,-5], group=iris[,5]) Descriptive statistics by group group: setosa vars n mean sd median trimmed mad min max range skew kurtosis se Sepal.Length 1 50 5.01 0.35 5.0 5.00 0.30 4.3 5.8 1.5 0.11 -0.45 0.05 Sepal.Width 2 50 3.43 0.38 3.4 3.42 0.37 2.3 4.4 2.1 0.04 0.60 0.05 Petal.Length 3 50 1.46 0.17 1.5 1.46 0.15 1.0 1.9 0.9 0.10 0.65 0.02 Petal.Width 4 50 0.25 0.11 0.2 0.24 0.00 0.1 0.6 0.5 1.18 1.26 0.01 --------------------------------------------------------------------------- group: versicolor vars n mean sd median trimmed mad min max range skew kurtosis se Sepal.Length 1 50 5.94 0.52 5.90 5.94 0.52 4.9 7.0 2.1 0.10 -0.69 0.07 Sepal.Width 2 50 2.77 0.31 2.80 2.78 0.30 2.0 3.4 1.4 -0.34 -0.55 0.04 Petal.Length 3 50 4.26 0.47 4.35 4.29 0.52 3.0 5.1 2.1 -0.57 -0.19 0.07 Petal.Width 4 50 1.33 0.20 1.30 1.32 0.22 1.0 1.8 0.8 -0.03 -0.59 0.03 --------------------------------------------------------------------------- group: virginica vars n mean sd median trimmed mad min max range skew kurtosis se Sepal.Length 1 50 6.59 0.64 6.50 6.57 0.59 4.9 7.9 3.0 0.11 -0.20 0.09 Sepal.Width 2 50 2.97 0.32 3.00 2.96 0.30 2.2 3.8 1.6 0.34 0.38 0.05 Petal.Length 3 50 5.55 0.55 5.55 5.51 0.67 4.5 6.9 2.4 0.52 -0.37 0.08 Petal.Width 4 50 2.03 0.27 2.00 2.03 0.30 1.4 2.5 1.1 -0.12 -0.75 0.04 Practice:`psych`package
  • 12. Practice:`psych`package > library(psych) > describeBy(iris, group=iris[,5]) Descriptive statistics by group group: setosa vars n mean sd median trimmed mad min max range skew kurtosis se Sepal.Length 1 50 5.01 0.35 5.0 5.00 0.30 4.3 5.8 1.5 0.11 -0.45 0.05 Sepal.Width 2 50 3.43 0.38 3.4 3.42 0.37 2.3 4.4 2.1 0.04 0.60 0.05 Petal.Length 3 50 1.46 0.17 1.5 1.46 0.15 1.0 1.9 0.9 0.10 0.65 0.02 Petal.Width 4 50 0.25 0.11 0.2 0.24 0.00 0.1 0.6 0.5 1.18 1.26 0.01 Species* 5 50 1.00 0.00 1.0 1.00 0.00 1.0 1.0 0.0 NaN NaN 0.00 --------------------------------------------------------------------------- group: versicolor vars n mean sd median trimmed mad min max range skew kurtosis se Sepal.Length 1 50 5.94 0.52 5.90 5.94 0.52 4.9 7.0 2.1 0.10 -0.69 0.07 Sepal.Width 2 50 2.77 0.31 2.80 2.78 0.30 2.0 3.4 1.4 -0.34 -0.55 0.04 Petal.Length 3 50 4.26 0.47 4.35 4.29 0.52 3.0 5.1 2.1 -0.57 -0.19 0.07 Petal.Width 4 50 1.33 0.20 1.30 1.32 0.22 1.0 1.8 0.8 -0.03 -0.59 0.03 Species* 5 50 2.00 0.00 2.00 2.00 0.00 2.0 2.0 0.0 NaN NaN 0.00 --------------------------------------------------------------------------- group: virginica vars n mean sd median trimmed mad min max range skew kurtosis se Sepal.Length 1 50 6.59 0.64 6.50 6.57 0.59 4.9 7.9 3.0 0.11 -0.20 0.09 Sepal.Width 2 50 2.97 0.32 3.00 2.96 0.30 2.2 3.8 1.6 0.34 0.38 0.05 Petal.Length 3 50 5.55 0.55 5.55 5.51 0.67 4.5 6.9 2.4 0.52 -0.37 0.08 Petal.Width 4 50 2.03 0.27 2.00 2.03 0.30 1.4 2.5 1.1 -0.12 -0.75 0.04 Species* 5 50 3.00 0.00 3.00 3.00 0.00 3.0 3.0 0.0 NaN NaN 0.00
  • 15. Control Structures Control structures in R allow you to control the flow of execution of the program, depending on runtime conditions. Common structures are · if,else:testingacondition · for:executealoopafixednumberoftimes · while:executealoopwhileaconditionistrue · repeat:executeaninfiniteloop · break:breaktheexecutionofaloop · next:skipaninterationofaloop · return:exitafunction Most control structures are not used in interactive sessions, but rather when writing functions or longer expresisons.
  • 16. for for loops take an interator variable and assign it successive values from a sequence or vector. For loops are most commonly used for iterating over the elements of an object (list, vector, etc.) This loop takes the i variable and in each iteration of the loop gives it values 1, 2, 3, ..., 10, and then exits. for(i in 1:10) { print(i) }
  • 17. for These three loops have the same behavior. x <- c("a", "b", "c", "d") for(i in 1:4) { print(x[i]) } for(i in seq_along(x)) { print(x[i]) } for(letter in x) { print(letter) } for(i in 1:4) print(x[i])
  • 18. Nested for loops for loops can be nested. Be careful with nesting though. Nesting beyond 2–3 levels is often very difficult to read/understand. x <- matrix(1:6, 2, 3) for(i in seq_len(nrow(x))) { for(j in seq_len(ncol(x))) { print(x[i, j]) } }
  • 19. for > print(paste("The year is", 2011)) [1] "The year is 2011" > print(paste("The year is", 2012)) [1] "The year is 2012" > print(paste("The year is", 2013)) [1] "The year is 2013" > print(paste("The year is", 2014)) [1] "The year is 2014" > print(paste("The year is", 2015)) [1] "The year is 2015” ... ... for (i in 2010:2015){ print(paste("The year is", i)) } for (year in c(2010,2011,2012,2013,2014,2015)){ print(paste("The year is", year)) }
  • 20. if(<condition>) { ## do something } Example: if statement x <- 5 if(x > 0){ print("Positive number") } Output [1] "Positive number" Control Structures: if
  • 21. Control Structures: if if...else statement The syntax of if...else statement is: if (test_expression) { ## do something } else { ## do something else } x <- -5 if(x > 0){ print("Non-negative number") } else { print("Negative number") } Output [1] "Negative number" 如果執⾏行的指令只有⼀一⾏行,⽐比較優雅的寫法如下: if(x > 0) print("Non-negative number") else print("Negative number”) x <- -5 y <- if(x > 0) 5 else 6 y [1] 6
  • 22. x <- 0 if (x < 0) { print("Negative number") } else if (x > 0) { print("Positive number") } else print("Zero") Output [1] "Zero" Control Structures: if if(test_expression1) { ## do something } else if(test_expression2){ ## do something different } else { ## do something different }