เอกสาร R Markdown ภาษาไทยชุดนี้อธิบาย การทำงานของโปรแกรม R/RStudio programming หัวข้อเรื่อง Introduction to R programming ในรายวิชา 2104525 Compuational Methods for IE เอกสารภาษาไทยชุดนี้ประกอบด้วย 3 ส่วน ได้แก่
data.table
การ บวก ลบ คูญ หาร ในโปรแกรม R/RStudio มีเครื่องหมายเช่นเดียวกับพีชคณิตทั่วไป
5+3
## [1] 8
5%%3
## [1] 2
5%/%3
## [1] 1
%%
เป็นการหารเอาเศษจำนวนเต็ม (Modulo) ของจำนวนเต็ม%/%
เป็นการหารเอาส่วนจำนวนเต็ม (Remainder) ของจำนวนเต็ม^
เป็นการยกกำลังsin()
cos()
tan()
asin()
cosh()
log()
log10()
exp()
rnorm()
runif()
dnorm()
qnorm()
factorial()
pi
sqrt()
abs()
ceiling()
round()
floor()
Im()
Re()
การกำหนดตัวแปรในโปรแกรม R/RStudio สามารถทำโดยเครื่องหมาย <-
หรือ =
เพื่อกำหนดชื่อตัวแปร โดยตัวแปรมักอยู่ในรูป เวคเตอร์ (Vector) ตัวอย่างเช่น
c(1,2) + c(3,4)
## [1] 4 6
2*c(1,2)
## [1] 2 4
myVector <− c(1,2) ## เพื่อกำหนดชือตัวแปร
mySeq <− seq(from = 1,to= 10,by = 2) ## สร้างลำดับ เริ่มที่ 1 สิ้นสุดที่ 10 เพิ่มขึ้นที่ละ 2
การตรวจสอบชนิดสามารถทำได้โดยคำสั่ง str()
หรือ class()
ซึ่งเป็นการตรวจสอบชนิดของตัวแปร และ ประเภทของข้อมูล
str(mySeq)
## num [1:5] 1 3 5 7 9
class(myVector)
## [1] "numeric"
Data Type | ชนิดของข้อมูล | ตัวอย่าง | คำสั่งแคส | คำสั่งที่เกี่ยวข้อง |
---|---|---|---|---|
Numeric | จำนวนจริง | 3, 3+6, 3.5 | as.numeric () | sum (), prod (), cumsum () |
Integer | จำนวนเต็ม | 3L, 6L | as.integer () | ceiling (), floor () |
Complex | จำนวนเชิงซ้อน | 3+5i, 4+0i | as.complex () | Re (), Im (), Conj () |
Logical | ตรรกะ | T, F, TRUE | as.logical () | all (), any () |
โปรแกรม R สามารถสร้างเงือนไขโดยการพิจารณา boolean ทางคณิตศาสตร์
==
(เท่ากับ) <=
(น้อยกว่าหรือเท่ากับ) >
(มากกว่า)&
(และ) |
(หรือ) !
(ไม่)all()
(จริงทุกนิพจน์) any()
(จริงอย่างน้อยนิพจน์) xor()
(จริงและเท็จเพียง หนึ่งนิพจน์) 5 == 3+2 ## 5 เท่ากับ 3+2 หรือไม่
## [1] TRUE
(5 == 3+2) & (7 != 2*3) ## (5 เท่ากับ3+2) และ (7 ไม่เท่ากับ 3 คูญ 2) จริงทั้งสองวงเล็บหรือไม่
## [1] TRUE
xor(5 == 3+2,7 != 2*3) ## วงเล็บ (5 เท่ากับ3+2) หรือ (7 ไม่เท่ากับ 3 คูญ 2) จริงเพียง หนึ่งวงเล็บหรือไม่
## [1] FALSE
การสร้างเงื่อนไข มักประกอบเข้ากับการสั่งทำงานโดยใช้ if
หรือ ifelse()
เช่น
if( 5 == 3+2){
cat("calculation is correct")
}
## calculation is correct
x <- runif(1)
result <- ifelse( x> 0.5,"HEAD","TAIL")
เช่นเดียวกับทุกโปรแกรมภาษา โปรแกรม R สามารถสร้าง Loop การทำงานวนเพื่อลดความซ้ำซ้อนได้ คำสั่ง loop ที่สำคัญ
for()
วนทำตามที่สั่งตามจำนวนรอบ หรือ ตามสมาชิกใน setwhile()
หากเป็นไปตามเงื่อนไข ทำวนจนไม่เป็นตามเงื่อนไขrepeat()
วนทำตามที่สั่งจนครบเงื่อนไข แล้วออกจาก loop multi <- 2
for(i in 1:20){ ## ทำซ้ำ 20 ครั้ง โดยการนับ 1 -20
cat(paste( c(i," x ",multi," =",multi*i,"\n"),collapse="") ) ## พิมพ์สูตรคูณ
}
## 1 x 2 =2
## 2 x 2 =4
## 3 x 2 =6
## 4 x 2 =8
## 5 x 2 =10
## 6 x 2 =12
## 7 x 2 =14
## 8 x 2 =16
## 9 x 2 =18
## 10 x 2 =20
## 11 x 2 =22
## 12 x 2 =24
## 13 x 2 =26
## 14 x 2 =28
## 15 x 2 =30
## 16 x 2 =32
## 17 x 2 =34
## 18 x 2 =36
## 19 x 2 =38
## 20 x 2 =40
iter <- 1
while( abs(runif(1) - 0.5) > 0.01 ){ ## ค่าสุ่มอยู่ระหว่าง 0.45-0.55
cat( rep("-",iter) )
iter < iter + 1
}
## -------------------
repeat{
samp <- sample(1:7,size=1) ## สุ่มค่า 1 ถึง 7
cat(paste(c("result: ",samp),collapse="")) ## พิมพ์ผลการสุ่ม
if(samp == 7){
break
}
cat(" no jackot, repeat \n " )
}
## result: 6 no jackot, repeat
## result: 3 no jackot, repeat
## result: 4 no jackot, repeat
## result: 6 no jackot, repeat
## result: 4 no jackot, repeat
## result: 4 no jackot, repeat
## result: 6 no jackot, repeat
## result: 7
หมายเหตุ การเลือกเงื่อนไขใน loop สามารถทำโดยคำสั่ง switch
centre <- function(x, type) {
switch(type,
mean = {
mean(x)
},
median = {
median(x)
},
trimmed = {
mean(x, trim = .1)
}
)
}
x <- 100*rnorm(20)
centre(x, "mean")
## [1] 13.86704
centre(x, "median")
## [1] -1.293179
centre(x, "trimmed")
## [1] 6.142156
R ยังมีฟังก์ช่ันช่วยในการคำนวนมากมาย อาทิเช่น
length(myVector) ## หาจำนวนสมาชิกใน vector
## [1] 2
sum(mySeq) ## คำนวนผลรวม
## [1] 25
prod(mySeq) ## คำนวนผลคูญ
## [1] 945
myCumSum <- cumsum(mySeq) ## คำนวนผลรวมสะสม
myCumPro <- cumprod(mySeq)## คำนวนผลคูญสะสม
myNewVal <- c(1:max(mySeq),3*myVector) ## 1:max(seq) = ตัวย่อของ seq(1,max(mySeq),1)
ผู้ใช้สามารถกำหนดฟังก์ชั่นได้เองใน R ด้วยคำสั่ง function()
และ กำหนดการคืนค่าด้วย return()
เพื่อป้องกันการสับสน
test01.Fun <- function(x){ 2*log(x) }
test02.Fun <- function(x){
value <- 2*log(x) +1
return(value)
}
test01.Fun(3)
## [1] 2.197225
test02.Fun(3:8)
## [1] 3.197225 3.772589 4.218876 4.583519 4.891820 5.158883
หมายเหต การใช้ vector เป็น input ในฟังก์ชั่นที่รับค่า scalar ดังเช่น test02.Fun(3:8)
มีความเสี่ยงในการคำนวนผิดพลาด
myFunInput <- 1:30
myFunOutput<- test02.Fun(myFunInput)
plot(myFunInput,myFunOutput)
myMatrix <- matrix( c(1:9),ncol=3) ## สร้างเมตริกจากเวคเตอร์
myMatrix <- myMatrix + diag(3)
det(myMatrix) ## คำนวนค่า det
## [1] -2
t(myMatrix) ## หาค่า transpose ของเมตริก
## [,1] [,2] [,3]
## [1,] 2 2 3
## [2,] 4 6 6
## [3,] 7 8 10
row.names(myMatrix) <- paste( "row",1:3,sep="-")
myMatrix <- cbind(myMatrix,seq(1,5,2))
myMatrix <- rbind( round(10*runif(4)),myMatrix)
ncol(myMatrix)
## [1] 4
det(myMatrix)
## [1] -183
solve(myMatrix) ## คำนวน inverse matrix
## row-1 row-2 row-3
## [1,] 0.17486339 0.2950820 -0.03825137 -0.2459016
## [2,] 0.04918033 -0.2295082 0.77049180 -0.4754098
## [3,] -0.07650273 0.2459016 -0.42076503 0.2950820
## [4,] -0.01092896 -0.3934426 -0.06010929 0.3278689
solve(myMatrix,c(1,5,3,4))## solve หาค่า x จาก Ax=b
## [1] 0.5519126 -0.6885246 1.0710383 -0.8469945
eigen(myMatrix) ## คำนวนค่า eigen value และ eigen vector
## eigen() decomposition
## $values
## [1] 18.705700 4.312162 2.075327 -1.093189
##
## $vectors
## [,1] [,2] [,3] [,4]
## [1,] -0.5542723 -0.94041226 -0.7379897 0.1820964
## [2,] -0.3363153 0.04834509 -0.2434187 -0.7845690
## [3,] -0.4616854 0.23665410 0.1921650 0.5502797
## [4,] -0.6054096 0.23933735 0.5993256 -0.2201921
pmax(myMatrix)
## [,1] [,2] [,3] [,4]
## 7 3 4 6
## row-1 2 4 7 1
## row-2 2 6 8 3
## row-3 3 6 10 5
ข้อมูลแต่ละสมาชิกของตัวแปรสามารถเข้าถึงได้แตกต่างกัน
which()
เป็นฟังก์ชั่นค้นหาตำแหน่งโดยระบุค่า หรือ เงื่อนไขsummary()
เป็นฟังก์ชั่นสรุปค่าsort()
เป็นพังก์ชั่นเรียงค่าorder()
เป็นพังก์ชั่นเรียงค่าตามตำแหน่ง[]
เป็นการเข้าถึงตำแหน่งของตัวแปร$
หรือ [[]]
เป็นการเข้าถึงตำแหน่งของ list ของตัวแปร which(myNewVal == 3) ## หาตำแหน่งของตัวแปร myNewVal ที่มีค่าเท่ากับ 9
## [1] 3 10
which.min(myNewVal) ## หาตำแหน่งของตัวแปร myNewVal ที่มีค่าน้อยที่สุด
## [1] 1
summary(myNewVal) ## สรุปค่า
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 1.000 3.000 5.000 4.909 6.500 9.000
sort(myNewVal,decreasing=F) ##จัดเรียงลำดับ
## [1] 1 2 3 3 4 5 6 6 7 8 9
order(myNewVal,decreasing=F) ##จัดเรียงลำดับ
## [1] 1 2 3 10 4 5 6 11 7 8 9
myNewVal[myNewVal > 8] ## ค่าของตัวแปร myNewVal มีมากกว่า 8
## [1] 9
myNewVal[2] ## ค่าของตัวแปร myNewVal ที่ตำแหน่งที่ 2
## [1] 2
quantile()
summary()
mean()
sd()
var()
median()
range()
IQR()
table()
xtabs()
ftable()
dcast()
melt()
sort()
order()
names()
length()
colname()
rowname()
dim()
attr()
sum()
prod()
cumsum()
cumprod()
colSums
colMeans()
apply()
sapply()
expression()
body()
eigen()
det()
solve()
quote()
subsitute()
call()
LETTERS[1] = A
) และดึงค่า ในฐานะ String assign(LETTERS[1],2)
get(LETTERS[1])
## [1] 2
do.call()
text01 <- "summary"
textdf <- "iris"
do.call(text01,arg=list(object=get(textdf) ))
## Sepal.Length Sepal.Width Petal.Length Petal.Width
## Min. :4.300 Min. :2.000 Min. :1.000 Min. :0.100
## 1st Qu.:5.100 1st Qu.:2.800 1st Qu.:1.600 1st Qu.:0.300
## Median :5.800 Median :3.000 Median :4.350 Median :1.300
## Mean :5.843 Mean :3.057 Mean :3.758 Mean :1.199
## 3rd Qu.:6.400 3rd Qu.:3.300 3rd Qu.:5.100 3rd Qu.:1.800
## Max. :7.900 Max. :4.400 Max. :6.900 Max. :2.500
## Species
## setosa :50
## versicolor:50
## virginica :50
##
##
##
eval(call(text01,get(textdf)))
## Sepal.Length Sepal.Width Petal.Length Petal.Width
## Min. :4.300 Min. :2.000 Min. :1.000 Min. :0.100
## 1st Qu.:5.100 1st Qu.:2.800 1st Qu.:1.600 1st Qu.:0.300
## Median :5.800 Median :3.000 Median :4.350 Median :1.300
## Mean :5.843 Mean :3.057 Mean :3.758 Mean :1.199
## 3rd Qu.:6.400 3rd Qu.:3.300 3rd Qu.:5.100 3rd Qu.:1.800
## Max. :7.900 Max. :4.400 Max. :6.900 Max. :2.500
## Species
## setosa :50
## versicolor:50
## virginica :50
##
##
##
note
call()
เป็นการสร้างคำสั่งแค่ยังไม่ดำเนินการประเมิน (non-execute)eval()
ประเมินค่าของฟัวก์ชั่นที่ประกาศในรูป call()
หรือ ประกาศในรูป expression()
do.call()
สั่งให้ดำเนินการฟังก์ชั่นในรูปแบบ รับค่า arg จากภายนอก อนึ่ง do.call()
= `eval(call())``expression()
alphaSym <- expression(alpha)
mathTerm <- expression( x1^3 - log(x1))
eval(mathTerm,list(x1=3))
## [1] 25.90139
D(mathTerm,"x1")
## 3 * x1^2 - 1/x1
substitute()
เป็นการแทนค่าด้วย envir
ที่กำหนด โดยผลจะออกมาเป็น expression()
x1Term <- quote(x+3)
varList <- list(x1=x1Term)
eval(
substitute(substitute(e, varList), list(e = mathTerm[[1]]))
)
## (x + 3)^3 - log(x + 3)
note
expression()
สร้างเงื่อนไขทางคณิตศาสตร์quote()
เก็บชุดคำสั่งในฐานะ String โดยไม่ประเมินค่าeval()
ประเมินค่าตัวแปรหรือเงื่อนไขทางคณิตศาสตร์substitute()
การแทนค่าทางคณิตศาสตร์โดยผลลัพธ์คือ expression stdNorm <− rnorm (50)
hist(stdNorm,breaks=10)
quantile(stdNorm,prob=0.45)
table(floor(10*stdNorm))
Copyright 2019 Oran Kittithreerapronchai. All Rights Reserved. Last modified: 2021-05-02,