SlideShare a Scribd company logo
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

PPTX
R part iii
PPTX
PYTHON-READ WORDS FROM STRING
PDF
Clustering and Visualisation using R programming
PDF
Association Rule Mining with R
PDF
Home work II
PDF
PHP and MySQL Tips and tricks, DC 2007
KEY
Boston Predictive Analytics: Linear and Logistic Regression Using R - Interme...
PPT
R part iii
PYTHON-READ WORDS FROM STRING
Clustering and Visualisation using R programming
Association Rule Mining with R
Home work II
PHP and MySQL Tips and tricks, DC 2007
Boston Predictive Analytics: Linear and Logistic Regression Using R - Interme...

What's hot (6)

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

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

DOCX
Summerization notes for descriptive statistics using r
PDF
Table of Useful R commands.
PDF
RDataMining slides-data-exploration-visualisation
PDF
Data Exploration and Visualization with R
PDF
01_introduction_lab.pdf
PPTX
r studio presentation.pptx
PPTX
r studio presentation.pptx
PDF
20170509 rand db_lesugent
PDF
Reference card for R
PDF
Short Reference Card for R users.
PDF
@ R reference
PDF
R command cheatsheet.pdf
PPTX
Language R
PDF
Data Wrangling with dplyr and tidyr Cheat Sheet
PDF
Graphics in R
PPTX
Descriptive Statistics in R.pptx
PDF
R Programming Reference Card
PDF
R Programming Homework Help
PDF
R programming & Machine Learning
PDF
Data transformation-cheatsheet
Summerization notes for descriptive statistics using r
Table of Useful R commands.
RDataMining slides-data-exploration-visualisation
Data Exploration and Visualization with R
01_introduction_lab.pdf
r studio presentation.pptx
r studio presentation.pptx
20170509 rand db_lesugent
Reference card for R
Short Reference Card for R users.
@ R reference
R command cheatsheet.pdf
Language R
Data Wrangling with dplyr and tidyr Cheat Sheet
Graphics in R
Descriptive Statistics in R.pptx
R Programming Reference Card
R Programming Homework Help
R programming & Machine Learning
Data transformation-cheatsheet
Ad

More from Kevin Chun-Hsien Hsu (20)

PDF
[1062BPY12001] Data analysis with R / April 26
PDF
[1062BPY12001] Data analysis with R / week 4
PDF
[1062BPY12001] Data analysis with R / week 3
PDF
[1062BPY12001] Data analysis with R / week 2
PDF
語言議題
PPTX
Regression 0410
PDF
Statistical computing 03
PDF
Statistical computing 01
PPTX
Statistical computing 00
PPTX
PPTX
Multiple regression
PPTX
Model III ANOVA & Simple Main Effects
PPTX
Essentials of EEG/MEG
PDF
repeated-measure-ANOVA
PDF
Kirk' Experimental Design, Chapter 4
PDF
Kirk' Experimental Design, Chapter 3
PPTX
PDF
資料檢索
PDF
Kirk' Experimental Design, Chapter 5
PDF
Kirk' Experimental Design, Chapter 2
[1062BPY12001] Data analysis with R / April 26
[1062BPY12001] Data analysis with R / week 4
[1062BPY12001] Data analysis with R / week 3
[1062BPY12001] Data analysis with R / week 2
語言議題
Regression 0410
Statistical computing 03
Statistical computing 01
Statistical computing 00
Multiple regression
Model III ANOVA & Simple Main Effects
Essentials of EEG/MEG
repeated-measure-ANOVA
Kirk' Experimental Design, Chapter 4
Kirk' Experimental Design, Chapter 3
資料檢索
Kirk' Experimental Design, Chapter 5
Kirk' Experimental Design, Chapter 2

Recently uploaded (20)

PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PPTX
Institutional Correction lecture only . . .
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
01-Introduction-to-Information-Management.pdf
PDF
Sports Quiz easy sports quiz sports quiz
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PPTX
PPH.pptx obstetrics and gynecology in nursing
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
Classroom Observation Tools for Teachers
PPTX
Cell Structure & Organelles in detailed.
PDF
Basic Mud Logging Guide for educational purpose
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Institutional Correction lecture only . . .
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
01-Introduction-to-Information-Management.pdf
Sports Quiz easy sports quiz sports quiz
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PPH.pptx obstetrics and gynecology in nursing
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
Microbial diseases, their pathogenesis and prophylaxis
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Supply Chain Operations Speaking Notes -ICLT Program
STATICS OF THE RIGID BODIES Hibbelers.pdf
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Classroom Observation Tools for Teachers
Cell Structure & Organelles in detailed.
Basic Mud Logging Guide for educational purpose

[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 }