โปรแกรม R เบื้องต้น

R เป็นโปรแกรมคอมพิวเตอร์ที่มีความสามารถสูงในการวิเคราะห์ข้อมูลเชิงสถิติ ในปัจจุบันเป็นที่นิยมในหลายสาขาวิชา เนื่องจากเป็น Open source ที่ทุกคนสามารถนำมาใช้งานโดยไม่มีค่าสใช้จ่ายและไม่ต้อกังวลเรื่องการละเมิดลิขสิทธ์เหมือนโปรแกรมสำเร็จรูปทางสถิติอื่น ๆ

การใช้ R เป็นเครื่องคิดเลข

ใช้เครื่องหมายคณิตศาสตร์ +, -, *, / ในการบวก, ลบ, คูณ และหาร และใช้ ^ เป็นเครื่องหมายในการยกกำลัง ตัวอย่างเช่น

1+1
## [1] 2
10-5
## [1] 5
5*2
## [1] 10
100/10
## [1] 10
5^2
## [1] 25
x=2
x+3
## [1] 5
x^3
## [1] 8

ชนิดและรูปแบบของข้อมูลใน R

ข้อมูลในโปรแกรม R แบ่งเป็น 3 ประเภท ได้แก่

Numeric เป็นข้อมูลที่มีค่าเป็นตัวเลข หรือในทางสถิติเรียกข้อมูลชนิดนี้ว่าข้อมูลเชิงปริมาณ (Quantitative data) เช่น อายุ รายได้ และคะแนนสอบ เป็นต้น ซึ่งข้อมูลชนิดนี้สามารถนํามาคำนวณหาค่าทางสถิติต่าง ๆ เช่น ค่าเฉลี่ย ค่าเบี่ยงเบนมาตรฐาน

age<- c(5,10,15,20)
mean(age)
## [1] 12.5
sd(age)
## [1] 6.454972

Character เป็นข้อมูลที่ค่าของมันไม่ใช่ตัวเลข โดยปรกติมักเป็นข้อความ หรือตัวอักษร ในทางสถิติเรียกข้อมูล ชนิดนี้ว่าข้อมูลเชิงคุณภาพ (Qualitative data) เช่น เพศ (ชาย, หญิง) ระดับการศึกษา (มัธยมศึกษา, ปริญญาตรี, ปริญญาโท) เป็นต้น ข้อมูลชนิดนี้ไม่สามารถนํามาคำนวณเพื่อหาค่าทางสถิติได้ แต่มีวิธีเชิง สถิติบางวิธีที่สามารถใช้ในการวิเคราะห์เพื่อหาคำตอบที่ผู้วิจัยต้องการจากข้อมูลชนิดนี้ได้ ซึ่งโดยทั่วไป จะใช้วิธีกลุ่มของสถิติไม่อิงพารามิเตอร์ (Nonparametric statistics)

sex<- c("boy","girl","girl","boy")
table(sex)
## sex
##  boy girl 
##    2    2

Logical เป็นข้อมูลเชิงตรรกที่มีค่าอยู่สองค่าเท่านั้น คือ TRUE แทนค่าจริง และ FALSE แทนค่าที่เป็นเท็จ

x = 10
x>12
## [1] FALSE
x<100
## [1] TRUE

ตัวอย่างข้อมูล

Download ตัวอย่างข้อมูล

iris เป็นตัวอย่างข้อมูลประกอบด้วยผลการวัดความยาว (Length) และความกว้าง(Width) ของกลีบเลี้ยง (sepal) และกลีบดอก (petal) จากดอกไม้ทั้งหมด 150 ดอก จาก 3 สายพันธุ์ (species)

data("iris")

แสดง 6 แถวแรกของข้อมูล

head(iris)
##   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1          5.1         3.5          1.4         0.2  setosa
## 2          4.9         3.0          1.4         0.2  setosa
## 3          4.7         3.2          1.3         0.2  setosa
## 4          4.6         3.1          1.5         0.2  setosa
## 5          5.0         3.6          1.4         0.2  setosa
## 6          5.4         3.9          1.7         0.4  setosa

เรียกดูการสรุปข้อมูลโดยใช้ summary()

สำหรับข้อมูลที่เป็นตัวเลข เราสามารถใช้คำสั่งต่อไปนี้เพื่อเรียกดูข้อมูล - Min: ค่าน้อยสุด - Median: ค่ามัธยฐาน - Mean: ค่าเฉลี่ย - Max: ค่ามากสุด

สำหรับข้อมูลที่เป็นตัวแปรจัดกลุ่ม (categorical variable) เราใช้การนับจำนวน setosa: มีข้อมูล 50 แถว versicolor: มีข้อมูล 50 แถว virginica: มีข้อมูล 50 แถว

summary(iris)
##   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  
##                 
##                 
## 

เรียกดูจำนวนแถว (row) และคอลัมม์ (column)

dim(iris)
## [1] 150   5

การแสดงข้อมูล (Visualization)

ใช้ hist() ในการสร้างแผนภูมิ Histrogram

hist(iris$Sepal.Length,
     col='steelblue',
     main='Histogram',
     xlab='Length',
     ylab='Frequency')

ใช้ plot() ในการสร้าง scatterplot ของการจับคู่ตัวแปรที่เป็น ตัวเลข (numerical variable)

plot(iris$Sepal.Width, iris$Sepal.Length,
     col='steelblue',
     main='Scatterplot',
     xlab='Sepal Width',
     ylab='Sepal Length',
     pch=19)

ใช้ boxplot() สร้าง boxplot จำแนกตามกลุ่ม

boxplot(Sepal.Length~Species,
        data=iris,
        main='Sepal Length by Species',
        xlab='Species',
        ylab='Sepal Length',
        col='steelblue',
        border='black')

ตัวอย่างข้อมูลสุขภาพ (ตัวเลขทั้งหมดเป็นการสมมติขึ้นมา)

Set working directory ใช้สำหรับกำหนดไฟล์ที่เราจะทำงานและบันทึกผลการวิเคราะห์ต่าง ๆ

Session–> Set working directory–> Choose Directory –> เลือกไฟล์งานของเรา

setwd(“/Volumes/KEERATI SSD/Keerati/SCPH/Computer_for_Public_Health/2022/Data”)

getwd() #เรียกดู Working Directory
## [1] "/Users/keeratiponpetch/Desktop/Keerati/สอน R"
library(readr)
Dataset <- read_csv("Data/Dataset.csv")
## Rows: 403 Columns: 17
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr  (3): location, gender, frame
## dbl (14): id, chol, stab.glu, hdl, ratio, glyhb, age, height, weight, bp.1s,...
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
View(Dataset)
library(readr)
Dataset <- read_csv("Data/Dataset.csv")
## Rows: 403 Columns: 17
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr  (3): location, gender, frame
## dbl (14): id, chol, stab.glu, hdl, ratio, glyhb, age, height, weight, bp.1s,...
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
head(Dataset)
## # A tibble: 6 × 17
##      id  chol stab.glu   hdl ratio glyhb location     age gender height weight
##   <dbl> <dbl>    <dbl> <dbl> <dbl> <dbl> <chr>      <dbl> <chr>   <dbl>  <dbl>
## 1  1000   203       82    56  3.60  4.31 Buckingham    46 female     62    121
## 2  1001   165       97    24  6.90  4.44 Buckingham    29 female     64    218
## 3  1002   228       92    37  6.20  4.64 Buckingham    58 female     61    256
## 4  1003    78       93    12  6.5   4.63 Buckingham    67 male       67    119
## 5  1005   249       90    28  8.90  7.72 Buckingham    64 male       68    183
## 6  1008   248       94    69  3.60  4.81 Buckingham    34 male       71    190
## # … with 6 more variables: frame <chr>, bp.1s <dbl>, bp.1d <dbl>, waist <dbl>,
## #   hip <dbl>, time.ppn <dbl>
summary(Dataset)
##        id             chol          stab.glu          hdl        
##  Min.   : 1000   Min.   : 78.0   Min.   : 48.0   Min.   : 12.00  
##  1st Qu.: 4792   1st Qu.:179.0   1st Qu.: 81.0   1st Qu.: 38.00  
##  Median :15766   Median :204.0   Median : 89.0   Median : 46.00  
##  Mean   :15978   Mean   :207.8   Mean   :106.7   Mean   : 50.45  
##  3rd Qu.:20336   3rd Qu.:230.0   3rd Qu.:106.0   3rd Qu.: 59.00  
##  Max.   :41756   Max.   :443.0   Max.   :385.0   Max.   :120.00  
##                  NA's   :1                       NA's   :1       
##      ratio            glyhb         location              age       
##  Min.   : 1.500   Min.   : 2.68   Length:403         Min.   :19.00  
##  1st Qu.: 3.200   1st Qu.: 4.38   Class :character   1st Qu.:34.00  
##  Median : 4.200   Median : 4.84   Mode  :character   Median :45.00  
##  Mean   : 4.522   Mean   : 5.59                      Mean   :46.85  
##  3rd Qu.: 5.400   3rd Qu.: 5.60                      3rd Qu.:60.00  
##  Max.   :19.300   Max.   :16.11                      Max.   :92.00  
##  NA's   :1        NA's   :13                                        
##     gender              height          weight         frame          
##  Length:403         Min.   :52.00   Min.   : 99.0   Length:403        
##  Class :character   1st Qu.:63.00   1st Qu.:151.0   Class :character  
##  Mode  :character   Median :66.00   Median :172.5   Mode  :character  
##                     Mean   :66.02   Mean   :177.6                     
##                     3rd Qu.:69.00   3rd Qu.:200.0                     
##                     Max.   :76.00   Max.   :325.0                     
##                     NA's   :5       NA's   :1                         
##      bp.1s           bp.1d            waist           hip       
##  Min.   : 90.0   Min.   : 48.00   Min.   :26.0   Min.   :30.00  
##  1st Qu.:121.2   1st Qu.: 75.00   1st Qu.:33.0   1st Qu.:39.00  
##  Median :136.0   Median : 82.00   Median :37.0   Median :42.00  
##  Mean   :136.9   Mean   : 83.32   Mean   :37.9   Mean   :43.04  
##  3rd Qu.:146.8   3rd Qu.: 90.00   3rd Qu.:41.0   3rd Qu.:46.00  
##  Max.   :250.0   Max.   :124.00   Max.   :56.0   Max.   :64.00  
##  NA's   :5       NA's   :5        NA's   :2      NA's   :2      
##     time.ppn     
##  Min.   :   5.0  
##  1st Qu.:  90.0  
##  Median : 240.0  
##  Mean   : 341.2  
##  3rd Qu.: 517.5  
##  Max.   :1560.0  
##  NA's   :3

Plot histogram of age

hist(Dataset$age,
     main = "Age (Year)",
     col = "blue",
     xlab = "Age",
     xlim = c(0,100))

สร้างตาราง location vs gender

table(Dataset$location, Dataset$gender)
##             
##              female male
##   Buckingham    114   86
##   Louisa        120   83

เลือกเฉพาะแถวที่ gender = female

data_female<- Dataset[Dataset$gender =="female",]
head(data_female)
## # A tibble: 6 × 17
##      id  chol stab.glu   hdl ratio glyhb location     age gender height weight
##   <dbl> <dbl>    <dbl> <dbl> <dbl> <dbl> <chr>      <dbl> <chr>   <dbl>  <dbl>
## 1  1000   203       82    56  3.60  4.31 Buckingham    46 female     62    121
## 2  1001   165       97    24  6.90  4.44 Buckingham    29 female     64    218
## 3  1002   228       92    37  6.20  4.64 Buckingham    58 female     61    256
## 4  1022   263       89    40  6.60  5.78 Buckingham    55 female     63    202
## 5  1024   242       82    54  4.5   4.77 Louisa        60 female     65    156
## 6  1029   215      128    34  6.30  4.97 Louisa        38 female     58    195
## # … with 6 more variables: frame <chr>, bp.1s <dbl>, bp.1d <dbl>, waist <dbl>,
## #   hip <dbl>, time.ppn <dbl>

เลือกเฉพาะคอลัมม์ Height และ Weight

data1<- Dataset[,10:11]
head(data1)
## # A tibble: 6 × 2
##   height weight
##    <dbl>  <dbl>
## 1     62    121
## 2     64    218
## 3     61    256
## 4     67    119
## 5     68    183
## 6     71    190

Scatter plot of Height และ Weight

plot(data1$height,data1$weight,
     col = "orange",
     pch = 20,
     cex = 1.5)

plot(data1,
     col = "red",
     pch = 21)

สร้างคอลัมป์ใหม่ชื่อ Height_cm (1 inch = 2.54 cm)

data1$height_cm<- data1$height*2.54
head(data1)
## # A tibble: 6 × 3
##   height weight height_cm
##    <dbl>  <dbl>     <dbl>
## 1     62    121      157.
## 2     64    218      163.
## 3     61    256      155.
## 4     67    119      170.
## 5     68    183      173.
## 6     71    190      180.

สร้างคอลัมป์ใหม่ชื่อ Height_meter

data1$height_meter<- data1$height_cm/100
head(data1)
## # A tibble: 6 × 4
##   height weight height_cm height_meter
##    <dbl>  <dbl>     <dbl>        <dbl>
## 1     62    121      157.         1.57
## 2     64    218      163.         1.63
## 3     61    256      155.         1.55
## 4     67    119      170.         1.70
## 5     68    183      173.         1.73
## 6     71    190      180.         1.80

สร้างคอลัมป์ใหม่ชื่อ weight_kg (1 pound = 0.45359237 kg)

data1$weight_kg<-data1$weight*0.45359237
head(data1)
## # A tibble: 6 × 5
##   height weight height_cm height_meter weight_kg
##    <dbl>  <dbl>     <dbl>        <dbl>     <dbl>
## 1     62    121      157.         1.57      54.9
## 2     64    218      163.         1.63      98.9
## 3     61    256      155.         1.55     116. 
## 4     67    119      170.         1.70      54.0
## 5     68    183      173.         1.73      83.0
## 6     71    190      180.         1.80      86.2

Calculate BMI = weight/hight_meter^2

data1$BMI<- data1$weight_kg/data1$height_meter^2
head(data1)
## # A tibble: 6 × 6
##   height weight height_cm height_meter weight_kg   BMI
##    <dbl>  <dbl>     <dbl>        <dbl>     <dbl> <dbl>
## 1     62    121      157.         1.57      54.9  22.1
## 2     64    218      163.         1.63      98.9  37.4
## 3     61    256      155.         1.55     116.   48.4
## 4     67    119      170.         1.70      54.0  18.6
## 5     68    183      173.         1.73      83.0  27.8
## 6     71    190      180.         1.80      86.2  26.5

Line graph (source: https://r-coder.com/plot-r/#R_plot_type)

plot(data1$BMI, type = "l", main = "type = 'line'")

Bar chart

create the data for the chart

B <- c(7,12,28,3,41)

barplot(B,
        xlab = "Month",
        ylab = "Case",
        col = "red")

Add x axis

M <- c("Mar","Apr","May","Jun","Jul")

barplot(B,
        xlab = "Month",
        ylab = "Case",
        col = "red",
        names.arg=M)

Pie chart (source: https://www.tutorialspoint.com/r/r_pie_charts.htm)

table(Dataset$gender)
## 
## female   male 
##    234    169
x <- c(234, 169)
labels <- c("Female", "Male")

pie(x,labels,
    main = "Gender",
    col = c("red", "blue"))