Category: Data analytics

  • วิธีทำ Hierarchical Clustering ในภาษา R — ตัวอย่างการใช้ hclust() จัดกลุ่มข้อมูลอาชญากรรมจาก USArrests dataset

    วิธีทำ Hierarchical Clustering ในภาษา R — ตัวอย่างการใช้ hclust() จัดกลุ่มข้อมูลอาชญากรรมจาก USArrests dataset

    ในบทความนี้ เราจะมาทำความรู้จักกับ hierarchical cluster analysis (HCA) หรือ hierarchical clustering ในภาษา R กัน


    1. 🧐 HCA คืออะไร?
    2. 💻 HCA ในภาษา R: hclust()
    3. 🔢 Example Dataset: USArrests
    4. 📏 Normalise the Data
    5. 🍿 HCA With hclust()
    6. 📈 Print & Dendrogram
    7. 😺 GitHub
    8. 📃 References
    9. ✅ R Book for Psychologists: หนังสือภาษา R สำหรับนักจิตวิทยา

    🧐 HCA คืออะไร?

    HCA เป็น machine learning algorithm ประเภท unsupervised learning และใช้จัดกลุ่มข้อมูล (clustering) แบบลำดับชั้น (hierarchical)

    HCA มี 2 ประเภท:

    1. Agglomerative (bottom-up): จับ data point ที่อยู่ใกล้กันให้อยู่ cluster เดียวกัน แล้วจับ clusters ที่อยู่ใกล้กันให้อยูากลุ่มเดียวกัน ทำอย่างนี้ไปเรื่อย ๆ จนได้ 1 cluster ใหญ่
    2. Divisive (top-down): เริ่มจาก 1 cluster และแยก cluster ย่อยออกมาเรื่อย ๆ

    ตัวอย่างการใช้งาน HCA เช่น จัดกลุ่มผู้บริโภค (customer segmentation):


    💻 HCA ในภาษา R: hclust()

    ในภาษา R เราสามารถทำ HCA ได้ด้วย 2 functions:

    1. hclust() สำหรับ agglomerative HCA
    2. diana() จาก cluster package สำหรับ divisive HCA

    ในบทความนี้ เราจะดูวิธีใช้ hclust() ซึ่งเป็นที่นิยมสำหรับ HCA กัน


    🔢 Example Dataset: USArrests

    Dataset ที่เราจะใช้เป็นตัวอย่างในบทความนี้ คือ USArrests

    USArrests มีข้อมูลจำนวนประชากรจาก 50 รัฐในอเมริกา และข้อมูลการจับกุมใน 3 ประเภทการกระทำผิด ได้แก่:

    1. ฆาตกรรม (murder)
    2. ทำร้ายร่างกาย (assault)
    3. ข่มขืน (rape)

    ในการใช้งาน เราสามารถโหลด USArrests ได้ด้วย data():

    # Load
    data(USArrests)
    

    จากนั้น ดูตัวอย่างข้อมูลด้วย head():

    # Preview
    head(USArrests)
    

    ผลลัพธ์:

               Murder Assault UrbanPop Rape
    Alabama      13.2     236       58 21.2
    Alaska       10.0     263       48 44.5
    Arizona       8.1     294       80 31.0
    Arkansas      8.8     190       50 19.5
    California    9.0     276       91 40.6
    Colorado      7.9     204       78 38.7
    

    📏 Normalise the Data

    เนื่องจาก HCA จัดกลุ่มข้อมูลโดยใช้ระยะห่างระหว่างข้อมูล เราจะต้อง normalise ข้อมูล เพื่อให้ข้อมูลมีช่วงข้อมูลที่เท่า ๆ กัน และป้องกันไม่ให้ข้อมูลที่มีระยะห่างมาก (เช่น ข้อมูลที่อยู่ในช่วง 1 ถึง 1,000 เทียบกับ ข้อมูลที่มีช่วง 1 ถึง 10) มีผลต่อการจัดกลุ่ม

    สำหรับ HCA เราจะ normalise ด้วย z-score standardisation ซึ่งมีสูตรคำนวณดังนี้:

    Z = (X - M) / SD
    • Z = ข้อมูลที่ normalised แล้ว
    • X = ข้อมูลตั้งต้น
    • M = ค่าเฉลี่ยของข้อมูลตั้งต้น
    • SD = standard deviation (SD) ของข้อมูลตั้งต้น

    ทั้งนี้ เราสามารถทำ z-score standardisation ได้ด้วย scale():

    # Perform z-score standardisation
    USArrests_scaled <- scale(USArrests)
    

    จากนั้น เช็กผลลัพธ์ด้วย colMeans() และ apply() กับ sd():

    # Check the results
    
    ## Mean
    colMeans(USArrests_scaled)
    
    ## SD
    apply(USArrests_scaled, 2, sd)
    

    ผลลัพธ์:

    > ## Mean
    > round(colMeans(USArrests_scaled), 2)
      Murder  Assault UrbanPop     Rape 
           0        0        0        0 
    > 
    > ## SD
    > apply(USArrests_scaled, 2, sd)
      Murder  Assault UrbanPop     Rape 
           1        1        1        1 
    

    จะเห็นได้ว่า ทุก column มี mean เป็น 0 และ SD เป็น 1 แสดงว่า เรา normalise ข้อมูลได้สำเร็จ และพร้อมไปขั้นตอนถัดไป


    🍿 HCA With hclust()

    ตอนนี้ เราจะเริ่มใช้ HCA เพื่อจัดกลุ่มข้อมูลกัน

    hclust() ต้องการ input 2 อย่าง:

    hclust(d, method)

    Input #1. d หมายถึง distance matrix หรือ matrix ที่เก็บค่าระยะห่างระหว่างข้อมูลแบบ pair-wise ไว้

    เราสามารถคำนวณ distance matrix ได้ด้วย dist() function

    Input #2. method หมายถึง linkage method หรือวิธีในการจับ clusters รวมกันเป็น cluster ที่ใหญ่ขึ้น

    Linkage methods มี 5 ประเภท:

    1. Ward’s linkage: จับกลุ่ม cluster โดยลด variance ภายใน cluster
    2. Complete linkage: ใช้ระยะห่างสูงสุด
    3. Single linkage: ใช้ระยะห่างต่ำที่สุด
    4. Average linkage: ใช้ระยะห่างเฉลี่ยระหว่างข้อมูลจาก 2 clusters
    5. Centroid linkage: ใช้ระยะห่างระหว่างจุดศูนย์กลางของ 2 clusters

    Linkage ที่มักใช้กันได้ แก่ Ward’s, complete, และ average และในบทความนี้ เราจะใช้ Ward’s linkage ("ward.D2") กัน

    เราเรียกใช้ hclust() เพื่อจัดกลุ่มข้อมูล:

    # Create a distance matrix
    dm <- dist(USArrests_scaled)
    
    # HCA
    hc <- hclust(dm,
                 method = "ward.D2")
    

    ตอนนี้ เราก็ได้ข้อมูลที่จัดกลุ่มแล้ว


    สุดท้าย เราสามารถดูผลลัพธ์ของ HCA ได้ด้วย print():

    # Print HCA
    print(hc)
    

    ผลลัพธ์:

    Call:
    hclust(d = dm, method = "ward.D2")
    
    Cluster method   : ward.D2 
    Distance         : euclidean 
    Number of objects: 50 
    

    และการสร้าง dendrogram:

    # Plot a dendrogram
    plot(hc,
         hang = -1,
         cex = 0.8,
         main = "Dendrogram of USArrests Data")
    

    ผลลัพธ์:


    😺 GitHub

    ดู code ทั้งหมดในบทความนี้ได้ที่ GitHub


    📃 References


    ✅ R Book for Psychologists: หนังสือภาษา R สำหรับนักจิตวิทยา

    📕 ขอฝากหนังสือเล่มแรกในชีวิตด้วยนะครับ 😆

    🙋 ใครที่กำลังเรียนจิตวิทยาหรือทำงานสายจิตวิทยา และเบื่อที่ต้องใช้ software ราคาแพงอย่าง SPSS และ Excel เพื่อทำข้อมูล

    💪 ผมขอแนะนำ R Book for Psychologists หนังสือสอนใช้ภาษา R เพื่อการวิเคราะห์ข้อมูลทางจิตวิทยา ที่เขียนมาเพื่อนักจิตวิทยาที่ไม่เคยมีประสบการณ์เขียน code มาก่อน

    ในหนังสือ เราจะปูพื้นฐานภาษา R และพาไปดูวิธีวิเคราะห์สถิติที่ใช้บ่อยกัน เช่น:

    • Correlation
    • t-tests
    • ANOVA
    • Reliability
    • Factor analysis

    🚀 เมื่ออ่านและทำตามตัวอย่างใน R Book for Psychologists ทุกคนจะไม่ต้องพึง SPSS และ Excel ในการทำงานอีกต่อไป และสามารถวิเคราะห์ข้อมูลด้วยตัวเองได้ด้วยความมั่นใจ

    แล้วทุกคนจะแปลกใจว่า ทำไมภาษา R ง่ายขนาดนี้ 🙂‍↕️

    👉 สนใจดูรายละเอียดหนังสือได้ที่ meb:

  • วิธีจัดกลุ่มข้อมูลด้วย k-means ผ่าน kmeans() function ในภาษา R — ตัวอย่างการจัดกลุ่มหินจาก rock dataset

    วิธีจัดกลุ่มข้อมูลด้วย k-means ผ่าน kmeans() function ในภาษา R — ตัวอย่างการจัดกลุ่มหินจาก rock dataset

    ในบทความนี้ เราจะมาทำความรู้จักกับ k-means และวิธีใช้ kmeans() ในภาษา R กัน


    1. 👉 Introduction to k-Means
      1. 🤔 k-Means คืออะไร?
      2. 🪜 Steps การทำงานของ k-Means
      3. 🏫 Learn More
    2. 💻 k-Means ในภาษา R: kmeans()
    3. 🔢 Dataset
      1. 🪨 rock
      2. 📏 Data Normalisation
      3. 🔎 Finding the Optimal k
    4. ⏹️ k-Means
      1. 🔥 Train the Model
      2. 🤓 Get the Results
    5. 😺 GitHub
    6. 📃 References
    7. ✅ R Book for Psychologists: หนังสือภาษา R สำหรับนักจิตวิทยา

    👉 Introduction to k-Means

    .

    🤔 k-Means คืออะไร?

    k-means เป็น machine learning algorithm ประเภท unsupervised learning และใช้จัดกลุ่ม data (clustering) ที่เราไม่รู้จำนวนกลุ่มล่วงหน้า

    ตัวอย่างการใช้ k-means ในโลกจริง:

    • Customer segmentation: จัดกลุ่มลูกค้าที่เข้ามาซื้อสินค้า/บริการ
    • Anomaly detection: ตรวจจับความผิดปกติในคอมพิวเตอร์ (แบ่งกลุ่มกิจกรรมในคอมพิวเตอร์ เป็น “ปกติ” และ “ไม่ปกติ”)
    • Document clustering: จัดกลุ่มเอกสาร โดยอ้างอิงจากเนื้อหา

    .

    🪜 Steps การทำงานของ k-Means

    k-means มีการทำงานอยู่ 5 ขั้นตอน ได้แก่:

    1. กำหนดจำนวนกลุ่ม หรือ clusters (k)
    2. สุ่มวาง centroid หรือจุดศูนย์กลางของ cluster ลงในข้อมูล
    3. จัดกลุ่มข้อมูล โดยข้อมูลจะอยู่กลุ่มเดียวกับ centroid ที่ใกล้ที่สุด
    4. คำนวณหา centroid ใหม่
    5. ทำขั้นที่ 3 และ 4 ซ้ำ ตามจำนวนครั้งที่กำหนด หรือจนกว่าข้อมูลจะไม่เปลี่ยนกลุ่ม

    ตัวอย่างเช่น เราต้องการจัดกลุ่มข้อมูล 100 ตัวอย่าง:

    ขั้นที่ 1. เรากำหนด k เช่น ให้ k = 3

    ขั้นที่ 2. สุ่มวาง centroid (ดอกจันสีแดง) ลงในข้อมูล:

    ขั้นที่ 3. จัดข้อมูลให้อยู่กลุ่มเดียวกัน โดยอิงจาก centroid ที่อยู่ใกล้ที่สุด:

    ขั้นที่ 4. คำนวณหา centroids ใหม่:

    จะสังเกตเห็นว่า centroids ของเราเปลี่ยนไป

    ขั้นที่ 5. ทำขั้นที่ 3 และ 4 ซ้ำ ๆ ไปเรื่อย ๆ เช่น ทำไป 10 ครั้ง:

    เราก็จะได้การจัดกลุ่มข้อมูลมา

    .

    🏫 Learn More

    เรียนรู้เพิ่มเติมเกี่ยวกับ k-means ได้จากคอร์ส The Nuts and Bolts of Machine Learning จาก Google Career Certificates (เริ่มต้นที่ 1:33:49)


    💻 k-Means ในภาษา R: kmeans()

    ในภาษา R เราสามารถใช้ k-means ได้ผ่าน kmeans() function ซึ่งต้องการ 3 arguments หลัก ดังนี้:

    kmeans(x, centers, nstart)
    • x = dataset ที่ต้องการจัดกลุ่ม
    • centers = จำนวนกลุ่มข้อมูล หรือ k
    • nstart = จำนวนครั้งที่ k-means จะสุ่มวาง centroids ลงใน dataset เพื่อหาการจัดกลุ่มที่ดีที่สุด

    (Note: ศึกษา arguments เพิ่มเติมของ kmeans() ได้ที่ kmeans: K-Means Clustering)

    เราไปดูวิธีใช้งาน kmeans() กัน


    🔢 Dataset

    .

    🪨 rock

    ในบทความนี้ เราจะใช้ rock dataset ซึ่งเป็น built-in dataset ในภาษา R เป็นตัวอย่าง

    rock มีข้อมูลหิน 48 ตัวอย่าง และมีข้อมูลลักษณะ 4 อย่าง:

    ลำดับลักษณะคำอธิบาย
    1areaพื้นที่ผิว
    2periเส้นผ่านศูนย์กลาง
    3shapeขนาด (เส้นผ่านศูนย์กลาง หารด้วย พื้นที่ผิว)
    4permระดับความสามารถที่ให้น้ำซึมผ่านได้

    เป้าหมายของเรา คือ จัดกลุ่มหิน 48 ตัวอย่างตามลักษณะทั้งสี่

    เราสามารถโหลด rock dataset ได้โดยใช้ data() function:

    # Load
    data(rock)
    

    หลังจากโหลดแล้ว เราสามารถ preview ข้อมูลได้ด้วย head():

    # Preview the dataset
    head(rock)
    

    ผลลัพธ์:

      area    peri     shape perm
    1 4990 2791.90 0.0903296  6.3
    2 7002 3892.60 0.1486220  6.3
    3 7558 3930.66 0.1833120  6.3
    4 7352 3869.32 0.1170630  6.3
    5 7943 3948.54 0.1224170 17.1
    6 7979 4010.15 0.1670450 17.1
    

    .

    📏 Data Normalisation

    เนื่องจาก k-means ใช้ระยะห่างระหว่างข้อมูลในการจัดกลุ่ม ข้อมูลที่มีระยะห่างมาก (เช่น ระยะห่าง 500 เมตร กับ 1,000 เมตร) อาจมีผลต่อการจัดกลุ่มมากกว่าข้อมูลที่มีระยะห่างน้อย (เช่น ระยะห่าง 1 ซม. กับ 5 ซม.) และทำให้เกิด bias ในการจัดกลุ่มได้

    เพื่อป้องกัน bias เราควร normalise ข้อมูล หรือการปรับให้ข้อมูลอยู่ใน scale เดียวกัน

    สำหรับ k-means เรามักจะ normalise ข้อมูล ด้วย z-score standardisation ซึ่งมีสูตรการคำนวณดังนี้:

    Z = (X - M(X)) / SD(X)
    • Z = ข้อมูลที่ scaled แล้ว
    • X = ข้อมูลดิบ
    • M(X) = mean ของ X
    • SD(X) = SD ของ X

    ในภาษา R เราสามารถทำ z-score standardisation ได้ด้วย scale():

    # Scale
    rock_scaled <- scale(rock)
    

    Note: เราใส่ rock ไปใน argument และเก็บผลลัพธ์ไว้ใน data frame ใหม่ ชื่อ rock_scaled

    เราสามารถเช็กผลลัพธ์ได้ด้วย:

    • colMeans() เพื่อเช็ก mean
    • apply() และ sd() เพื่อเช็ก SD
    # Check the results
    
    ## Check mean
    round(colMeans(rock_scaled), 2)
    
    # Check SD
    apply(rock_scaled, 2, sd)
    

    ผลลัพธ์:

    > ### Check mean
    > round(colMeans(rock_scaled), 2)
     area  peri shape  perm 
        0     0     0     0 
    > 
    > ### Check SD
    > apply(rock_scaled, 2, sd)
     area  peri shape  perm 
        1     1     1     1 
    

    จากผลลัพธ์ เราจะเห็นได้ว่า ทุกลักษณะมี mean เท่ากับ 0 และ SD เท่ากับ 1 แสดงว่า เราทำ z-score standardisation ได้สำเร็จ และพร้อมไปขั้นตอนถัดไป

    .

    🔎 Finding the Optimal k

    ในการจัดกลุ่มด้วย k-means เราต้องเริ่มด้วยการกำหนด k

    แต่เราจะรู้ได้ยังไงว่า k ควรมีค่าเท่าไร?

    เรามี 3 วิธีในการหาค่า k ที่ดีที่สุด (optimal k):

    1. Elbow method
    2. Silhouette analysis
    3. Gap analysis

    ในบทความนี้ เราจะมาใช้วิธีแรกกัน: elbow method

    (Note: เรียนรู้เกี่ยวทั้งสามวิธีได้ที่ ML | Determine the optimal value of K in K-Means Clustering)

    Elbow method หาค่า k ที่ดีที่สุด โดยสร้างกราฟระหว่างค่า k และ within-cluster sum of squares (WSS) หรือระยะห่างระหว่างข้อมูลในกลุ่ม ค่า k ที่ดีที่สุด คือ ค่า k ที่ WSS เริ่มไม่ลดลง

    ในภาษา R เราสามารถเริ่มสร้างกราฟได้ โดยเริ่มจากใช้ for loop หา WSS สำหรับช่วงค่า k ที่เราต้องการ

    ในตัวอย่าง rock dataset เราจะใช้ช่วงค่า k ระหว่าง 1 ถึง 15:

    # Initialise a vector for within cluster sum of squares (wss)
    wss <- numeric(15)
    
    # For-loop through the wss
    for (k in 1:15) {
      
      ## Try the k
      km <- kmeans(rock_scaled,
                   centers = k,
                   nstart = 20)
      
      ## Get WSS for the k
      wss[k] <- km$tot.withinss
    }
    

    จากนั้น ใช้ plot() สร้างกราฟความสัมพันธ์ระหว่างค่า k และ WSS:

    # Plot the wss
    plot(1:15,
         wss,
         type = "b",
         main = "The Number of Clusters vs WSS",
         xlab = "Number of Clusters",
         ylab = "WSS")
    

    ผลลัพธ์:

    จากกราฟ จะเห็นว่า WSS เริ่มชะลอตัว เมื่อค่า k อยู่ที่ 3 และ 4 ซึ่งเป็นจุดที่เป็นข้อศอก (elbow) ของกราฟ:

    แสดงว่า optimal k มีค่า 3 หรือ 4

    สำหรับบทความนี้ เราจะกำหนด optimal k = 4:

    # Set optiomal k = 4
    opt_k <- 4
    

    ⏹️ k-Means

    🔥 Train the Model

    หลังเตรียมข้อมูลและหา optimal k แล้ว เราก็พร้อมที่จะใช้ kmeans() ในการจัดกลุ่มข้อมูลแล้ว:

    # Set see for reproducibility
    set.seed(100)
    
    # Train the model
    km <- kmeans(rock_scaled,
                 centers = opt_k,
                 nstart = 20)
    

    .

    🤓 Get the Results

    เราสามารถดูผลการจัดกลุ่มได้ 2 วิธี:

    วิธีที่ 1. ดูค่าทางสถิติ:

    # Print the model
    print(km)
    

    ผลลัพธ์:

    K-means clustering with 4 clusters of sizes 10, 18, 6, 14
    
    Cluster means:
            area       peri
    1 -0.4406840 -0.9164442
    2  0.3496197  0.8022501
    3  1.5646450  1.3101981
    4 -0.8052989 -0.9383748
           shape       perm
    1  1.5369800  1.1775435
    2 -0.7319607 -0.8017914
    3  0.2358392 -0.7425075
    4 -0.2578245  0.5079897
    
    Clustering vector:
     [1] 2 2 2 2 2 2 2 2 2 2 2 2 3
    [14] 2 2 2 3 3 3 2 2 3 3 2 1 4
    [27] 4 4 4 1 1 1 4 1 4 1 4 1 4
    [40] 4 1 4 1 1 4 4 4 4
    
    Within cluster sum of squares by cluster:
    [1] 18.917267  8.104718
    [3]  1.471788 22.095636
     (between_SS / total_SS =  73.1 %)
    
    Available components:
    
    [1] "cluster"     
    [2] "centers"     
    [3] "totss"       
    [4] "withinss"    
    [5] "tot.withinss"
    [6] "betweenss"   
    [7] "size"        
    [8] "iter"        
    [9] "ifault"
    

    จากผลลัพธ์ จะเห็นได้ว่า ข้อมูลถูกแบ่งเป็น 4 กลุ่ม และเราสามารถดูค่า mean และ WSS ของแต่ละกลุ่มได้

    .

    วิธีที่ 2. สร้างกราฟ:

    # Create a plot
    plot(rock_scaled[, c("shape", "perm")], 
         col = km$cluster,
         pch = 19,
         main = "K-Means Clustering (Rock Dataset)",
         xlab = "Shape",
         ylab = "Permeability")
    
    # Add cluster centers
    points(km$centers[, c("shape", "perm")], 
           col = 1:5,
           pch = 4,
           cex = 2,
           lwd = 2)
    

    ผลลัพธ์:

    ตอนนี้ เราก็ได้ข้อมูลที่จัดกลุ่มด้วย k-means เรียบร้อยแล้ว 👍


    😺 GitHub

    ดู code ทั้งหมดในบทความนี้ได้ที่ GitHub


    📃 References


    ✅ R Book for Psychologists: หนังสือภาษา R สำหรับนักจิตวิทยา

    📕 ขอฝากหนังสือเล่มแรกในชีวิตด้วยนะครับ 😆

    🙋 ใครที่กำลังเรียนจิตวิทยาหรือทำงานสายจิตวิทยา และเบื่อที่ต้องใช้ software ราคาแพงอย่าง SPSS และ Excel เพื่อทำข้อมูล

    💪 ผมขอแนะนำ R Book for Psychologists หนังสือสอนใช้ภาษา R เพื่อการวิเคราะห์ข้อมูลทางจิตวิทยา ที่เขียนมาเพื่อนักจิตวิทยาที่ไม่เคยมีประสบการณ์เขียน code มาก่อน

    ในหนังสือ เราจะปูพื้นฐานภาษา R และพาไปดูวิธีวิเคราะห์สถิติที่ใช้บ่อยกัน เช่น:

    • Correlation
    • t-tests
    • ANOVA
    • Reliability
    • Factor analysis

    🚀 เมื่ออ่านและทำตามตัวอย่างใน R Book for Psychologists ทุกคนจะไม่ต้องพึง SPSS และ Excel ในการทำงานอีกต่อไป และสามารถวิเคราะห์ข้อมูลด้วยตัวเองได้ด้วยความมั่นใจ

    แล้วทุกคนจะแปลกใจว่า ทำไมภาษา R ง่ายขนาดนี้ 🙂‍↕️

    👉 สนใจดูรายละเอียดหนังสือได้ที่ meb:

  • สอนปลูกต้นไม้ในภาษา R (ภาค 1): วิธีสร้าง tree-based models ใน 3 ขั้นตอนด้วย rpart และ randomForest packages — ตัวอย่างการทำนายประเภทเกียร์รถใน mtcars dataset

    สอนปลูกต้นไม้ในภาษา R (ภาค 1): วิธีสร้าง tree-based models ใน 3 ขั้นตอนด้วย rpart และ randomForest packages — ตัวอย่างการทำนายประเภทเกียร์รถใน mtcars dataset

    ในบทความนี้ เราจะมาทำความรู้จักและสร้าง tree-based models ในภาษา R กัน:

    1. Classification tree
    2. Random forest

    ถ้าพร้อมแล้ว ไปเริ่มกันเลย


    🌳 Tree-Based Algorithms คืออะไร?

    Tree-based algorithm เป็น machine learning algorithm ประเภท supervised learning ที่ทำนายข้อมูลโดยใช้ decision tree

    Decision tree เป็นเครื่องมือช่วยตัดสินใจที่ดูคล้ายกับต้นไม้กลับหัว เพราะประกอบด้วยจุดตัดสินใจ (node) ที่แตกยอด (ทางเลือก) ออกไปเรื่อย ๆ เพื่อใช้ทำนายผลลัพธ์ที่ต้องการ

    ยกตัวอย่างเช่น เราอยากรู้ว่า เราควรจะสมัครงานกับบริษัทแห่งหนึ่งไหม เราอาจจะสร้าง decision tree จาก 3 ปัจจัย คือ:

    1. เงินเดือน
    2. ได้ใช้ทักษะที่มี
    3. การทำงานแบบ hybrid หรือ remote

    ได้แบบนี้:

    จาก decision tree ถ้าเราเห็นงานที่ได้เงินเดือนไม่ตรงใจ เราจะไม่สมัครงานนั้น (เส้นการตัดสินใจซ้ายสุด)

    ในทางกลับกัน ถ้างานมีเงินเดือนที่น่าสนใจ และได้ใช้ทักษะที่มีอยู่ เราจะสมัครงานนั้น (เส้นการตัดสินใจขวาสุด) เป็นต้น


    💻 Tree-Based Models ในภาษา R

    ในภาษา R เราสามารถสร้าง tree-based model ได้ด้วย rpart() จาก rpart package:

    # Install
    install.packages("rpart")
    # Load
    library(rpart)
    

    rpart() ต้องการ 4 arguments ดังนี้:

    rpart(formula, data, method, control)
    • formula = สูตรในการวิเคราะห์ (ตัวแปรตาม ~ ตัวแปรต้น)
    • data = dataset ที่ใช้สร้าง model
    • method = ประเภท algorithm ("anova" สำหรับ regression และ "class" สำหรับ classification)
    • control (optional) = เงื่อนไขควบคุม “การเติบโต” ของ decision tree เช่น ระดับชั้นที่มีได้ เป็นต้น

    (Note: ศึกษาการใช้งาน rpart() เพิ่มเติมได้ที่ rpart: Recursive Partitioning and Regression Trees)

    เราไปดูตัวอย่างการใช้งาน rpart() กัน

    .

    🚗 Dataset: mtcars

    ในบทความนี้ เราจะลองสร้าง tree-based model ประเภท classification หรือ classification tree เพื่อทำนายประเภทเกียร์รถใน mtcars dataset

    mtcars เป็นชุดข้อมูลรถจาก ปี ค.ศ. 1974 ซึ่งประกอบไปด้วยข้อมูล เช่น รุ่นรถ น้ำหนัก ระดับการกินน้ำมัน แรงม้า เป็นต้น

    เราสามารถโหลด mtcars มาใช้งานได้ด้วย data() และ preview ด้วย head():

    # Load
    data(mtcars)
    # Preview
    head(mtcars)
    

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

                       mpg cyl disp  hp drat    wt  qsec vs        am gear carb
    Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0    manual    4    4
    Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0    manual    4    4
    Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1    manual    4    1
    Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1 automatic    3    1
    Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0 automatic    3    2
    Valiant           18.1   6  225 105 2.76 3.460 20.22  1 automatic    3    1
    

    .

    🔧 Prepare the Data

    ก่อนนำ mtcars ไปใช้สร้าง classification tree เราจะต้องทำ 2 อย่างก่อน:

    อย่างที่ #1. ปรับ column am ให้เป็น factor เพราะสิ่งที่เราต้องการทำนายเป็น categorical data:

    # Convert `am` to factor
    mtcars$am <- factor(mtcars$am,
                        levels = c(0, 1),
                        labels = c("automatic", "manual"))
    # Check the result
    class(mtcars$am)
    

    ผลลัพธ์:

    [1] "factor"
    

    อย่างที่ #2. Split ข้อมูลเป็น 2 ชุด:

    1. Training set สำหรับสร้าง model
    2. Test set สำหรับประเมิน model
    # Set seed for reproducibility
    set.seed(500)
    # Get training index
    train_index <- sample(nrow(mtcars),
                          nrow(mtcars) * 0.7)
    # Split the data
    train_set <- mtcars[train_index, ]
    test_set <- mtcars[-train_index, ]
    

    .

    🪴 Train the Model

    ตอนนี้ เราพร้อมที่จะสร้าง classification tree ด้วย rpart() แล้ว

    สำหรับ classification tree ในบทความนี้ เราจะลองตั้งเงื่อนไขในการปลูกต้นไม้ (control) ดังนี้:

    ArgumentExplanation
    cp = 0คะแนนประสิทธิภาพขั้นต่ำ ก่อนจะแตกกิ่งใหม่ได้ = 0
    minsplit = 1จำนวนกิ่งย่อยขั้นต่ำที่ต้องมี ก่อนจะแตกกิ่งใหม่ได้ = 1
    maxdepth = 5จำนวนชั้นที่ decision tree มีได้สูงสุด = 5
    # Classification tree
    ct <- rpart(am ~ .,
                data = train_set,
                method = "class",
                control = rpart.control(cp = 0, minsplit = 1, maxdepth = 5))
    

    เราสามารถดู classification tree ของเราได้ด้วย rpart.plot():

    # Plot classification tree
    rpart.plot(ct,
               type = 3,
               extra = 101,
               under = TRUE,
               digits = 3,
               tweak = 1.2)
    

    ผลลัพธ์:

    Note:

    • ก่อนใช้งาน rpart.plot() เราต้องจะติดตั้งและเรียกใช้งานด้วย install.packages() และ library() ตามลำดับ
    • ศึกษาการใช้งาน rpart.plot() เพิ่มเติมได้ที่ rpart.plot: Plot an rpart model. A simplified interface to the prp function.

    .

    📏 Evaluate the Model

    เมื่อได้ classification tree มาแล้ว เราลองมาประเมินความสามารถของ model ด้วย accuracy หรือสัดส่วนการทำนายที่ถูกต้องกัน

    เราเริ่มจากใช้ predict() เพื่อใช้ model ทำนายประเภทเกียร์:

    # Predict the outcome
    test_set$pred_ct <- predict(ct,
                                newdata = test_set,
                                type = "class")
    

    จากนั้น สร้าง confusion matrix หรือ matrix เปรียบเทียบคำทำนายกับข้อมูลจริง:

    # Create a confusion matrix
    cm_ct <- table(Predicted = test_set$pred_ct,
                   Actual = test_set$am)
    # Print confusion matrix
    print(cm_ct)
    

    ผลลัพธ์:

               Actual
    Predicted   automatic manual
      automatic         5      1
      manual            0      4
    

    สุดท้าย เราหา accuracy ด้วยการนำจำนวนคำทำนายที่ถูกต้องมาหารด้วยจำนวนคำทำนายทั้งหมด:

    # Get accuracy
    acc_ct <- sum(diag(cm_ct)) / sum(cm_ct)
    # Print accuracy
    cat("Accuracy (classification tree):", acc_ct)
    

    ผลลัพธ์:

    Accuracy (classification tree): 0.9
    

    จะเห็นได้ว่า model ของเรามีความแม่นยำถึง 90%


    🍄 Random Forest

    Random forest เป็น tree-based algorithm ที่ช่วยเพิ่มความแม่นยำในการทำนาย โดยสุ่มสร้าง decision trees ต้นเล็กขึ้นมาเป็นกลุ่ม (forest) แทนการปลูก decision tree ต้นเดียว

    Decision tree แต่ละต้นใน random forest มีความสามารถในการทำนายแตกต่างกัน ซึ่งบางต้นอาจมีความสามารถที่น้อยมาก

    แต่จุดแข็งของ random forest อยู่ที่จำนวน โดย random forest ทำนายผลลัพธ์โดยดูจากผลลัพธ์ในภาพรวม ดังนี้:

    TaskPredict by
    Regressionค่าเฉลี่ยของผลลัพธ์การทำนายของทุกต้น
    Classificationเสียงส่วนมาก (majority vote)

    ดังนั้น แม้ว่า decision tree บางต้นอาจทำนายผิดพลาด แต่โดยรวมแล้ว random forest มีโอกาสที่จะทำนายได้ดีกว่า decision tree ต้นเดียว

    ในภาษา R เราสามารถสร้าง random forest ได้ด้วย randomForest() จาก randomForest package ซึ่งต้องการ 3 arguments:

    randomFrest(formula, data, ntree)
    • formula = สูตรในการวิเคราะห์ (ตัวแปรตาม ~ ตัวแปรต้น)
    • data = dataset ที่ใช้สร้าง model
    • ntree = จำนวน decision trees ที่ต้องการสร้าง

    Note:

    • เราไม่ต้องกำหนดว่า จะทำ classification หรือ regression model เพราะ randomForest() จะเลือก model ให้อัตโนมัติตามข้อมูลที่เราใส่เข้าไป
    • ศึกษาการใช้งาน randomForest() เพิ่มเติมได้ที่ randomForest: Classification and Regression with Random Forest

    ก่อนใช้ randomForest() เราต้องเตรียมข้อมูลแบบเดียวกันกับ rpart() ได้แก่:

    1. เปลี่ยน am ให้เป็น factor
    2. Split the data

    สมมุติว่า เราเตรียมข้อมูลแล้ว เราสามารถเรียกใช้ randomForest() ได้เลย โดยเราจะลองสร้าง random forest ที่ประกอบด้วย decision trees 100 ต้น:

    # Random forest
    rf <- randomForest(am ~ .,
                       data = train_set,
                       ntree = 100)
    

    แล้วลองประเมินความสามารถของ model ด้วย accuracy

    เริ่มจากทำนายประเภทเกียร์:

    # Predict the outcome
    test_set$pred_rf <- predict(rf,
                                newdata = test_set,
                                type = "class")
    

    สร้าง confusion matrix:

    # Create a confusion matrix
    cm_rf <- table(Predicted = test_set$pred_rf,
                   Actual = test_set$am)
    # Print confusion matrix
    print(cm_rf)
    

    ผลลัพธ์:

               Actual
    Predicted   automatic manual
      automatic         5      0
      manual            0      5
    

    และสุดท้าย คำนวณ accuracy:

    # Get accuracy
    acc_rf <- sum(diag(cm_rf)) / sum(cm_rf)
    # Print accuracy
    cat("Accuracy (random forest):", acc_rf)
    

    ผลลัพธ์:

    Accuracy (random forest): 1
    

    จะเห็นว่า random forest (100%) มีความแม่นยำในการทำนายมากกว่า classification tree ต้นเดียว (90%)


    🐱 GitHub

    ดู code ทั้งหมดในบทความนี้ได้ที่ GitHub:


    📃 References


    ✅ R Book for Psychologists: หนังสือภาษา R สำหรับนักจิตวิทยา

    📕 ขอฝากหนังสือเล่มแรกในชีวิตด้วยนะครับ 😆

    🙋 ใครที่กำลังเรียนจิตวิทยาหรือทำงานสายจิตวิทยา และเบื่อที่ต้องใช้ software ราคาแพงอย่าง SPSS และ Excel เพื่อทำข้อมูล

    💪 ผมขอแนะนำ R Book for Psychologists หนังสือสอนใช้ภาษา R เพื่อการวิเคราะห์ข้อมูลทางจิตวิทยา ที่เขียนมาเพื่อนักจิตวิทยาที่ไม่เคยมีประสบการณ์เขียน code มาก่อน

    ในหนังสือ เราจะปูพื้นฐานภาษา R และพาไปดูวิธีวิเคราะห์สถิติที่ใช้บ่อยกัน เช่น:

    • Correlation
    • t-tests
    • ANOVA
    • Reliability
    • Factor analysis

    🚀 เมื่ออ่านและทำตามตัวอย่างใน R Book for Psychologists ทุกคนจะไม่ต้องพึง SPSS และ Excel ในการทำงานอีกต่อไป และสามารถวิเคราะห์ข้อมูลด้วยตัวเองได้ด้วยความมั่นใจ

    แล้วทุกคนจะแปลกใจว่า ทำไมภาษา R ง่ายขนาดนี้ 🙂‍↕️

    👉 สนใจดูรายละเอียดหนังสือได้ที่ meb:

  • วิธีสร้างและประเมิน logistic regression model ใน 5 ขั้นตอน ด้วย glm(), roc(), และ auc() ในภาษา R — ตัวอย่างการทำนายประเภทเกียร์รถใน mtcars dataset

    วิธีสร้างและประเมิน logistic regression model ใน 5 ขั้นตอน ด้วย glm(), roc(), และ auc() ในภาษา R — ตัวอย่างการทำนายประเภทเกียร์รถใน mtcars dataset

    ในบทความนี้ เราจะมาทำความรู้จักกับ logistic regression model รวมทั้งการสร้างและประเมิน logistic regression ด้วย glm(), roc(), และ auc() ในภาษา R กัน


    1. 📈 Logistic Regression คืออะไร?
    2. 🔨 วิธีสร้าง Logistic Regression ในภาษา R
    3. 1️⃣ Step 1. Load the Dataset
    4. 2️⃣ Step 2. Prepare the Data
    5. 3️⃣ Step 3. Split the Data
    6. 4️⃣ Step 4. Train the Model
    7. 5️⃣ Step 5. Evaluate the Model
      1. ⚖️ Threshold
      2. 🎯 Metric #1. Accuracy
      3. 📈 Metric #2. ROC Curve
      4. 📉 Metric #3. AUC
    8. 😺 GitHub
    9. ✅ R Book for Psychologists: หนังสือภาษา R สำหรับนักจิตวิทยา

    📈 Logistic Regression คืออะไร?

    Logistic regression เป็น machine learning algorithm ประเภท classification สำหรับทำนายผลลัพธ์ที่มี 2 ค่า (binary) เช่น:

    • Spam filter: เป็น spam vs เป็นอีเมลปกติ
    • Churn prediction: ลูกค้าจะเลิกใช้บริการ vs ใช้บริการต่อ
    • Fraud detection: เป็นธุรกรรมทุจริต vs ไม่ทุจริต
    • Disease diagnosis: เป็นโรค vs ไม่เป็นโรค

    โดยการทำงานของ logistic regression เป็นการต่อยอดจาก linear regression

    ใน linear regression เราหาเส้นตรงที่ช่วยทำนายตัวแปรตาม (y) ด้วยตัวแปรต้น (x) ได้ดีที่สุด ตามสมการเส้นตรง:

    y = mx + c
    • y = ตัวแปรตาม
    • m = ความชันของเส้นตรง
    • x ตัวแปรต้น
    • c = จุดตัดระหว่าง x และ y

    Linear regression ใช้งานได้ดีกับข้อมูลที่เป็น continuous data และความสัมพันธ์ระหว่าง x และ y เป็นเส้นตรง:

    แต่เส้นตรงไม่ใช่เส้นที่ดีที่สุด ในการทำนาย y ที่มีเพียง 2 ระดับ:

    เพื่อแก้ปัญหานี้ เราต้องใช้ logistic regression ซึ่งใช้ sigmoid function ที่ทำนายความเป็นได้ (probability) ที่ y จะตกอยู่ในระดับใดระดับหนึ่ง แทนการทำนายค่า y โดยตรง:

    y = sigmoid_func(mx + c)
    • y = ตัวแปรตาม
    • sigmoid_func = sigmoid function
    • m = ความชันของเส้นตรง
    • x ตัวแปรต้น
    • c = จุดตัดระหว่าง x และ y

    เมื่อใช้ sigmoid function เราจะได้เส้นในการทำนายข้อมูลเรียกว่า sigmoid curve ที่ดูคล้ายตัว S ดังภาพ:


    🔨 วิธีสร้าง Logistic Regression ในภาษา R

    ในภาษา E เราสร้าง logistic regression model ได้ง่าย ๆ ด้วย glm() function โดยทำตาม 5 ขั้นตอนของ machine learning workflow:

    1. Load the dataset
    2. Prepare the data
    3. Split the data
    4. Train the model
    5. Evaluate the model

    1️⃣ Step 1. Load the Dataset

    ในขั้นแรก ให้เราโหลด dataset ที่จะใช้งานเข้ามาใน R

    โดยในบทความนี้ เราจะทำงานกับ mtcars dataset ซึ่งมข้อมูลรถจาก ปี ค.ศ. 1974 เช่น รุ่นรถ ระดับการกินน้ำมัน แรงม้า ประเภทเกียร์ และน้ำหนัก

    เป้าหมายของเรา คือ สร้าง logistic regression model เพื่อทำนายประเภทเกียร์ ว่า เป็นรถเกียร์ auto (0) หรือ manual (1)

    เนื่องจาก mtcars เป็น built-in dataset ในภาษา R เราสามารถโหลดข้อมูลได้ด้วย data() function:

    # Load the dataset
    data(mtcars)
    

    หลังการโหลด เราสามารถ preview ข้อมูลได้ด้วย head():

    # Preview the dataset
    head(mtcars)
    

    ผลลัพธ์:

                       mpg cyl disp  hp drat    wt  qsec vs        am gear carb
    Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0    manual    4    4
    Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0    manual    4    4
    Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1    manual    4    1
    Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1 automatic    3    1
    Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0 automatic    3    2
    Valiant           18.1   6  225 105 2.76 3.460 20.22  1 automatic    3    1
    

    2️⃣ Step 2. Prepare the Data

    สำหรับการสร้าง logistic regression model ตัวแปรตามของเราจะต้องมี data type เป็น factor

    เราสามารถเช็ก data type ของ dataset ได้ด้วย str():

    # Check the data typs of the columns
    str(mtcars)
    

    ผลลัพธ์:

    'data.frame':	32 obs. of  11 variables:
     $ mpg : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
     $ cyl : num  6 6 4 6 8 6 8 4 4 6 ...
     $ disp: num  160 160 108 258 360 ...
     $ hp  : num  110 110 93 110 175 105 245 62 95 123 ...
     $ drat: num  3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...
     $ wt  : num  2.62 2.88 2.32 3.21 3.44 ...
     $ qsec: num  16.5 17 18.6 19.4 17 ...
     $ vs  : num  0 0 1 1 0 1 0 1 1 1 ...
     $ am  : num  1 1 1 0 0 0 0 0 0 0 ...
     $ gear: num  4 4 4 3 3 3 3 4 4 4 ...
     $ carb: num  4 4 1 1 2 1 4 2 2 4 ...
    

    จากผลลัพธ์ เราจะเห็นได้ว่า am ซึ่งบอกประเภทเกียร์รถ มี data type เป็น num (numeric) แสดงว่า เราจะต้องทำ operation เพื่อเปลี่ยน data type ก่อนไปขั้นต่อไป

    เราสามารถเปลี่ยน data type ได้ด้วย factor():

    # Convert column `am` to factor
    mtcars$am <- factor(mtcars$am,
                        levels = c(0, 1),
                        labels = c("automatic", "manual"))
    

    จากนั้น เช็กผลลัพธ์ที่ได้ด้วย str() อีกครั้ง:

    # Check the result
    str(mtcars)
    

    ผลลัพธ์:

    'data.frame':	32 obs. of  11 variables:
     $ mpg : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
     $ cyl : num  6 6 4 6 8 6 8 4 4 6 ...
     $ disp: num  160 160 108 258 360 ...
     $ hp  : num  110 110 93 110 175 105 245 62 95 123 ...
     $ drat: num  3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...
     $ wt  : num  2.62 2.88 2.32 3.21 3.44 ...
     $ qsec: num  16.5 17 18.6 19.4 17 ...
     $ vs  : num  0 0 1 1 0 1 0 1 1 1 ...
     $ am  : Factor w/ 2 levels "automatic","manual": 2 2 2 1 1 1 1 1 1 1 ...
     $ gear: num  4 4 4 3 3 3 3 4 4 4 ...
     $ carb: num  4 4 1 1 2 1 4 2 2 4 ...
    

    จะเห็นว่า ตอนนี้ am เป็น factor แล้ว และเราสามารถไปขั้นตอนถัดไปได้


    3️⃣ Step 3. Split the Data

    ในขั้นที่สาม เราจะต้องแบ่ง dataset เป็น 2 ชุด ได้แก่:

    1. Training set สำหรับสร้าง model
    2. Test set สำหรับประเมินความสามารถของ model

    เราแบ่ง dataset ได้โดยเริ่มจากสร้าง row index ที่จะอยู่ใน training set:

    # Set seed for reproducibility
    set.seed(300)
    
    # Create a training index
    train_index <- sample(1:nrow(mtcars),
                          nrow(mtcars) * 0.7)
    

    Note: เรากำหนด row index ใน training set เป็น 70% แสดงว่า test set จะมีข้อมูล 30% จาก dataset

    จากนั้น ใช้ row index แบ่ง dataset เป็น 2 ชุด:

    # Create training and test sets
    train_set <- mtcars[train_index, ]
    test_set <- mtcars[-train_index, ]
    

    ตอนนี้ เราพร้อมที่จะสร้าง model กันแล้ว


    4️⃣ Step 4. Train the Model

    ในขั้นที่สี่ เราจะสร้าง logistic regression model โดยใช้ glm() function กัน

    glm() ต้องการ input 3 อย่าง:

    glm(formula, data, family)
    No.Inputคำอธิบายในบทความนี้
    1formulaตัวแปรตามที่ต้องการทำนาย และตัวแปรต้นที่จะใช้ทำนายam ~ .
    2dataชุดข้อมูลที่จะใช้สร้าง modeltrain_set
    3familyRegression algorithm ที่เราจะเรียกใช้"binomial"
    # Build a logistic regression model
    log_reg <- glm(am ~ .,
                   data = train_set,
                   family = "binomial")
    

    ตอนนี้ เราก็จะได้ logistic regression model ในการทำนายประเภทเกียร์มาเรียบร้อย


    5️⃣ Step 5. Evaluate the Model

    ในขั้นสุดท้าย เราจะประเมินความสามารถของ model ในการทำนายประเภทเกียร์กัน

    เราจะใช้ 3 metrics ในการประเมิน:

    1. Accuracy: สัดส่วนของผลลัพธ์ที่ทำนายถูก
    2. ROC curve: กราฟแสดงความสัมพันธ์ระหว่าง true positive rate (TPR) และ false positive rate (FPR) โดยยิ่งเส้นกราฟออกห่างเหนือเส้นตรงมากเท่าไรก็ยิ่งดี
    3. AUC: พื้นที่ใต้กราฟของ ROC โดยมีค่าระหว่าง 0 กับ 1 โดยค่ายิ่งเข้าใกล้ 1 เท่าไรก็ยิ่งดี

    .

    ⚖️ Threshold

    ในการคำนวณทั้ง 3 metrics เราจะต้องกำหนด threshold เพื่อทำนายปรพเภทเกียร์ก่อน เพราะ glm() ให้ model ที่ส่งค่าความเป็นไปได้ (แทนประเภทเกียร์) กลับมา เช่น:

    • 0.45
    • 0.32
    • 0.93

    Threshold จะเป็นค่าที่ระบุประเภทเกียร์ให้เรา เช่น เรากำหนด threshold ที่ 0.30:

    ความเป็นไปได้เทียบกับ 0.30ประเภทเกียร์ที่ทำนาย
    0.45> 0.30Manual
    0.32> 0.30Manual
    0.93> 0.30Manual

    หรือ threshold ที่ 0.80:

    ความเป็นไปได้เทียบกับ 0.80ประเภทเกียร์ที่ทำนาย
    0.45< 0.80Auto
    0.32< 0.80Auto
    0.93> 0.80Manual

    จะเห็นว่า threshold ที่เรากำหนด มีผลต่อผลลัพธ์ในการทำนาย

    Note: ทั้งนี้ threshold ที่ดีที่สุดขึ้นอยู่กับแต่ละ model

    ในบทความนี้ เราจะลองกำหนด threshold ไว้ที่ 0.50

    เมื่อกำหนด threshold แล้ว เราจะใช้ predict() เพื่อสร้าง column ที่เก็บค่าความเป็นไปได้ ใน test_set:

    # Get predictive probability
    test_set$pred_prob <- predict(log_reg,
                                  newdata = test_set,
                                  type = "response")
    

    จากนั้น ใช้ ifelse() และ threshold เพื่อทำนายประเภทเกียร์:

    # Predict the outcome
    test_set$pred <- ifelse(test_set$pred_prob > 0.5,
                            1,
                            0)
    
    # Set column `pred ` as factor
    test_set$pred <- factor(test_set$pred,
                            levels = c(0, 1),
                            labels = c("automatic", "manual"))
    

    จากนั้น เราดูผลลัพธ์ได้ด้วย head():

    # Check the results
    head(test_set[c("pred_prob", "pred", "am")])
    

    ผลลัพธ์:

                          pred_prob      pred        am
    Datsun 710         1.000000e+00    manual    manual
    Hornet 4 Drive     2.220446e-16 automatic automatic
    Merc 240D          9.999999e-01    manual automatic
    Merc 280C          2.220446e-16 automatic automatic
    Cadillac Fleetwood 2.220446e-16 automatic automatic
    Chrysler Imperial  3.941802e-11 automatic automatic
    

    ตอนนี้ เราได้ผลลัพธ์ในการทำนายมา และพร้อมที่จะคำนวณ metrics ในการประเมินแล้ว

    .

    🎯 Metric #1. Accuracy

    เรามาคำนวณแต่ละ metric กัน โดยเริ่มจาก accuracy

    สำหรับ accuracy เราจะสร้าง confusion matrix ที่เปรียบการทำนายและประเภทเกียร์จริง ๆ ในข้อมูล:

    # Create a confusion matrix
    cm <- table(Predicted = test_set$pred,
                Actual = test_set$am)
    
    # Print cm
    print(cm)
    

    ผลลัพธ์:

               Actual
    Predicted   automatic manual
      automatic         6      1
      manual            1      2
    

    จากนั้น เรานำสัดส่วนผลลัพธ์ที่ทำนายถูกมาหารด้วยผลลัพธ์ทั้งหมด:

    # Compute accuracy
    accuracy <- sum(diag(cm)) / sum(cm)
    
    # Print accuracy
    cat("Accuracy:", round(accuracy, 2))
    

    ผลลัพธ์:

    Accuracy: 0.8
    

    จะเห็นได้ว่า model มีความแม่นยำในการทำนายอยู่ที่ 80%

    .

    📈 Metric #2. ROC Curve

    สำหรับการสร้าง ROC curve เราจะเรียกใช้ roc() function จาก pROC package

    Note: ในการใช้งาน pROC package ให้รันคำสั่ง install.packages("pROC") เพื่อติดตั้ง และ library(pROC) เพื่อเรียกใช้งาน

    roc() ต้องการ input 2 อย่าง:

    roc(actual, predicted)
    1. actual = ประเภทเกียร์ในข้อมูลจริง
    2. predicted = ความเป็นไปได้ในการทำ
    # Calculate ROC
    ROC <- roc(test_set$am,
               pred_prob)
    

    จากนั้น เราสร้างกราฟ ROC curve ด้วย plot():

    # Plot ROC
    plot(ROC,
         main = "ROC Curve",
         col = "blue",
         lwd = 2)
    

    ผลลัพธ์:

    จากกราฟ ดูเหมือนว่า model ของเราอาจจะไม่ได้ทำได้ดีเท่ากับ accuracy เพราะเส้นกราฟ (สีน้ำเงิน) ไม่ได้ออกห่างจากเส้นตรงมากนัก และมีบางส่วนที่อยู่ใต้เส้นตรง

    .

    📉 Metric #3. AUC

    สุดท้าย เรามาคำนวณพื้นที่ใต้กราฟ ด้วย auc() จาก pROC() package เพื่อดูว่า การตีความ ROC curve เป็นอย่างอย่างที่เราคิดไหม:

    # Calculate AUC
    AUC <- auc(ROC)
    
    # Print AUC
    print(AUC)
    

    ผลลัพธ์:

    Area under the curve: 0.6429
    

    จะเห็นได้ว่า model ของเรายังมีประสิทธิภาพไม่ดีมาก เพราะมีค่าน้อยกว่า 1 มาก ซึ่งเป็นไปตามการอ่าน ROC curve ก่อนหน้านี้

    Note: จากผลลัพธ์ เราอาจจะอยากไปปรับปรุง model ของเรา ซึ่งเราสมารถทำได้ 2 วิธี:

    1. เพิ่มข้อมูลใน training set
    2. ปรับ threshold

    😺 GitHub

    ดู code ทั้งหมดในบทความนี้ได้ที่ GitHub


    📃 References


    ✅ R Book for Psychologists: หนังสือภาษา R สำหรับนักจิตวิทยา

    📕 ขอฝากหนังสือเล่มแรกในชีวิตด้วยนะครับ 😆

    🙋 ใครที่กำลังเรียนจิตวิทยาหรือทำงานสายจิตวิทยา และเบื่อที่ต้องใช้ software ราคาแพงอย่าง SPSS และ Excel เพื่อทำข้อมูล

    💪 ผมขอแนะนำ R Book for Psychologists หนังสือสอนใช้ภาษา R เพื่อการวิเคราะห์ข้อมูลทางจิตวิทยา ที่เขียนมาเพื่อนักจิตวิทยาที่ไม่เคยมีประสบการณ์เขียน code มาก่อน

    ในหนังสือ เราจะปูพื้นฐานภาษา R และพาไปดูวิธีวิเคราะห์สถิติที่ใช้บ่อยกัน เช่น:

    • Correlation
    • t-tests
    • ANOVA
    • Reliability
    • Factor analysis

    🚀 เมื่ออ่านและทำตามตัวอย่างใน R Book for Psychologists ทุกคนจะไม่ต้องพึง SPSS และ Excel ในการทำงานอีกต่อไป และสามารถวิเคราะห์ข้อมูลด้วยตัวเองได้ด้วยความมั่นใจ

    แล้วทุกคนจะแปลกใจว่า ทำไมภาษา R ง่ายขนาดนี้ 🙂‍↕️

    👉 สนใจดูรายละเอียดหนังสือได้ที่ meb:

  • วิธีสร้าง Naïve Bayes classifier ใน 5 ขั้นตอนด้วย naivebayes package ในภาษา R – ตัวอย่างการทำนายประเภทดอกไม้ใน iris dataset

    วิธีสร้าง Naïve Bayes classifier ใน 5 ขั้นตอนด้วย naivebayes package ในภาษา R – ตัวอย่างการทำนายประเภทดอกไม้ใน iris dataset

    ในบทความนี้ เราจะมาทำความรู้กับ Naïve Bayes และดูวิธีสร้าง Naïve Bayes classifier ในภาษา R ด้วย naivebayes package กัน


    1. 👼 Naïve Bayes คืออะไร?
    2. 🧑‍💻 วิธีสร้าง NB Classifer ด้วย naivebayes Package
      1. 1️⃣ Step 1. Install & Load the Package
      2. 2️⃣ Step 2. Load & Preview the Dataset
      3. 3️⃣ Step 3. Split the Dataset
      4. 4️⃣ Step 4. Create a NB Model
      5. 5️⃣ Step 5. Evaluate the Model
    3. 😺 GitHub
    4. 📃 References
    5. ✅ R Book for Psychologists: หนังสือภาษา R สำหรับนักจิตวิทยา

    👼 Naïve Bayes คืออะไร?

    Naïve Bayes (NB) เป็น machine learning algorithm ประเภท supervised learning สำหรับทำนายกลุ่มของข้อมูล (classification)

    NB ทำนายข้อมูล โดยวิเคราะห์ความน่าจะเป็นที่ 2 เหตุการณ์ (ตัวแปรต้นและตัวแปรตาม) จะเกิดขึ้นคู่กัน

    ยกตัวอย่างเช่น การอนุมัติสินเชื่อ (อนุมัติ/ไม่อนุมัติ) ที่เกิดขึ้นอยู่กับ:

    • รายได้: รายได้มาก -> อนุมัติ
    • อายุ: อายุน้อย -> อนุมัติ
    • ประวัติการขอสินเชื่อ: เคยขอแล้วผ่าน -> อนุมัติ

    NB คำนวณความน่าจะเป็นของแต่ละปัจจัยต่อตัวแปรตาม (การอนุมัติ) โดยอนุมานว่า แต่ละปัจจัยเกิดแยกกัน (independent) แม้ว่าในความเป็นจริงหลายปัจจัยจะเกิดขึ้นร่วมกัน (dependent; เช่น อายุมาก -> รายได้มาก) ก็ตาม

    เนื่องจาก NB มีการมองโลกอย่างง่าย จึงได้ชื่อว่า “naïve” หรือไร้เดียงนั่นเอง

    แม้ว่า NB จะมีการมองโลกที่ไร้เดียงสา แต่ก็เป็น algorithm ที่:

    1. เข้าใจได้ง่าย (เพราะไร้เดียงสา)
    2. รวดเร็ว (เพราะใช้การวิเคราะห์อย่างง่าย)
    3. น่าเชื่อถือ (มักจะทำนายได้แม่นยำ แม้จะมีมุมมองที่ไม่ตรงกับความเป็นจริง)

    🧑‍💻 วิธีสร้าง NB Classifer ด้วย naivebayes Package

    วิธีการสร้าง NB classifier ด้วย naivebayes package มี 5 ขั้นตอน ได้แก่:

    1. Install and load the package
    2. Load and preview the dataset
    3. Split the dataset
    4. Create a NB model
    5. Evaluate the model

    .

    1️⃣ Step 1. Install & Load the Package

    ในขั้นแรก เราต้องติดตั้งและเรียกใช้งาน naivebayes package:

    # Install and load the package
    ## Install
    install.packages("naivebayes")
    ## Load
    library(naivebayes)
    

    Note: เราทำการติดตั้งแค่ครั้งแรกครั้งเดียว แต่การเรียกใช้ต้องทำทุกครั้งทุกเริ่ม session ใหม่

    .

    2️⃣ Step 2. Load & Preview the Dataset

    ในขั้นที่สอง ให้เราโหลด dataset ที่จะใช้งาน

    โดยในบทความนี้ เราจะใช้ built-in dataset ในภาษา R ชื่อ iris dataset

    iris dataset มีกลีบดอกของข้อมูลดอกไม้ 3 ชนิด ได้แก่:

    • Iris setosa
    • Iris virginica
    • Iris versicolor

    เป้าหมายของเรา คือ ทำนายประเภทของดอกไม้จากความกว้างและความยาวกลีบดอก

    เนื่องจากเป็น built-in dataset เราสามารถโหลด iris dataset ด้วยคำสั่ง data():

    # Load
    data(iris)
    

    จากนั้น เราสามารถใช้คำสั่ง head() เพื่อ preview ข้อมูล:

    # Preview
    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
    

    Note: จะเห็นว่า iris dataset มีข้อมูลทั้งหมด 5 columns คือ ความยาวและความกว้างของกลีบดอกชั้นนอก (sepal) และความยาวและความกว้างของกลีบดอกชั้นใน (petal) รวมทั้งประเภทดอกไม้ (species)

    เนื่องจาก NB classifier ต้องการตัวแปรตามที่เป็น factor เราต้องเช็กได้ว่า Species เป็น data type ไหนด้วยคำสั่ง str():

    # Preview
    str(iris)
    

    ผลลัพธ์:

    'data.frame':	150 obs. of  5 variables:
     $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
     $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
     $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
     $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
     $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
    

    จะเห็นได้ว่า Species เป็น factor อยู่แล้ว และพร้อมที่ใช้สร้าง NB classifier

    .

    3️⃣ Step 3. Split the Dataset

    ในขั้นที่สาม เราจะแบ่งข้อมูลเป็น 2 ชุด:

    1. Training set เพื่อสร้าง NB classifier
    2. Test set เพื่อทดสอบประสิทธิภาพของ NB classifier

    ขั้นแรกในการแบ่งข้อมูล ให้เราสุ่มเลือก row index ที่จะอยู่ใน training set:

    # Set seed for reproducibility
    set.seed(2025)
    # Create a training index
    training_index <- sample(1:nrow(iris),
                             0.7 * nrow(iris))
    

    จากนั้น ใช้ row index ที่ได้แบ่งข้อมูลเป็น 2 ชุด:

    # Split the dataset
    train_set <- iris[training_index, ]
    test_set <- iris[-training_index, ]
    

    .

    4️⃣ Step 4. Create a NB Model

    ในขั้นที่สี่ เราจะสร้าง NB classifier โดยใช้ naive_bayes() จาก naivebayes package

    naive_bayes() ต้องการ input 2 อย่าง:

    1. Formula: ตัวแปรต้นและตัวแปรตามที่ต้องการใช้สร้าง model โดยในกรณีนี้ คือ ทำนาย Species ด้วยข้อมูลที่เหลือทั้งหมด (.)
    2. Data: dataset ที่จะใช้สร้าง model ซึ่งในกรณีนี้ คือ train_set
    # Create a NB model
    nb <- naive_bayes(Species ~ .,
                      data = train_set)
    

    เมื่อเราได้ NB classifier มาแล้ว เรามาลองใช้ model ทำนายประเภทดอกไม้กัน:

    # Predict the outcomes
    pred <- predict(nb,
                    newdata = test_set[, 1:4],
                    type = "class")
    print(pred)
    

    ผลลัพธ์:

     [1] setosa     setosa     setosa     setosa     setosa    
     [6] setosa     setosa     setosa     setosa     setosa    
    [11] setosa     setosa     setosa     setosa     setosa    
    [16] virginica  versicolor versicolor versicolor versicolor
    [21] virginica  versicolor versicolor versicolor versicolor
    [26] versicolor virginica  versicolor versicolor versicolor
    [31] versicolor versicolor versicolor versicolor virginica 
    [36] virginica  virginica  virginica  virginica  virginica 
    [41] virginica  virginica  virginica  virginica  virginica 
    Levels: setosa versicolor virginica
    

    .

    5️⃣ Step 5. Evaluate the Model

    ในขั้นสุดท้าย เราจะประเมินประสิทธิภาพของ model ด้วยการคำนวณ accuracy หรือ สัดส่วนของคำตอบที่ model ตอบถูก:

    Accuracy = Correct predictions / Total predictions

    เราสามารถหาค่า accuracy ได้โดยเริ่มสร้าง confusion matrix ก่อน:

    # Create a confusion matrix
    cm <- table(Predicted = pred, 
                Actual = test_set$Species)
    print(cm)
    

    ผลลัพธ์:

                Actual
    Predicted    setosa versicolor virginica
      setosa         15          0         0
      versicolor      0         16         0
      virginica       0          3        11
    

    จากนั้น นำจำนวนคำตอบที่ถูกต้องและจำนวนคำตอบทั้งหมดมาหาค่า accuracy:

    # Calculate the accuracy
    accuracy <- sum(diag(cm)) / sum(cm)
    cat("Accuracy:", round(accuracy, 2))
    

    ผลลัพธ์:

    Accuracy: 0.93
    

    จะเห็นได้ว่า NB classifier ที่เป็น model ไร้เดียงสาของเรา มีความแม่นยำในการทำนายสูงถึง 93%


    😺 GitHub

    ดู code ทั้งหมดในบทความนี้ได้ที่ GitHub


    📃 References


    ✅ R Book for Psychologists: หนังสือภาษา R สำหรับนักจิตวิทยา

    📕 ขอฝากหนังสือเล่มแรกในชีวิตด้วยนะครับ 😆

    🙋 ใครที่กำลังเรียนจิตวิทยาหรือทำงานสายจิตวิทยา และเบื่อที่ต้องใช้ software ราคาแพงอย่าง SPSS และ Excel เพื่อทำข้อมูล

    💪 ผมขอแนะนำ R Book for Psychologists หนังสือสอนใช้ภาษา R เพื่อการวิเคราะห์ข้อมูลทางจิตวิทยา ที่เขียนมาเพื่อนักจิตวิทยาที่ไม่เคยมีประสบการณ์เขียน code มาก่อน

    ในหนังสือ เราจะปูพื้นฐานภาษา R และพาไปดูวิธีวิเคราะห์สถิติที่ใช้บ่อยกัน เช่น:

    • Correlation
    • t-tests
    • ANOVA
    • Reliability
    • Factor analysis

    🚀 เมื่ออ่านและทำตามตัวอย่างใน R Book for Psychologists ทุกคนจะไม่ต้องพึง SPSS และ Excel ในการทำงานอีกต่อไป และสามารถวิเคราะห์ข้อมูลด้วยตัวเองได้ด้วยความมั่นใจ

    แล้วทุกคนจะแปลกใจว่า ทำไมภาษา R ง่ายขนาดนี้ 🙂‍↕️

    👉 สนใจดูรายละเอียดหนังสือได้ที่ meb:

  • วิธีสร้าง KNN model ใน 5 ขั้นตอนด้วย class package ในภาษา R – ตัวอย่างการทำนายประเภทดอกไม้ใน iris dataset

    วิธีสร้าง KNN model ใน 5 ขั้นตอนด้วย class package ในภาษา R – ตัวอย่างการทำนายประเภทดอกไม้ใน iris dataset

    ในบทความนี้ เราจะมาทำความรู้กันกับ KNN model และวิธีสร้าง KNN model ด้วย class package ในภาษา R กัน


    1. 💻 KNN in R With class Package
    2. 1️⃣ Step 1. Get class Package
    3. 2️⃣ Step 2. Get the Dataset
    4. 3️⃣ Step 3. Prepare Data
      1. 📉 Normalise Data
      2. 🪓 Split Data
      3. 🏷️ Separate Features From Label
    5. 4️⃣ Step 4. Train a KNN Model
    6. 5️⃣ Step 5. Evaluate the Model
    7. 🍩 Bonus: Fine-Tuning
    8. 😺 GitHub
    9. 📃 References
    10. ✅ R Book for Psychologists: หนังสือภาษา R สำหรับนักจิตวิทยา

    KNN หรือ K-Nearest Neighbors เป็น machine learning algorithm ประเภท supervised learning ซึ่งใช้ได้กับงานประเภท classification (จัดกลุ่ม) และ regression (ทำนายแนวโน้ม)

    การทำงานของ KNN ตรงไปตรงมา คือ ทำนายข้อมูลโดยการดูจากข้อมูลใกล้เคียง จำนวน k ข้อมูล (เราสามารถกำหนดค่า k เองได้)

    ยกตัวอย่างเช่น เราต้องการใช้ KNN ทำนายราคาหุ้น KNN จะดูราคาหุ้นที่อยู่ใกล้เคียงกับหุ้นที่เราต้องการทำนายราคา เช่น 5 หุ้นใกล้เคียง โดย:

    • 2/5 หุ้น = ราคาลง
    • 3/5 หุ้น = ราคาขึ้น

    KNN จะทำนายว่า หุ้นในใจของเรา จะราคาขึ้น เพราะหุ้นใกล้เคียงส่วนใหญ่ปรับราคาขึ้น เป็นต้น


    💻 KNN in R With class Package

    เราสามารถสร้าง KNN model ในภาษา R ด้วย class package โดยมี 5 ขั้นตอนดังนี้:

    1. Get class package
    2. Load the dataset
    3. Prepare the data
    4. Train a KNN model
    5. Evaluate the model

    เราไปดูตัวอย่างการสร้าง KNN model เพื่อทำนายประเภทดอกไม้ ด้วย iris dataset กัน


    1️⃣ Step 1. Get class Package

    ในขั้นแรก ให้เราติดตั้งและเรียกใช้งาน class package

    ติดตั้ง (ทำครั้งเดียว):

    # Install
    install.packages("class")
    

    เรียกใช้งาน (ทำทุกครั้งที่เริ่ม session ใหม่):

    # Load
    library(class)
    

    2️⃣ Step 2. Get the Dataset

    ในขั้นที่สอง ให้เราโหลด dataset ที่จะใช้งาน

    โดยในบทความนี้ เราจะใช้ iris ที่มีข้อมูลดอกไม้ 3 ชนิด ได้แก่:

    • Iris setosa
    • Iris virginica
    • Iris versicolor

    นอกจากประเภทดอกไม้ (species) iris dataset ยังประกอบด้วยความกว้าง (width) และความยาว (length) ของกลีบดอกชั้นนอก (sepal) และชั้นใน (petal)

    เนื่องจาก iris เป็น built-in dataset ใน ภาษา R เราสามารถโหลดข้อมูลด้วยคำสั่ง data() ได้:

    # Load
    data(iris)
    

    เมื่อโหลดแล้ว เราสามารถดูตัวอย่าง dataset ได้ด้วย head():

    # Preview
    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
    

    3️⃣ Step 3. Prepare Data

    ในขั้นที่สาม เราจะเตรียมข้อมูล เพื่อใช้สร้าง KNN model

    โดยสำหรับ iris dataset เราจะทำ 3 อย่าง คือ:

    1. Normalise data
    2. Split data
    3. Separate features from the label

    .

    📉 Normalise Data

    เนื่องจาก KNN model อ้างอิงระยะห่างระหว่างข้อมูลในการทำนายผลลัพธ์ ข้อมูลที่มีช่วงกว้าง (เช่น 0-100) จะมีน้ำหนักกว่าข้อมูลที่มีช่วงแคบ (เช่น 0-10) และทำให้ model ของเรา bias ได้

    เพื่อป้องกันความเสี่ยงนี้ เราต้อง normalise ข้อมูล หรือการทำให้ข้อมูลมีช่วงมีช่วงข้อมูลเดียวกัน

    การทำ normalisation มีหลายวิธี แต่วิธีที่นิยมใช้กับ KNN คือ min-max normalisation ซึ่งเปลี่ยนช่วงข้อมูลให้อยู่ในช่วง 0-1 ผ่านสูตร:

    (X - Min) / (Max - Min)
    • X คือ ข้อมูล
    • Min คือ ค่าที่น้อยที่สุด
    • Max คือ ค่าที่มากที่สุด

    ในภาษา R เราไม่มี function ที่ใช้ทำ min-max normalisation ได้โดยตรง เราเลยต้องเขียน function ขึ้นมาใช้เอง:

    # Define a function for normalisation
    normalise <- function(x) {
      return((x - min(x)) / (max(x) - min(x)))
    }
    

    จากนั้น ให้เราใช้ function นี้กับ columns ที่เป็นตัวเลข (numeric) เช่น Sepal.Length แล้วเก็บผลลัพธ์ไว้ใน data frame ใหม่ ชื่อ iris_normalises:

    # Apply the function to the dataset
    iris_normalised <- as.data.frame(lapply(iris[, 1:4],
                                            normalise))
    

    เนื่องจากตอนที่เราใช้ function เราตัด column ที่ไม่ใช่ตัวเลขออก ทำให้ iris_normalised ไม่มี column Species

    เราสามารถใส่ Species กลับเข้าไป เพื่อใช้ในขั้นตอนถัดไป แบบนี้:

    # Add species column back into the data frame
    iris_normalised$Species <- iris$Species
    

    สุดท้าย เราเช็กผลลัพธ์ด้วยการเรียกดูสถิติของ iris_normalised:

    # Check the results
    summary(iris_normalised)
    

    ผลลัพธ์:

      Sepal.Length     Sepal.Width    
     Min.   :0.0000   Min.   :0.0000  
     1st Qu.:0.2222   1st Qu.:0.3333  
     Median :0.4167   Median :0.4167  
     Mean   :0.4287   Mean   :0.4406  
     3rd Qu.:0.5833   3rd Qu.:0.5417  
     Max.   :1.0000   Max.   :1.0000  
      Petal.Length     Petal.Width     
     Min.   :0.0000   Min.   :0.00000  
     1st Qu.:0.1017   1st Qu.:0.08333  
     Median :0.5678   Median :0.50000  
     Mean   :0.4675   Mean   :0.45806  
     3rd Qu.:0.6949   3rd Qu.:0.70833  
     Max.   :1.0000   Max.   :1.00000  
           Species  
     setosa    :50  
     versicolor:50  
     virginica :50  
    

    จะเห็นว่า:

    1. Columns ที่เป็นตัวเลข มีช่วงอยู่ระหว่าง 0 และ 1
    2. เรายังมี column Species อยู่

    .

    🪓 Split Data

    ในการสร้าง KNN model เราควรแบ่ง dataset ที่มีเป็น 2 ส่วน คือ:

    1. Training set: ใช้สำหรับสร้าง model
    2. Test set: ใช้สำหรับประเมิน model

    เราเริ่มแบ่งข้อมูลด้วยการสุ่ม row index ที่จะอยู่ใน training set:

    # Set seed for reproducibility
    set.seed(2025)
    
    # Create a training index
    train_index <- sample(1:nrow(iris_normalised),
                          0.7 * nrow(iris_normalised))
    

    จากนั้น subset ข้อมูลด้วย row index ที่สุ่มไว้:

    # Split the data
    train_set <- iris_normalised[train_index, ]
    test_set <- iris_normalised[-train_index, ]
    

    .

    🏷️ Separate Features From Label

    ขั้นตอนสุดท้ายในการเตรียมข้อมูล คือ แยก features หรือ X (columns ที่จะใช้ทำนาย) ออกจาก label หรือ Y (สิ่งที่ต้องการทำนาย):

    # Separate features from label
    
    ## Training set
    train_X <- train_set[, 1:4]
    train_Y <- train_set$Species
    
    ## Test set
    test_X <- test_set[, 1:4]
    test_Y <- test_set$Species
    

    4️⃣ Step 4. Train a KNN Model

    ขั้นที่สี่เป็นขั้นที่เราสร้าง KNN model ขึ้นมา โดยเรียกใช้ knn() จาก class package

    ทั้งนี้ knn() ต้องการ input 3 อย่าง:

    1. train: fatures จาก training set
    2. test: feature จาก test set
    3. cl: label จาก training set
    4. k: จำนวนข้อมูลใกล้เคียงที่จะใช้ทำนายผลลัพธ์
    # Train a KNN model
    pred <- knn(train = train_X,
                test = test_X,
                cl = train_Y,
                k = 5)
    

    ในตัวอย่าง เรากำหนด k = 5 เพื่อทำนายผลลัพธ์โดยดูจากข้อมูลที่ใกล้เคียง 5 อันดับแรก


    5️⃣ Step 5. Evaluate the Model

    หลังจากได้ model แล้ว เราประเมินประสิทธิภาพของ model ในการทำนายผลลัพธ์ ซึ่งเราทำได้ง่าย ๆ โดยคำนวณ accuracy หรือสัดส่วนของข้อมูลที่ model ตอบถูกต่อจำนวนข้อมูลทั้งหมด:

    Accuracy = Correct predictions / Total predictions

    ในภาษา R ให้เราสร้าง confusion matrix หรือ matrix แสดงจำนวนคำตอบที่ถูกและผิด ด้วย table() function:

    # Create a confusion matrix
    cm <- table(Predicted = predictions,
                Actual = test_Y)
    
    # Print the matrix
    print(cm)
    

    ผลลัพธ์:

                Actual
    Predicted    setosa versicolor virginica
      setosa         15          0         0
      versicolor      0         17         0
      virginica       0          2        11
    

    Note: จะเห็นได้ว่า model เราตอบถูกเป็นส่วนใหญ่ (ราว 90%)

    จากนั้น คำนวณ accuracy ด้วย sum() และ diag():

    # Calculate accuracy
    acc <- sum(diag(cm)) / sum(cm)
    
    # Print accuracy
    cat("Accuracy:", round(acc, 2))
    

    ผลลัพธ์:

    Accuracy: 0.96
    

    จากผลลัพธ์ เราจะเห็นว่า model มีความแม่นยำสูงถึง 96%


    🍩 Bonus: Fine-Tuning

    ในบางครั้ง ค่า k ที่เราตั้งไว้ อาจไม่ได้ทำให้เราได้ KNN model ที่ดีที่สุด

    แทนที่เราจะแทนค่า k ใหม่ไปเรื่อย ๆ เราสามารถใช้ for loop เพื่อหาค่า k ที่ทำให้เราได้ model ที่ดีที่สุดได้

    ให้เราเริ่มจากสร้าง vector ที่มีค่า k ที่ต้องการ:

    # Create a set of k values
    k_values <- 1:20
    

    และ vector สำหรับเก็บค่า accuracy ของค่า k แต่ละตัว:

    # Createa a vector for accuracy results
    accuracy_results <- numeric(length(k_values))
    

    แล้วใช้ for loop เพื่อหาค่า accuracy ของค่า k:

    # For-loop through the k values
    for (i in seq_along(k_values)) {
      
      ## Set the k value
      k <- k_values[i]
      
      ## Create a KNN model
      predictions <- knn(train = train_X,
                         test = test_X,
                         cl = train_Y,
                         k = k)
      
      ## Create a confusion matrix
      cm <- table(Predicted = predictions,
                  Actual = test_Y)
      
      ## Calculate accuracy
      accuracy_results[i] <- sum(diag(cm)) / sum(cm)
    }
    
    # Find the best k and the corresponding accuracy
    best_k <- k_values[which.max(accuracy_results)]
    best_accuracy <- max(accuracy_results)
    
    # Print best k and accuracy
    cat(paste("Best k:", best_k),
        paste("Accuracy:", round(best_accuracy, 2)),
        sep = "\n")
    

    ผลลัพธ์:

    Best k: 12
    Accuracy: 0.98
    

    แสดงว่า ค่า k ที่ดีที่สุด คือ 12 โดยมี accuracy เท่ากับ 98%

    นอกจากนี้ เรายังสามารถสร้างกราฟ เพื่อช่วยทำความเข้าใจผลของค่า k ต่อ accuracy:

    # Plot the results
    plot(k_values,
         accuracy_results,
         type = "b",
         pch = 19,
         col = "blue",
         xlab = "Number of Neighbors (k)",
         ylab = "Accuracy",
         main = "KNN Model Accuracy for Different k Values")
    grid()
    

    ผลลัพธ์:

    จะเห็นได้ว่า k = 12 ให้ accuracy ที่ดีที่สุด และ k = 20 ให้ accuracy ต่ำที่สุด ส่วนค่า k อื่น ๆ ให้ accuracy ในช่วง 93 ถึง 96%


    😺 GitHub

    ดู code ทั้งหมดในบทความนี้ได้ที่ GitHub


    📃 References


    ✅ R Book for Psychologists: หนังสือภาษา R สำหรับนักจิตวิทยา

    📕 ขอฝากหนังสือเล่มแรกในชีวิตด้วยนะครับ 😆

    🙋 ใครที่กำลังเรียนจิตวิทยาหรือทำงานสายจิตวิทยา และเบื่อที่ต้องใช้ software ราคาแพงอย่าง SPSS และ Excel เพื่อทำข้อมูล

    💪 ผมขอแนะนำ R Book for Psychologists หนังสือสอนใช้ภาษา R เพื่อการวิเคราะห์ข้อมูลทางจิตวิทยา ที่เขียนมาเพื่อนักจิตวิทยาที่ไม่เคยมีประสบการณ์เขียน code มาก่อน

    ในหนังสือ เราจะปูพื้นฐานภาษา R และพาไปดูวิธีวิเคราะห์สถิติที่ใช้บ่อยกัน เช่น:

    • Correlation
    • t-tests
    • ANOVA
    • Reliability
    • Factor analysis

    🚀 เมื่ออ่านและทำตามตัวอย่างใน R Book for Psychologists ทุกคนจะไม่ต้องพึง SPSS และ Excel ในการทำงานอีกต่อไป และสามารถวิเคราะห์ข้อมูลด้วยตัวเองได้ด้วยความมั่นใจ

    แล้วทุกคนจะแปลกใจว่า ทำไมภาษา R ง่ายขนาดนี้ 🙂‍↕️

    👉 สนใจดูรายละเอียดหนังสือได้ที่ meb:

  • pandas fundamentals: 5 กลุ่ม pd functions ที่ควรรู้ในการทำงานกับข้อมูล พร้อมตัวอย่างจาก Spotify dataset

    pandas fundamentals: 5 กลุ่ม pd functions ที่ควรรู้ในการทำงานกับข้อมูล พร้อมตัวอย่างจาก Spotify dataset

    pandas เป็น library ใน Python ที่นิยมใช้ทำงานกับ data เพราะ:

    • pandas สามารถเก็บข้อมูลในรูปแบบ table หรือ data frame ได้
    • มี functions/methods สำหรับทำงานกับ data frame

    .

    ในบทความนี้ เราจะมาดูวิธีใช้ pandas ในการทำงานกับ data เบื้องต้นกัน

    โดย functions ของ pandas ที่เราจะดู แบ่งเป็น 5 กลุ่ม ได้แก่:

    No.GroupDescription
    1Exploringสำรวจข้อมูลเบื้องต้น
    2Selecting and filteringเลือกและกรองข้อมูล
    3Sortingจัดลำดับข้อมูล
    4Slicingตัดแบ่งข้อมูล
    5Aggregatingสรุปข้อมูล

    ถ้าพร้อมแล้ว ไปเริ่มกันเลย


    1. 🎧 Dataset: Spotify Tracks
    2. ▶️ Press Play
      1. 1️⃣ Install
      2. 2️⃣ Import
      3. 3️⃣ Read
    3. 🎶 Playlist #1 – Exploring
      1. 1️⃣ .head()
      2. 2️⃣ .info()
      3. 3️⃣ .describe()
      4. 4️⃣ .shape
    4. 🎶 Playlist #2 – Selecting & Filtering
      1. 1️⃣ df[condition]
      2. 2️⃣ .query()
    5. 🎶 Playlist #3 – Sorting
      1. 1️⃣ .sort_values()
    6. 🎶 Playlist #4 – Slicing
      1. 1️⃣ df[column_name]
      2. 2️⃣ .loc[]
      3. 3️⃣ .iloc[]
      4. 4️⃣ .filter()
    7. 🎶 Playlist #5 – Aggregating
      1. 1️⃣ Aggregation Functions
      2. 2️⃣ .agg()
      3. 3️⃣ .groupby()
    8. ⏭️ Next Song
      1. 💻 Example Code
      2. 📚 Further Reading

    🎧 Dataset: Spotify Tracks

    ในบทความนี้ dataset ที่จะใช้เป็นตัวอย่าง คือ Spotify Tracks Dataset จาก Kaggle

    Spotify Tracks Dataset เป็นชุดข้อมูลเพลงใน Spotify ทั้งหมด 125 แนวเพลง และประกอบด้วย 20 columns เช่น:

    • track_name: ชื่อเพลง
    • artists: ชื่อศิลปิน
    • popularity: คะแนนความนิยม
    • energy: ความดัง + ความเร็ว
    • liveness: เป็นเพลง live หรืออัดใน studio

    ▶️ Press Play

    ก่อนไปดูการใช้งาน pandas เรามาดูวิธีการเตรียม pandas และ dataset กันก่อน:

    1. Install
    2. Import
    3. Read

    .

    1️⃣ Install

    ในการใช้งาน pandas ให้เราเริ่มจากติดตั้ง pandas ก่อน:

    # Install pandas
    !pip install pandas
    

    Note: ถ้าใครติดตั้งแล้ว สามารถไปที่ step ต่อไปได้เลย

    .

    2️⃣ Import

    หลังติดตั้ง pandas แล้ว ให้เรียกใช้งานผ่านคำสั่ง import:

    # Load pandas
    import pandas as pd
    

    Note:

    • pandas มักใช้ตัวย่อ pd เพื่อง่ายต่อการทำงาน
    • ทุกครั้งที่เปิด session ใหม่ จะต้อง run บรรทัดนี้ก่อนทำงานเสมอ

    .

    3️⃣ Read

    เมื่อติดตั้งและเรียกใช้งาน pandas แล้ว ให้โหลด dataset ที่ต้องการใช้งานซึ่งในกรณีนี้ คือ Spotify Tracks Dataset ซึ่งเป็นไฟล์ CSV โดยเราจะโหลดผ่าน read_csv() ของ pandas:

    # Load the dataset
    spotify = pd.read_csv("spotify_tracks_dataset.csv", index_col=0)
    

    Note: ในกรณีของ Spotify Tracks Dataset เราต้องใช้ index_col=0 เพื่อบอก pandas ว่า เราจะไม่ต้องการสร้าง column ที่เป็น running number

    .

    หลังจากทำครบทั้ง 3 ขั้นตอนนี้แล้ว เราสามารถเริ่มทำงานกับข้อมูลด้วย pandas กันได้เลย


    🎶 Playlist #1 – Exploring

    เริ่มแรก เรามาดูการใช้งาน pandas เพื่อสำรวจข้อมูลเบื้องต้นกัน

    Functions ในกลุ่มนี้ประกอบด้วย 4 functions/methods:

    1. .head()
    2. .info()
    3. .describe()
    4. .shape

    .

    1️⃣ .head()

    Use case:

    เรียกดู 5 rows แรกของ dataset

    ตัวอย่าง:

    # View the first 5 rows
    spotify.head()
    

    ผลลัพธ์:

    Note:

    • ถ้าต้องการดูมากกว่า 5 rows ให้ใส่จำนวน rows ที่ต้องการ เช่น spotify.head(10) จะเรียกดู 10 rows แรก

    .

    2️⃣ .info()

    Use case:

    ดูข้อมูลภาพรวมของ dataset

    ตัวอย่าง:

    # Get overview of the dataset
    spotify.info()
    

    ผลลัพธ์:

    .

    3️⃣ .describe()

    Use case:

    เรียกดู summary stats ของ datasets ซึ่งได้แก่:

    • Count
    • Mean
    • Standard deviation (std)
    • Min
    • Quartiles
      • 25
      • 50
      • 75
    • Max

    ตัวอย่าง:

    # Get summary stats
    spotify.describe()
    

    ผลลัพธ์:

    Note:

    โดย default, .describe() จะสรุปข้อมูลเฉพาะ column ที่เป็น numerical variable เท่านั้น

    ถ้าเราต้องการ summary stats ของ categorical variable เราสามารถใช้ argument include="all" ได้:

    # Get summary stats for all variable types
    spotify.describe(include="all")
    

    ผลลัพธ์:

    จะเห็นได้ว่า ตอนนี้เราจะได้ summary stats ของทั้ง numerical (เช่น popularity) และ categorical variables (เช่น artists)

    .

    4️⃣ .shape

    Use case:

    ดูจำนวน rows และ columns ของ dataset

    ตัวอย่าง:

    # See the dimensions of the dataset
    spotify.shape
    
    

    ผลลัพธ์:

    • 114000 คือ จำนวน rows
    • 20 คือ จำนวน columns

    🎶 Playlist #2 – Selecting & Filtering

    ในกลุ่มการใช้งานที่ 2 เรามาดูวิธีการเลือกและกรองข้อมูลกัน:

    1. df[condition]
    2. .query()

    .

    1️⃣ df[condition]

    Use case:

    df[condition] เป็น syntax เพื่อกรองข้อมูล

    ตัวอย่าง:

    เราต้องการดูข้อมูลเพลงที่มีคะแนนความนิยม (popularity) สูงกว่า 80:

    # Select records where popularity is greater than 80
    spotify[spotify["popularity"] > 80]
    

    ผลลัพธ์:

    Note:

    ในการกรอง เราสามารถใช้ comparison operators เหล่านี้ช่วยได้:

    Comparison OperatorMeaning
    ==เท่ากับ
    !=ไม่เท่ากับ
    >มากกว่า
    >=มากกว่า/เท่ากับ
    <น้อยกว่า
    <=น้อยกว่า/เท่ากับ

    นอกจากนี้ เราสามารถใช้ Boolean operators เพื่อเพิ่ม conditions ในการกรองข้อมูลได้:

    Boolean OperatorMeaning
    &and
    ``
    !not

    เช่น ดูข้อมูลเพลงที่มีคะแนนความนิยม (popularity) สูงกว่า 80 จากวง The Neighbourhood (ดูจาก artists):

    # Select records where popularity is greater than 80 from The Neighbourhood
    spotify[(spotify["popularity"] > 80) & (spotify["artists"] == "The Neighbourhood")]
    

    ผลลัพธ์:

    .

    2️⃣ .query()

    Use case:

    .query() ทำหน้าที่คล้ายกับ df[condition] นั่นคือ กรองข้อมูล

    แต่ .query() มีข้อดีอยู่ 2 อย่าง:

    1. ใช้งานง่าย
    2. เหมาะกับการกรองข้อมูล ด้วย conditions ที่ซับซ้อน

    การเขียน input ของ .query() เราจะใช้ใน syntax ของ SQL

    ตัวอย่าง:

    จากตัวอย่างก่อนหน้านี้ที่เราต้องการดูข้อมูลเพลงที่:

    • มีคะแนนความนิยม (popularity) สูงกว่า 80
    • จากวง The Neighbourhood (ดูจาก artists)

    เราสามารถเขียน .query() ได้ดังนี้:

    # Filter with .query()
    spotify.query("popularity > 80 and artists == 'The Neighbourhood'")
    

    ผลลัพธ์:

    Note:

    ถ้าเราเทียบระหว่าง df[condition] และ .query() :

    df[condition].query()
    spotify[(spotify["popularity"] > 80) & (spotify["artists"] == "The Neighbourhood")]spotify.query("popularity > 80 and artists == 'The Neighbourhood'")

    จะเห็นว่า .query():

    • สั้นกว่า
    • ทำความเข้าใจได้ง่ายกว่า

    🎶 Playlist #3 – Sorting

    หลังจากกรองข้อมูล บางครั้งเราอยากจะจัดลำดับข้อมูล เพื่อช่วยในการทำความเข้าใจข้อมูล:

    • .sort_values()

    .

    1️⃣ .sort_values()

    Use case:

    จัดเรียงข้อมูล โดย:

    • default จะเรียงจากน้อยไปมาก (A-Z)
    • ถ้าต้องการเรียงจากมากไปน้อย (Z-A) ให้ใช้ ascending=False

    ตัวอย่าง:

    ต้องการเรียงเพลงตามคะแนนความนิยม (popularity) จากสูงไปต่ำ เพื่อหาเพลงฮิต:

    # Sort tracks by popularity in descending order
    spotify.sort_values(by="popularity", ascending=False)
    

    ผลลัพธ์:


    🎶 Playlist #4 – Slicing

    ในกลุ่มนี้ เราจะมาดู 4 วิธี เพื่อดึง rows และ/หรือ columns ออกจาก dataset กัน:

    1. df[column]
    2. .loc[]
    3. .iloc[]
    4. .filter()

    .

    1️⃣ df[column_name]

    Use case:

    df[column_name] เป็น syntax เพื่อเลือกข้อมูลจาก column ที่ต้องการ โดย:

    • df หมายถึง ชื่อ dataset
    • column_name หมายถึง ชื่อ column ที่เราเลือก

    ตัวอย่าง:

    เลือกดูชื่อเพลง (track_name):

    # Select column track_name
    spotify["track_name"]
    

    ผลลัพธ์:

    Note:

    ถ้าต้องการมากกว่า 1 column เราสามารถใส่ input เป็น list ได้

    เช่น เลือกชื่อเพลง (track_name) และคะแนนความนิยม (popularity):

    # Select columns track_name and popularity
    spotify[["track_name", "popularity"]]
    

    ผลลัพธ์:

    .

    2️⃣ .loc[]

    Use case:

    เลือก rows และ/หรือ columns โดยใช้ ชื่อ rows และ columns (label-based)

    Syntax:

    .loc[] มีหลักการใช้งานดังนี้:

    SyntaxFor
    df.loc[r_lab]เลือก 1 row
    df.loc[rx:ry]เลือกมากกว่า 1 rows
    df.loc[[r_list]]เลือกมากกว่า 1 rows
    df.loc[:, c_lab]เลือก 1 column
    df.loc[:, cx:cy]เลือกมากกว่า 1 column
    df.loc[:, [c_list]]เลือกมากกว่า 1 columns
    • r_lab คือ ชื่อ row
    • rx:ry คือ ช่วง rows ที่ต้องการเลือก
    • [r_list] คือ list ของ rows ที่ต้องการเลือก
    • c_lab คือ ชื่อ column ที่ต้องการเลือก
    • cx:cy คือ ช่วง columns ที่ต้องการเลือก
    • [c_list] คือ list ของ columns ที่ต้องการเลือก

    ตัวอย่าง:

    เลือก 5 rows แรก และแสดงเฉพาะ:

    • ชื่อเพลง (track_name)
    • ชื่อศิลปิน (artists)
    • คะแนนความนิยม (popularity)
    # Select first 5 rows from track_name, artists, popularity
    spotify.loc[0:4, ["track_name", "artists", "popularity"]]
    

    ผลลัพธ์:

    .

    3️⃣ .iloc[]

    Use case:

    เลือก rows และ/หรือ columns โดยใช้ ตำแหน่ง rows และ columns (position-based)

    Syntax:

    .iloc[] มีวิธีการใช้งาน คล้ายกับ .loc[] ดังนี้:

    SyntaxFor
    df.iloc[r_index]เลือก 1 row
    df.iloc[rx:ry]เลือกมากกว่า 1 rows
    df.iloc[[r_list]]เลือกมากกว่า 1 rows
    df.iloc[:, c_index]เลือก 1 column
    df.iloc[:, cx:cy]เลือกมากกว่า 1 column
    df.iloc[:, [c_list]]เลือกมากกว่า 1 columns
    • r_index คือ ตำแหน่ง row
    • rx:ry คือ ช่วง rows ที่ต้องการเลือก
    • [r_list] คือ list ของ rows ที่ต้องการเลือก
    • c_index คือ ตำแหน่ง column ที่ต้องการเลือก
    • cx:cy คือ ช่วง columns ที่ต้องการเลือก
    • [c_list] คือ list ของ columns ที่ต้องการเลือก

    ความแตกต่างระหว่าง .loc[] และ .iloc[] คือ สิ่งที่ใช้ในการเลือก s และ columns:

    • .loc[] ใช้ ชื่อ (label)
    • .iloc[] ใช้ ตำแหน่ง (position)

    ตัวอย่าง:

    เลือก 5 rows แรก และแสดงเฉพาะ:

    • ชื่อเพลง (track_name)
    • ชื่อศิลปิน (artist_name)
    • คะแนนความนิยม (popularity)
    # Select first 5 rows from track_name, artists, popularity
    spotify.iloc[0:5, [0, 1, 5]]
    

    ผลลัพธ์:

    .

    4️⃣ .filter()

    Use case:

    .filter() ทำหน้าที่คล้ายกับ df[condition] แต่ทรงพลังกว่า เพราะเลือกกรองข้อมูลได้ทั้ง rows และ columns

    Syntax:

    df.filter(condition, axis)
    
    • df คือ ชื่อ dataset
    • condition คือ เงื่อนไขในการเลือกข้อมูล ซึ่งเรามี 3 parametres ให้เลือกใช้:
      • items กรองตาม labels ของ rows หรือ columns
      • like กรองตาม คำค้นหา
      • reg กรองตาม regular expression
    • axis ระบุว่า ต้องการเลือก rows (0) หรือ columns (1)

    ตัวอย่าง:

    เลือก rows ที่เลข 123:

    # Select rows with "123"
    spotify.filter(like="123", axis=0)
    

    ผลลัพธ์:

    หรือ เลือกข้อมูลจาก columns:

    • ชื่อเพลง (track_name)
    • ชื่อศิลปิน (artist_name)
    • คะแนนความนิยม (popularity)
    # Select first 5 rows from track_name, artists, popularity
    spotify.filter(items=["track_name", "artists", "popularity"])
    

    ผลลัพธ์:


    🎶 Playlist #5 – Aggregating

    สุดท้าย เรามาดูวิธีการสรุปข้อมูลกัน:

    1. Aggregation functions
    2. .agg()
    3. .groupby()

    .

    1️⃣ Aggregation Functions

    ในกรณีที่เราต้องการ คำนวณค่าทางสถิติ pandas มี functions ให้เลือกใช้งานมากมาย เช่น:

    FunctionMeaning
    .sum()หาผลรวม
    .mean()หาค่าเฉลี่ย
    .median()หาค่ากลาง
    .mode()หาค่าที่ซ้ำมากที่สุด
    .min()หาค่าน้อยที่สุด
    .max()หาค่ามากที่สุด
    .std()หา standard deviation (SD)
    .cumsum()หาผลรวมสะสม
    .value_counts()นับจำนวนข้อมูล
    .nunique()นับจำนวนข้อมูลที่ไม่ซ้ำ

    ตัวอย่าง:

    ต้องการหาค่าเฉลี่ยของคะแนนความนิยม (popularity):

    # Calculate the mean of popularity
    spotify["popularity"].mean()
    

    ผลลัพธ์:

    หรือหา SD ของคะแนนความนิยม (popularity):

    # Calculate the SD of popularity
    spotify["popularity"].std()
    
    

    ผลลัพธ์:

    .

    2️⃣ .agg()

    Use case:

    ในบางครั้ง เราต้องการคำนวณหลายค่าทางสถิติพร้อมกัน เช่น ตัวอย่างก่อนหน้านี้ที่เราต้องการหา mean และ SD

    แทนที่เราจะเขียน code เพื่อแสดงผลแยกกัน เช่น:

    # Calculate mean
    spotify["popularity"].mean()
    
    # Calculate SD
    spotify["popularity"].std()
    

    เราสามารถใช้ agg() เพื่อช่วยลดเวลาได้

    ตัวอย่าง:

    หาค่าเฉลี่ยและ SD ของคะแนนความนิยม (popularity):

    # Calculate mean and SD of popularity
    spotify["popularity"].agg(["mean", "std"])
    

    ผลลัพธ์:

    Note:

    เราสามารถใช้ .agg() เพื่อคำนวณค่าทางสถิติกับหลาย column พร้อมกันได้ เช่น หาค่า:

    • mean
    • std

    ให้กับ:

    • คะแนนความนิยม
    • ความยาวของเพลง
    # Calculate mean and SD for popularity and duration_ms
    spotify[["popularity", "duration_ms"]].agg({
    		"popularity": ["mean", "std"],
    		"duration_ms": ["mean", "std"]
    		})
    

    ผลลัพธ์:

    .

    3️⃣ .groupby()

    Use case:

    บางครั้ง เราต้องการคำนวณค่าทางสถิติตามกลุ่มข้อมูล

    เราสามารถใช้ .groupby() เพื่อจับกลุ่มข้อมูล ก่อนจะคำนวณค่าทางสถิติได้

    ตัวอย่าง:

    ต้องการหา ค่าเฉลี่ยและ SD ของคะแนนความนิยม (popularity) ของศิลปินแต่ละคน:

    # Group by artists and calculate mean of popularity 
    spotify.groupby("artists")["popularity"].agg(["mean", "std"])
    

    ผลลัพธ์:


    ⏭️ Next Song

    .

    💻 Example Code

    สำหรับคนที่ลองรัน code ด้วยตัวเอง สามารถโหลด code ตัวอย่างได้ที่ GitHub

    .

    📚 Further Reading

    สำหรับคนที่สนใจเรียนรู้เพิ่มเติมเกี่ยวกับ pandas สามารถศึกษาต่อได้ตาม links ด้านล่าง:

  • Intro to Python: ทำความรู้จักกับภาษา Python และวิธีใช้งานเบื้องต้น สำหรับผู้เริ่มต้น พร้อมตัวอย่าง

    Intro to Python: ทำความรู้จักกับภาษา Python และวิธีใช้งานเบื้องต้น สำหรับผู้เริ่มต้น พร้อมตัวอย่าง

    ในบทความนี้ เราจะไปทำความรู้จักกับภาษา Python กัน:

    • Python คืออะไร?
    • วิธีเขียน Python เบื้องต้น
    • Data types ใน Python
    • การทำงานกับ data types ใน Python

    ถ้าพร้อมแล้ว ไปเริ่มกันเลย


    1. 🐍 Python คืออะไร?
    2. 🏁 Getting Started With Python
    3. 👶 Baby Steps
      1. 🔢 (1) Basic Arithmetic
      2. 📦 (2) Variables
    4. 🍞 Data Types
    5. 👉 Integre & Float
      1. 1️⃣ Arithmetic
      2. 2️⃣ Type Casting
    6. 👉 String
      1. 1️⃣ Markers of String
      2. 2️⃣ Type Casting
      3. 3️⃣ Concatenate
      4. 4️⃣ String Methods
    7. 👉 Boolean
      1. 1️⃣ Check for True & False
      2. 2️⃣ Comparison
    8. 👉 List
      1. 1️⃣ Purpose
      2. 2️⃣ Indexing & Slicing
      3. 3️⃣ Check Length
      4. 4️⃣ Add to List
      5. 5️⃣ Update List
      6. 6️⃣ Delete From List
    9. 👉 Dictionary
      1. 1️⃣ Purpose
      2. 2️⃣ Extract Values
      3. 3️⃣ Get Keys & Values
      4. 4️⃣ Add to Dictionary
      5. 5️⃣ Update Dictionary
      6. 6️⃣ Delete From Dictionary

    🐍 Python คืออะไร?

    Python เป็น high-level programming language ที่พัฒนาโดย programmer ชาวดัชต์ Guido van Rossum ในช่วง ปี ค.ศ. 1980-1990 เพื่อทำให้การเขียน programme เป็นเรื่องง่าย

    van Rossum เรียกภาษาที่คิดขึ้นมาว่า Python ตามชื่อกลุ่มนักแสดงตลกจากประเทศอังกฤษ Monty Python หรือ The Pythons เพราะคำว่า Python สั้น จำง่าย และดูลึกลับ (ไม่มีความเกี่ยวข้องกับชนิดงู Python แต่อย่างใด)

    .

    เนื่องจาก Python เป็น high-level language หรือมีความใกล้เคียงกับภาษามนุษย์ (มากกว่าภาษาคอมพิวเตอร์) จึงเป็นภาษาที่ใช้งานและทำความเข้าใจง่าย และเป็นที่นิยมของนักพัฒนาทั่วโลก

    ในปัจจุบัน (2025) Python ครองอันดับในฐานะ programming language ที่เป็นที่นิยมมากที่สุด (อ้างอิง TIOBE):

    นอกจากใช้งานง่ายแล้ว Python ยังมีข้อดีอื่น ๆ อีก ได้แก่:

    • เป็น open source
    • มี libraries รองรับการใช้งานที่มากมายและหลากหลาย
    • แก้ bug ได้ง่าย
    • ใช้ได้กับหลายระบบปฏิบัติการ ทั้ง Windows, macOS, และ Linux

    .

    การใช้งาน Python มีตั้งแต่:

    • เขียน programme
    • เขียน web application
    • ทำ web scraping
    • ทำ data analysis
    • พัฒนา AI และ machine learning

    🏁 Getting Started With Python

    สำหรับการเริ่มใช้งาน Python เราสามารถติดตั้ง Python บนคอมพิวเตอร์ของเรา โดยดาวน์โหลด Python จาก https://www.python.org/downloads/:

    หรือใช้งานผ่าน online services ฟรี เช่น:

    Note: บทความนี้มีตัวอย่าง code ใน Google Colab สามารถกดเข้าไปดูได้


    👶 Baby Steps

    หลังจากเตรียมตัวให้พร้อมแล้ว เรามาดูวิธีเขียน Python เบื้องต้นกัน

    .

    🔢 (1) Basic Arithmetic

    สำหรับก้าวแรกในการเขียน Python เรามาเริ่มจากการคิดเลขง่าย ๆ กัน เช่น:

    บวก:

    # Addition
    3 + 4
    

    ลบ:

    # Subtraction
    10 - 7
    

    คูณ:

    # Multiplication
    2 * 2
    

    หาร:

    # Division
    9 / 3
    

    เราจะเห็นได้ว่า Python สามารถคิดเลขให้ได้อย่างรวดเร็ว:

    .

    📦 (2) Variables

    ในการทำงานกับ Python เราสามารถสร้าง variable เพื่อช่วยเก็บข้อมูลได้ (แทนที่การเขียน code เรียกใช้ข้อมูลเองทุกครั้ง)

    เช่น เราสามารถเก็บเงินค่าขนม:

    # Create allowance variable
    allowance = 100
    

    และค่าใช้จ่าย:

    # Create expense variable
    expense = 40
    

    แล้วเรียกใช้งานทั้งสองค่า เช่น ดูว่าเดือนนี้เราเหลือเงินเท่าไร:

    # Calculate remaining balance
    allowance - expense
    

    ผลลัพธ์:

    60

    .

    เราสามารถ update ค่าใน variable ได้ เช่น update expense จาก 40 เป็น 70:

    # Update expense
    expense = 70
    

    ถ้าเราคำนวณเงินคงเหลือ:

    # Calculate remaining balance
    allowance - expense
    

    เราจะได้ค่าที่ต่างไปจากเดิม:

    30

    .

    สุดท้าย เราสามารถเก็บผลลัพธ์ที่ได้ ไว้ใน variable ตัวใหม่ เพื่อเรียกใช้งานในภายหลังได้:

    # Store remaining balance in a variable
    remain = allowance - expense
    
    # Check remaining balance
    remain
    

    ผลลัพธ์:

    30

    Note: เราสามารถลบ variable ได้ด้วย del() เช่น del(remain) จะลบ remain จาก Python


    🍞 Data Types

    ตอนนี้ เรารู้วิธีการทำงานกับ Python เบื้องต้นแล้ว

    เรามาทำความรู้จักกับ data type หรือประเภทข้อมูล ซึ่งเป็นตัวกำหนด action ที่เราสามารถกระทำใช้กับข้อมูลได้

    .

    โดย Python มี 6 data types ที่เราใช้บ่อย ได้แก่:

    No.TypeMeaningExample
    1Integreเลขจำนวนเต็ม11
    2Floatเลขทศนิยม3.78104
    3Stringข้อความ"Python"
    4Booleanจริง/ไม่จริงTrue
    5Listเก็บข้อมูลได้หลายประเภท[”John”, 34, True]
    6Dictionaryเก็บ key-value pair{"name": "John", "age": 34, "is_male": True}

    เราไปดูกันว่า แต่ละ data type สามารถทำอะไรได้บ้าง


    👉 Integre & Float

    .

    1️⃣ Arithmetic

    จากที่ได้เห็นก่อนหน้านี้ เราสามารถใช้ integre และ float ในการคำนวณเลขได้ เช่น:

    3 * 7
    

    และ

    7.3915 - 3.2914
    

    .

    2️⃣ Type Casting

    ทั้งนี้ เราสามารถเปลี่ยนข้อมูลบางประเภท ให้เป็น integre และ float ได้ดังนี้

    เปลี่ยนให้เป็น integre:

    # Convert to integre
    int(100.50)
    

    ผลลัพธ์:

    100

    เปลี่ยนให้เป็น float:

    # Convert to float
    float("100")
    

    ผลลัพธ์:

    100.0

    👉 String

    .

    1️⃣ Markers of String

    String ใน Python จะอยู่ใน "" หรือ '' เสมอ เช่น

    # Single-line string
    "John"
    

    หรือ

    # Single-line string
    'John'
    

    ถ้าเรามีข้อความหลายบรรทัด ให้ใช้ """ หรือ ''':

    # Multiple-line string
    """
    My name is Wick.
    John Wick.
    I'm looking for my dog.
    """
    

    หรือ

    # Multiple-line string
    '''
    My name is Wick.
    John Wick.
    I'm looking for my dog.
    '''
    

    .

    2️⃣ Type Casting

    เราสามารถเปลี่ยนข้อมูลต่าง ๆ ให้เป็น string ได้โดยใช้ str() เช่น:

    str(100)
    

    ผลลัพธ์:

    '100'

    สังเกตว่า ตอนนี้ 100 อยู่ใน '' แสดงว่า 100 เป็น string และไม่ใช่ integre แล้ว

    ถ้าเราเอา 100 นี้ไปคิดเลข ระบบจะส่ง error กลับมา เพราะเราไม่สามารถคำนวณเลขด้วย string ได้:

    TypeError                                 Traceback (most recent call last)
    <ipython-input-49-efc4e6e83db0> in <cell line: 0>()
          1 # String cannot be used in arithmetic operation
    ----> 2 str(100) + 100
    
    TypeError: can only concatenate str (not "int") to str

    .

    3️⃣ Concatenate

    แม้ว่าเราจะไม่สามารถบวกลบ string ได้ แต่เราสามารถใช้ + เพื่อรวม string เข้าด้วยกันได้ เช่น:

    "I have " + str(100) + " THB."
    

    ผลลัพธ์:

    'I have 100 THB.'

    .

    4️⃣ String Methods

    นอกจากการรวม string แล้ว เรายังมีอย่างอื่นที่ใช้กับ string ได้อีก เช่น:

    No.MethodExplain
    1upper()เปลี่ยนให้เป็นพิมพ์ใหญ่ทั้งหมด
    2lower()เปลี่ยนให้เป็นพิมพ์เล็กทั้งหมด
    3capitalize()เปลี่ยนอักษรแรกให้เป็นพิมพ์ใหญ่
    4title()เปลี่ยนอักษรแรกของทุกคำให้เป็นพิมพ์ใหญ่
    5strip()ลบ space ออกจากก่อนและหลังคำ
    6replace()แทนที่คำ
    7split()แยกคำ
    8join(iterable)รวมคำ
    9find(substring)หาตำแหน่งของคำ
    10count()นับตัวอักษรที่ต้องการ

    👉 Boolean

    Boolean เป็นเหมือนกับค่า on (True) และ off (False) ของ switch ซึ่งเป็นพื้นฐานของการทำงานของคอมพิวเตอร์

    .

    1️⃣ Check for True & False

    เราสามารถใช้ bool() เพื่อเช็กว่า ข้อมูลเราเป็น True หรือ False เช่น:

    bool("John")
    

    ผลลัพธ์:

    True

    .

    bool() จะส่ง True กลับมาทุกครั้ง ยกเว้นในกรณีเหล่านี้:

    TypeFalseExplain
    Integrebool(0)เลขเป็น 0
    Stringbool("")String ที่เป็นค่าว่าง
    Booleanbool(False)Boolean ที่เป็นค่า False
    Listbool([])List ที่เป็นค่าว่าง
    Dictionarybool({})Dictionary ที่เป็นค่าว่าง

    .

    2️⃣ Comparison

    Python จะส่งค่า boolean กลับมา เมื่อเราทำการเปรียบเทียบ เช่น:

    10 > 5
    

    ผลลัพธ์:

    True

    .

    หรือ

    10 < 5
    

    ผลลัพธ์:

    False

    👉 List

    .

    1️⃣ Purpose

    List ใช้เก็บข้อมูลหลาย ๆ ค่า เช่น:

    • Integre
    • Float
    • String
    • Boolean
    • List
    • Dictionary
    • etc.

    เช่น:

    # List can store data of different types
    a_list = [10, 15.94, "ok", True, ["egg", "milk"], {"store": "Walmart"}]
    

    .

    2️⃣ Indexing & Slicing

    เราสามารถดึงข้อมูลที่อยู่ใน list ได้ โดยการใช้ []:

    SyntaxExplain
    list[x]ดึงข้อมูลในตำแหน่งที่ x
    list[-x]ดึงข้อมูลในตำแหน่งที่ -x (นับจากหลังมาหน้า)
    list[x:y]ดึงข้อมูลในตำแหน่งระหว่าง x และ y-1 (ข้อมูลที่ y จะไม่ถูกดึงมาด้วย)
    list[-x:-y]ดึงข้อมูลในตำแหน่งระหว่าง -x และ -y-1 (ข้อมูลที่ -y จะไม่ถูกดึงมาด้วย)

    .

    เช่น เรามี list ผลไม้:

    # A list
    my_list = ["apple", "banana", "cherry"]
    

    เราสามารถดึง “apple” ออกได้โดยใช้:

    # Get "apple"
    my_list[0]
    

    ผลลัพธ์:

    'apple'

    Note: เราใช้ 0 เพราะใน Python เราจะเริ่มนับตำแหน่งที่ 1 เป็น 0

    .

    หรือเลือก “apple” ถึง “cherry”:

    # Get "apple" to "cherry"
    my_list[0:3]
    

    ผลลัพธ์:

    ['apple', 'banana', 'cherry']

    .

    3️⃣ Check Length

    เราสามารถหาความยาวของ list ได้ด้วย len() เช่น:

    # Check length
    len(my_list)
    

    ผลลัพธ์:

    3

    .

    4️⃣ Add to List

    เราสามารถเพิ่มข้อมูลลงใน list ได้ด้วย 2 วิธี:

    No.WayExample
    1.append()เพิ่มข้อมูล 1 ค่า
    2.extend()เพิ่มข้อมูลจาก list หรือ string

    .

    ตัวอย่าง .append():

    # append()
    my_list.append("orange")
    
    my_list
    

    ผลลัพธ์:

    ['apple', 'banana', 'cherry', 'orange']

    .

    ตัวอย่าง .extend():

    เรามี 2 lists ที่ต้องการรวมกัน:

    # Lists to merge
    list_1 = [1, 2, 3]
    list_2 = [4, 5, 6]
    

    ให้เราใช้ .extend() แบบนี้:

    # extend()
    list_1.extend(list_2)
    

    ผลลัพธ์:

    [1, 2, 3, 4, 5, 6]

    .

    5️⃣ Update List

    เราสามารถ update ข้อมูลใน list ได้ โดยการระบุตำแหน่งข้อมูลที่เราต้องการ update

    เช่น เราต้องการเปลี่ยน “orange” เป็น “kiwi”:

    # Update list
    my_list[3] = "kiwi"
    
    my_list
    

    เมื่อเราเรียกดู my_list เราจะเห็นว่า “orange” เปลี่ยนเป็น “kiwi”:

    ['apple', 'banana', 'cherry', 'kiwi']

    .

    6️⃣ Delete From List

    เราสามารถลบข้อมูลออกจาก list ได้ด้วย .remove()

    เช่น ลบ “kiwi” ออกจาก my_list:

    # Delete from list
    my_list.remove("kiwi")
    
    my_list
    

    ผลลัพธ์:

    ['apple', 'banana', 'cherry']

    👉 Dictionary

    .

    1️⃣ Purpose

    Dictionary มีไว้เก็บ key-value pair เช่น:

    # A dictionary
    cities = {"Thailand": "Bangkok",
              "Japan": "Tokyo",
              "Brazil": "Brasilia"}
    

    .

    2️⃣ Extract Values

    เราสามารถดึงข้อมูลออกจาก dictionary ได้ด้วยการระบุ key ของข้อมูล

    เช่น ต้องการดึง “Tokyo” ให้เราระบุ “Japan”:

    # Extract values from list
    cities["Japan"]
    

    ผลลัพธ์:

    'Tokyo'

    .

    3️⃣ Get Keys & Values

    เราสามารถดู keys และ values ทั้งหมดใน dictionary ได้ด้วย .keys() และ .values() เช่น:

    # Get keys
    cities.keys()
    

    ผลลัพธ์:

    dict_keys(['Thailand', 'Japan', 'Brazil'])

    .

    และ

    # Get values
    cities.values()
    

    ผลลัพธ์:

    dict_values(['Bangkok', 'Tokyo', 'Brasilia'])

    .

    4️⃣ Add to Dictionary

    เราสามารถเพิ่มข้อมูลลงใน dictionary ได้ โดยการใส่ key และ value ใหม่ เช่น:

    # Add to dictionary
    cities["US"] = "New York"
    
    cities
    

    ผลลัพธ์:

    {'Thailand': 'Bangkok',
     'Japan': 'Tokyo',
     'Brazil': 'Brasilia',
     'US': 'New York'}

    .

    5️⃣ Update Dictionary

    เราสามารถ update ข้อมูลใน dictionary ได้ด้วยเรียก key และใส่ value ใหม่ เช่น:

    # Update dictionary
    cities["US"] = "Washington DC"
    
    cities
    

    ผลลัพธ์:

    {'Thailand': 'Bangkok',
     'Japan': 'Tokyo',
     'Brazil': 'Brasilia',
     'US': 'Washington DC'}

    .

    6️⃣ Delete From Dictionary

    เราสามารถลบข้อมูลออกจาก dictionary ได้ด้วย del

    เช่น ลบ “US”: “Washington DC” ออก:

    # Delete from dictionary
    del cities["US"]
    
    cities
    

    ผลลัพธ์:

    {'Thailand': 'Bangkok', 'Japan': 'Tokyo', 'Brazil': 'Brasilia'}
  • แนะนำ dtplyr: package เชื่อม dplyr และ data.table เพื่อการทำ data wrangling กับข้อมูลขนาดใหญ่ที่ง่ายและรวดเร็ว — ตัวอย่างจาก mtcars dataset

    แนะนำ dtplyr: package เชื่อม dplyr และ data.table เพื่อการทำ data wrangling กับข้อมูลขนาดใหญ่ที่ง่ายและรวดเร็ว — ตัวอย่างจาก mtcars dataset

    ในบทความนี้ เรามาความรู้จักกับ package ในภาษา R ที่เรียกว่า dtplyr กัน


    1. 🏎️ dtplyr คืออะไร?
    2. 🧑‍💻 วิธีใช้ dytplyr
      1. 1️⃣ ขั้นที่ 1. Install & Load dtplyr
      2. 2️⃣ ขั้นที่ 2. Create a Lazy data.table
      3. 3️⃣ ขั้นที่ 3. Execute the Syntax
    3. 😺 GitHub
    4. 📃 References
    5. ✅ R Book for Psychologists: หนังสือภาษา R สำหรับนักจิตวิทยา

    🏎️ dtplyr คืออะไร?

    dtplyr เป็น package ที่เชื่อม 2 libraries ยอดนิยมสำหรับ data wrangling เข้าด้วยกัน ได้แก่:

    .

    Library #1. dplyr ซี่งมี verb-based syntax ที่ใช้งานง่าย

    เช่น จาก mtcars dataset เลือกรถเกียร์ manual (am == 1) ที่มี miles/gallon (mpg) ตั้งแต่ 20 ขึ้นไป โดยเรียงจากมากไปน้อย:

    # dplyr
    mtcars |>
      filter(am == 1 & mpg >= 20) |>
      select(model, mpg) |>
      arrange(desc(mpg))
    

    Note: mtcars ถูกปรับให้มี column ชื่อ model (ดู code ในการเพิ่ม column ได้ใน GitHub)

    .

    Library #2. data.table ซึ่งมี syntax ที่เข้าใจยากกว่า:

    # data.table
    mtcars_dt[am == 1 & mpg >= 20, .(model, mpg)][order(-mpg)]
    

    Note: mtcars_dt เป็น dataset ที่ถูกเปลี่ยนจาก data.frame เป็น data.table object เพื่อใช้งานกับ data.table

    แต่มีจุดเด่น คือ ประมวลผลได้เร็ว เหมาะกับการทำงานกับ data ขนาดใหญ่

    .

    dtplyr เชื่อม dplyr เข้ากับ data.table โดยการแปล dplyr syntax ให้เป็น data.table syntax ทำให้เราทำงานได้ง่ายและรวดเร็ว


    🧑‍💻 วิธีใช้ dytplyr

    เราสามารถใช้ dtplyr ได้ใน 3 ขั้นตอนง่าย ๆ:

    1. Install and load dtplyr
    2. Create a lazy data.table
    3. Execute the syntax

    .

    1️⃣ ขั้นที่ 1. Install & Load dtplyr

    ในการใช้งาน dtplyr เราต้องเรียกใช้ dplyr ด้วยเสมอ

    ดังนั้น ในการติดตั้ง เราต้องติดตั้งทั้ง dtplyr และ dplyr:

    # Install
    install.packages("dplyr")
    install.packages("dtplyr")
    

    เมื่อติดตั้งแล้ว ให้เราเรียกใช้งาน dtplyr และ dplyr ทุกครั้งที่เริ่ม session ในการทำงาน:

    # Load
    library(dplyr)
    library(dtplyr)
    

    Note: คู่มือการใช้ dtplyr แนะนำให้โหลด data.table ด้วย เพื่อใช้ functions ของ data.table ในการทำงาน

    .

    2️⃣ ขั้นที่ 2. Create a Lazy data.table

    หลังเรียกใช้งาน dtplyr ให้เราสร้าง dataset ที่เป็น lazy data.table object ขึ้นมา เพื่อช่วยให้ dtplyr เปลี่ยนคำสั่งของ dplyr เป็นคำสั่งของ data.table ได้:

    # Convert mtcars dataset into lazy data.table object
    mtcars_ldt <- lazy_dt(mtcars)
    

    .

    3️⃣ ขั้นที่ 3. Execute the Syntax

    ในขั้นสุดท้าย เราสามารถเริ่มทำงานโดยใช้ syntax ของ dplyr ได้เลย:

    # Execute the syntax
    mtcars_ldt |>
      filter(am == 1 & mpg >= 20) |>
      select(model, mpg) |>
      arrange(desc(mpg)) |>
      as.data.table()
    

    ผลลัพธ์:

                 model   mpg
                <char> <num>
     1: Toyota Corolla  33.9
     2:       Fiat 128  32.4
     3:    Honda Civic  30.4
     4:   Lotus Europa  30.4
     5:      Fiat X1-9  27.3
     6:  Porsche 914-2  26.0
     7:     Datsun 710  22.8
     8:     Volvo 142E  21.4
     9:      Mazda RX4  21.0
    10:  Mazda RX4 Wag  21.0
    

    จะสังเกตว่า ใน code บรรทัดสุดท้าย เราเพิ่ม as.data.table() เข้ามาเพื่อบอกให้ dtplyr รู้ว่า เราเขียน syntax เสร็จแล้ว และพร้อมให้แปลงให้เป็น data.table syntax

    ทั้งนี้ ถ้าเราเขียนโดยไม่มี as.data.table():

    # Execute the syntax, without as.data.table()
    mtcars_ldt |>
      filter(am == 1 & mpg >= 20) |>
      select(model, mpg) |>
      arrange(desc(mpg))
    

    เราจะได้ผลลัพธ์ที่เป็นแค่ preview ที่ไม่สามารถนำไปใช้งานต่อได้:

      model            mpg
      <chr>          <dbl>
    1 Toyota Corolla  33.9
    2 Fiat 128        32.4
    3 Honda Civic     30.4
    4 Lotus Europa    30.4
    5 Fiat X1-9       27.3
    6 Porsche 914-2   26  
    # ℹ 4 more rows
    # ℹ Use `print(n = ...)` to see more rows
    

    ดังนั้น ถ้าเราต้องการผลลัพธ์ทั้งหมด เราต้องใช้ as.data.table() ในการรันคำสั่งทุกครั้ง

    Note: เราสามารถใช้คำสั่งอื่น ๆ แทน as.data.table() ได้ โดยจะให้ผลลัพธ์ที่แตกต่างกันไปดังนี้:

    Functionผลลัพธ์ที่ส่งกลับมา
    as.data.table()data.table
    as.data.frame()data.frame
    as.tibble()tibble
    collect()tibble
    pull()Single column

    😺 GitHub

    ดู code ทั้งหมดในบทความนี้ได้ที่ GitHub


    📃 References


    ✅ R Book for Psychologists: หนังสือภาษา R สำหรับนักจิตวิทยา

    📕 ขอฝากหนังสือเล่มแรกในชีวิตด้วยนะครับ 😆

    🙋 ใครที่กำลังเรียนจิตวิทยาหรือทำงานสายจิตวิทยา และเบื่อที่ต้องใช้ software ราคาแพงอย่าง SPSS และ Excel เพื่อทำข้อมูล

    💪 ผมขอแนะนำ R Book for Psychologists หนังสือสอนใช้ภาษา R เพื่อการวิเคราะห์ข้อมูลทางจิตวิทยา ที่เขียนมาเพื่อนักจิตวิทยาที่ไม่เคยมีประสบการณ์เขียน code มาก่อน

    ในหนังสือ เราจะปูพื้นฐานภาษา R และพาไปดูวิธีวิเคราะห์สถิติที่ใช้บ่อยกัน เช่น:

    • Correlation
    • t-tests
    • ANOVA
    • Reliability
    • Factor analysis

    🚀 เมื่ออ่านและทำตามตัวอย่างใน R Book for Psychologists ทุกคนจะไม่ต้องพึง SPSS และ Excel ในการทำงานอีกต่อไป และสามารถวิเคราะห์ข้อมูลด้วยตัวเองได้ด้วยความมั่นใจ

    แล้วทุกคนจะแปลกใจว่า ทำไมภาษา R ง่ายขนาดนี้ 🙂‍↕️

    👉 สนใจดูรายละเอียดหนังสือได้ที่ meb:

  • สรุป 10 คอนเซ็ปต์ทางสถิติที่คนทำงานสาย data ควรรู้ จาก 3 คอร์สเรียน stats แนะนำของ Google, DataCamp, และ DataRockie

    สรุป 10 คอนเซ็ปต์ทางสถิติที่คนทำงานสาย data ควรรู้ จาก 3 คอร์สเรียน stats แนะนำของ Google, DataCamp, และ DataRockie

    Statistics เป็น 1 ใน 3 ทักษะที่สำคัญในการทำงานกับ data

    (อีก 2 ทักษะ คือ programming และ domain expertise)

    โดย statistics ช่วยให้เรา …

    • ค้นพบรูปแบบและความสัมพันธ์ในข้อมูล
    • วิเคราะห์และรับมือกับความไม่แน่นอน (uncertainty)
    • Get insights จาก data
    • ช่วยตัดสินใจเกี่ยวกับอนาคต
    • แก้ปัญหาที่ซับซ้อน

    ในบทความนี้ เราจะมาดู 10 statistical concepts ที่คนทำงานสาย data ควรรู้กัน โดยสรุปเนื้อหาจาก 3 คอร์ส data analytics:

    ถ้าพร้อมแล้ว มาเริ่มกันเลย


    1. 1️⃣ What Is Statistics?
    2. 2️⃣ Central Tendency
    3. 3️⃣ Spread
    4. 4️⃣ Position
    5. 5️⃣ Probability
    6. 6️⃣ Sampling
    7. 7️⃣ Distributions & Central Limit Theorem (CLT)
    8. 8️⃣ Confidence Interval
    9. 9️⃣ Hypothesis Testing
    10. 🔟 Experimental Designs
    11. 📄 References

    1️⃣ What Is Statistics?

    👉 Statistics เป็นศาสตร์ของการเก็บรวบรวม (collect) และวิเคราะห์ (analyse) ข้อมูล

    เมื่อเราต้องการศึกษา population หรือกลุ่มที่เราสนใจ (เช่น คนไทย) เราต้องเก็บข้อมูลและนำมาวิเคราะห์ เพื่อหาข้อสรุป

    แต่เพราะเราไม่สามารถเก็บข้อมูลของ population ได้ทั้งหมด (เช่น เก็บข้อมูลจากคนไทยทั้งประเทศ) ทำให้เราต้องเลือกเก็บข้อมูลจาก sample หรือกลุ่มตัวอย่างที่เป็นตัวแทนของ population แทน

    การที่เรามี population และ sample ทำให้เราแบ่ง statistics ได้เป็น 2 สาขา:

    No.TypeDescription
    1Descriptive statisticsสรุปลักษณะของชุดข้อมูล (sample และ popilation)
    2Inferential statisticsอนุมานลักษณะของ population จากลักษณะของ sample

    ตัวอย่างหัวข้อของ descriptive statistics:

    • Central tendency
    • Spread
    • Position

    ตัวอย่างหัวข้อของ inferential statistics:

    • Confidence level
    • Significance level
    • Hypothesis testing

    2️⃣ Central Tendency

    👉 Central tendency คือ ค่ากลางของชุดข้อมูล และมี 3 ค่า ได้แก่:

    No.MeasureDefinition
    1Meanค่าเฉลี่ย (average)
    2Medianข้อมูลที่อยู่กลางชุดข้อมูล (middle value)
    3Modeข้อมูลที่เกิดขึ้นบ่อยที่สุดในชุดข้อมูล (most frequent value)

    Note:

    • Central tendency ที่เรานิยมใช้ คือ mean
    • เราควรใช้ median ในกรณีที่ชุดข้อมูลมี outlier เพราะ mean มีความอ่อนไหวต่อ outlier
    • Mean และ median มีได้ 1 ค่า แต่ mode มีได้มากกว่า 1 ค่า

    อ่านเพิ่มเติมเกี่ยวกับ central tendency: บทความจาก Australian Bureau of Statistics


    3️⃣ Spread

    👉 Spread คือ การวัดความหลากหลายของข้อมูล และมี 4 ค่า ได้แก่:

    No.MeasureDefinition
    1Rangeค่าความต่างระหว่าง ค่าที่น้อยที่สุด (min) และค่าที่มากที่สุด (max)
    2Standard deviation (SD)ค่าความห่างโดยเฉลี่ยระหว่างข้อมูลและ mean ของชุดข้อมูล
    3VarianceSD กำลังสอง
    4Interquartile rangeค่าความต่างระหว่าง quartile ที่ 1 (Q1) และ quartile ที่ 3 (Q3)

    อ่านเพิ่มเติมเกี่ยวกับ spread: บทความจาก Australian Bureau of Statistics


    4️⃣ Position

    👉 Position หมายถึง ตำแหน่งของข้อมูลในชุดข้อมูล และมี 2 ค่าหลัก ได้แก่:

    No.MeasureDefinition
    1Percentileระบุตำแหน่งจาก % ข้อมูลที่มีค่าน้อยกว่าข้อมูลนั้น (เช่น ข้อมูลที่ P70 หมายถึง มีข้อมูลที่อยู่ต่ำกว่าข้อมูลนี้ 70%)
    2Quartileระบุตำแหน่งโดยแบ่งข้อมูลเป็น 4 ส่วนเท่า ๆ กัน (quartile)

    5️⃣ Probability

    👉 Probability (ความน่าจะเป็น) คือ การศึกษาความไม่แน่นอน (uncertainty) และแบ่งได้เป็น 2 ประเภทหลัก ตามลักษณะ event (เหตุการณ์) ที่เราสนใจ:

    1. Independent probability
    2. Conditional probability

    .

    ประเภทที่ 1. Independent probability

    👉 Probability ของเหตุการณ์ที่ไม่ขึ้นอยู่กับเหตุการณ์อื่น (independent events) เช่น:

    • การฟังเพลงรัก กับ พระอาทิตย์ขึ้น
    • การดื่มกาแฟ กับ ฝนตก
    • การใส่เสื้อสีฟ้า กับ ราคาหุ้นขึ้น

    🧮 วิธีคำนวณ:

    P(A) = Outcome A / Total outcomes

    • P(A) คือ probability ของ event A
    • Outcome A คือ จำนวนครั้งที่เกิด event A
    • Total outcomes คือ จำนวนครั้งที่เกิด events ทั้งหมด

    .

    ประเภทที่ 2. Conditional probability

    👉 Probability ของเหตุการณ์ที่ขึ้นอยู่กับเหตุการณ์อื่น (dependent events) เช่น:

    • การสอบเข้ามหาวิทยาลัย กับ การเรียนจบ ป.ตรี (จะเรียนไม่จบ ถ้าไม่ได้สอบ)
    • การซื้อหวย กับ การถูกหวย (จะถูกหวยไม่ได้ ถ้าไม่ได้ซื้อ)
    • การออมเงิน และ การมีเงินหลังเกษียณ (อาจไม่มีเงินใช้ ถ้าไม่ออมเงิน)

    🧮 วิธีคำนวณ:

    P(A | B) = P(A ∩ B) / P(B)

    • P(A | B) คือ probability ของ event A ถ้าเกิด event B
    • P(A ∩ B) คือ probability ของ event A และ B
    • P(B) คือ probability ของ event B

    6️⃣ Sampling

    👉 Sampling คือ การสร้าง sample จาก population และมี 2 ประเภท ได้แก่

    1. Non-probability sampling: การสร้าง sample ที่สมาชิกของ population มีโอกาสถูกเลือกไม่เท่ากัน
    2. Probability sampling: การสร้าง sample ที่สมาชิกของ population มีโอกาสถูกเลือกเท่า ๆ กัน

    โดยแต่ละประเภทมีประเภทย่อยดังนี้:

    .

    🍀 Non-probability sampling มี 4 ประเภทย่อย:

    No.TypeMeaning
    1Voluntary responseกลุ่มตัวอย่างสมัครใจเข้าร่วมเอง
    2Convenience samplingกลุ่มตัวอย่างมาจากคนที่เข้าถึงได้ง่าย (เช่น เพื่อน คนในครอบครัว)
    3Purposive samplingสร้างกลุ่มตัวอย่างตามเกณฑ์ที่กำหนด (เช่น เลือกคนอายุ 20 ปีเท่านั้น)
    4Snowball samplingกลุ่มตัวอย่างที่ได้จากการให้ผู้เข้าร่วมชวนกันต่อเป็นลูกโซ่

    .

    🍀 Probability sampling มี 4 ประเภทย่อย:

    No.TypeMeaning
    1Simple random samplingสุ่มกลุ่มตัวอย่างจากประชากรโดยตรง
    2Stratified random samplingแบ่งประชากรออกเป็นกลุ่ม ๆ แล้วสุ่มตัวอย่างจากแต่ละกลุ่มตามสัดส่วน
    3Cluster random samplingแบ่งประชากรเป็นกลุ่ม ๆ แล้วเลือกสุ่มกลุ่มมาเป็นตัวอย่าง
    4Systematic random samplingจัดลำดับสมาชิกแล้วสุ่มเลือกทุก ๆ nth คน เช่น คนที่ 5, 10, 15, …

    7️⃣ Distributions & Central Limit Theorem (CLT)

    👉 Distribution คือ การกระจายตัวของข้อมูล

    แม้ว่า distribution จะมีหลายประเภท แต่มี 2 ประเภท ที่เรามักพบบ่อย ได้แก่:

    1. Normal distribution
    2. Sampling distribution

    .

    ประเภทที่ 1. Normal distribution

    👉 Normal distribution คือ การกระจายตัวแบบระฆังคว่ำ (bell shape) เพราะมีข้อมูลส่วนใหญ่กระจุกตัวอย่างตรงกลาง และกระจายตัวออกด้านข้าง

    นอกจากทรงระฆังคว่ำที่เป็นจุดเด่น normal distribution ยังมีลักษณะอื่น ๆ อีก คือ:

    1. สมมาตร (symmetrical)
    2. พื้นที่ใต้กราฟ = 1
    3. หางทั้งสองข้างจะเข้าใกล้ 0 แต่ไม่แตะ 0
    4. เรารู้ว่า ในแต่ละส่วนของ normal distribution มีข้อมูลอยู่กี่เปอร์เซ็นต์:
    Zone%
    -/+1 SD68
    -/+2 SD95
    -/+3 SD99

    Normal distribution เป็น distribution ที่มีความสำคัญ เพราะ:

    1. เป็น distribution ที่พบได้ทั่วไปในธรรมชาติ เช่น ส่วนสูง ความดันเลือด IQ
    2. เป็นพื้นฐานของการวิเคราะห์ทางสถิติอื่น ๆ เช่น hypothesis testing

    .

    ประเภทที่ 2. Sampling distribution

    👉 Sampling distribution เป็น distribution ที่เกิดจากการเอา mean ของหลาย ๆ samples มาสร้างกราฟ

    ยกตัวอย่างเช่น sampling distribution จาก 10 samples, 100 samples, และ 1,000 samples (แต่ละ sample มีขนาด 30 คน):

    .

    📊 Central limit theorem (CLT)

    CLT ระบุว่า ยิ่งเรามี sample มากขึ้นเท่าไร sampling distribution ก็จะยิ่งเหมือน normal distribution เข้าไปเท่านั้น

    เราสามารถสังเกตเห็นได้จากตัวอย่างกราฟด้านบน ในขณะที่เราเพิ่ม samples จาก 10 เป็น 100 เป็น 1,000 การกระจายตัวก็ดูเหมือน normal distribution เข้าไปเรื่อย ๆ

    ทั้งนี้ CLT จะเป็นจริงได้ ถ้าเงื่อนไข 3 ข้อนี้เป็นจริง:

    No.AssumptionDescription
    1Randomisationsamples ได้มาจากการสุ่ม
    2Independenceการสุ่มแต่ละครั้งไม่ขึ้นกับการสุ่มครั้งก่อน
    3Sample sizeกลุ่มตัวอย่างมีขนาดใหญ่พอ (อย่างน้อย 30 ตัวอย่าง ตาม rule of thumb)

    8️⃣ Confidence Interval

    👉 Confidence interval คือ การประมาณการ (estimate) โดยใช้ช่วง (interval) แทนค่าเดี่ยว ๆ (point)

    ยกตัวอย่างเช่น แทนที่เราจะเดาว่า คนคนหนึ่งมีอายุ 20 ปี (point) เราสามารถเดาเป็นช่วงได้ เช่น อายุ 18-22 ปี (interval)

    ทั้งนี้ confidence interval ประกอบด้วย 3 ส่วน:

    No.ComponentExample
    1Sample statisticเรารู้ว่า คนคนนี้อยู่ในกลุ่มคนที่มีค่าเฉลี่ยอายุ 20 ปี
    2Margin of errorเราเชื่อว่า อายุจริงของคนคนนี้จะต่างจากค่าเฉลี่ย -/+ 2 ปี
    3Confidence levelเราเชื่อว่า การเดาของเรามีโอกาสถูก 95%

    Note:

    • 95% เป็น confidence level ที่นิยมใช้มากที่สุด
    • ยิ่ง confidence level สูง, confidence interval ก็ยิ่งกว้าง เพราะต้องมีความครอบคลุมเพิ่ม

    9️⃣ Hypothesis Testing

    👉 Hypothesis testing คือ การทดสอบว่า สิ่งที่เราเชื่อเกี่ยวกับ population เป็นจริงไหม

    ตัวอย่างเช่น:

    • คนไทยมีความสูงเฉลี่ย 170 cm
    • ผู้หญิงทำข้อสอบเลขได้ดีกว่าผู้ชาย
    • กาแฟช่วยให้ทำงานได้ดีขึ้น

    .

    👉 4 ขั้นตอนในการทำ hypothesis testing:

    1. ตั้ง null hypothesis (H0) และ alternate hypothesis (H1)
    2. เลือก significance level
    3. หา p-value
    4. ตัดสินใจว่า จะ reject หรือ fail to reject H0

    .

    🤔 H0 vs H1

    HypothesisDescriptionExample
    H0สมมุติฐานที่ถือว่าเป็นจริง จนกว่าจะมีหลักฐานมาหักล้างความสูงเฉลี่ยของคนไทย เท่ากับ 170 cm
    H1สมมุติฐานที่ถือว่าเป็นจริง ต่อเมื่อมีหลักฐานสนับสนุนความสูงเฉลี่ยของคนไทย ไม่เท่ากับ 170 cm

    ตัวอย่างเช่น:

    ExampleH0H1
    คนไทยมีความสูงเฉลี่ย 170 cmความสูงเฉลี่ยของคนไทย เท่ากับ 170 cmความสูงเฉลี่ยของคนไทย ไม่เท่ากับ 170 cm
    ผู้หญิงทำข้อสอบเลขได้ดีกว่าผู้ชายคะแนนสอบเลขของผู้หญิงและผู้ชายเท่ากันคะแนนสอบเลขของผู้หญิงและผู้ชายไม่เท่าเท่ากัน
    กาแฟช่วยให้ทำงานได้ดีขึ้นดื่มกาแฟแล้ว จะทำงานได้แค่ 8 ชม.ดื่มกาแฟแล้ว จะทำงานได้นานกว่า 8 ชม.

    .

    🤔 Significance level vs p-value

    TermDescription
    Significance levelความเป็นไปได้ที่จะ reject H0 เมื่อ H0 เป็นจริง
    P-valueความเป็นไปได้ที่จะเห็นผลลัพธ์ที่แตกต่างจาก H0 เมื่อ H0 เป็นจริง

    .

    🤔 Reject H0 vs fail to reject H0

    เราจะ reject H0 (ยอมรับ H1) เมื่อ significance level และ p-value มีค่าดังนี้:

    ActionWhen
    Reject H0p-value < significance level
    Fail to reject H0p-value > significance level

    🔟 Experimental Designs

    การเก็บข้อมูลทางสถิติทำได้ 3 แบบหลัก ๆ ได้แก่:

    1. Observational study
    2. A/B testing
    3. Randomised controlled trial (RCT)

    .

    👉 Observational study เป็นการเก็บข้อมูล ผ่านการสังเกตการณ์ เช่น:

    • สังเกตพฤติกรรมการซื้อของในร้านค้า
    • สังเกตพฤติกรรมการเล่นของเด็ก
    • สังเกตพฤติกรรมการหาคู่ของนก

    ใน observational study เราไม่ได้เปลี่ยนแปลงตัวแปรต้น (independent variable) ทำให้:

    • เราสามารถบอกได้ว่า อะไรเกิดขึ้นกับอะไร (correlation)
    • แต่ไม่สามารถบอกได้ว่า อะไรทำให้เกิดอะไร (causation) เท่านั้น

    .

    👉 A/B testing เป็นการทดสอบที่นิยมใช้ใน business เพื่อทดสอบผลิตภัณฑ์/บริการ

    ใน A/B testing เรามีของ 2 versions (A vs B) และกลุ่มตัวอย่างจะถูกสุ่มให้เห็น version ที่ไม่เหมือนกัน

    เช่น เรามีเว็บไซต์แบบเก่า (A) และแบบใหม่ (B) และเราอยากรู้ว่า แบบไหนกระตุ้นยอดขายดีที่สุด

    เราเปิดใช้งานเว็บไซต์ 2 versions โดยลูกค้าแต่ละคนจะเห็นเว็บไซต์ไม่เหมือนกัน (บางคนเห็นแบบเก่า และบางคนเห็นแบบใหม่)

    หลังจากเวลาผ่านไปสักพัก เราเอาข้อมูลการขายมาดูว่า ลูกค้าที่เห็นเว็บไซต์แบบไหนที่มียอดซื้อมากที่สุด

    ดูตัวอย่าง A/B testing ในโลกจริง: 10 real-world examples of A/B testing that made an impact

    .

    👉 RCT เป็น “gold standard” ของ experimental design เพราะ:

    1. มีการควบคุมตัวแปรต้น ทำให้เราอนุมานถึง cause และ effect ได้
    2. ลดความลำเอียง (bias) และอิทธิพลของตัวแปรที่สาม (confounding variables)

    RCT มีลักษณะเด่น 2 อย่าง:

    No.CharacteristicDescription
    1Randomisationกลุ่มตัวอย่างถูกสุ่มเข้าเงื่อนไข
    2Control groupมีกลุ่มที่เป็น baseline เพื่อเปรียบเทียบกับกลุ่มที่ได้รับเงื่อนไขบางอย่าง

    ตัวอย่างการทำ RCT เช่น การทดสอบผลของยาลดความดัน:

    • เราใช้การสุ่มผู้เข้าร่วมให้เป็น 2 กลุ่ม
    • กลุ่มแรกให้รับยาปลอมที่ไม่ส่งผลต่อร่างกาย (control group)
    • กลุ่มที่สองได้รับยาจริงที่เราต้องการทดสอบผล (treatment)
    • หลังรับยา เราวัดความดันของทั้งสองกลุ่ม

    📄 References

  • วิธีใช้ ggplot2 เพื่อสร้างกราฟอย่างมืออาชีพระดับโลก แบบ BBC และ Financial Times ในภาษา R — ตัวอย่างการสำรวจข้อมูลเพนกวินจาก palmerpenguins

    วิธีใช้ ggplot2 เพื่อสร้างกราฟอย่างมืออาชีพระดับโลก แบบ BBC และ Financial Times ในภาษา R — ตัวอย่างการสำรวจข้อมูลเพนกวินจาก palmerpenguins

    ggplot2 เป็น package สำหรับ data visualisation ในภาษา R และเป็นเครื่องมือสร้างกราฟที่มืออาชีพนิยม ตั้งแต่นักวิจัยในการตีพิมพ์ผลงาน ไปจนถึงสำนักข่าวระดับโลกอย่าง BBC และ Financial Times

    ggplot2 มีจุดเด่น 4 ข้อ:

    1. ใช้งานง่าย
    2. สร้างกราฟได้หลากหลาย
    3. ปรับแต่งกราฟได้ดังใจ
    4. ได้กราฟที่ดูดีและมีคุณภาพ

    .

    ในบทความนี้ เราจะมาดูวิธีใช้ ggplot2 เพื่อสร้างกราฟแบบมืออาชีพกัน:

    • ggplot2 syntax
    • Basic plotting
    • Plot customisations

    .

    ถ้าพร้อมแล้ว ไปเริ่มกันเลย


    1. 🔤 gg for “Grammar of Graphics”
    2. 🏁 Getting Started With ggplot2
    3. ✍️ Basic Syntax
    4. 📊 Basic Plotting: Data, Aesthetics, & Geom
      1. 🎨 Aesthetics
      2. ⏹️ Geom
    5. 🔧 More Customisations
      1. 🖼️ Theme
      2. 🔤 Text
      3. ✌️ Facet
    6. 🔥 Summary
    7. 📚 Learn More About ggplot2
      1. 😺 GitHub
      2. 📖 Read More About ggplot2
      3. 📰 Cheat Sheets
    8. 📃 References
    9. ✅ R Book for Psychologists: หนังสือภาษา R สำหรับนักจิตวิทยา

    🔤 gg for “Grammar of Graphics”

    gg ใน ggplot2 ย่อมาจาก “Grammar of Graphics”

    หนังสือ Grammar of Graphics ของ Leland Wilkinson บน Amazon

    Grammar of Graphics เป็นแนวคิดที่มองกราฟเป็นเหมือนภาษา คือ มีโครงสร้างและองค์ประกอบที่ตายตัว ซึ่งเมื่อเรานำมารวมกัน เราก็จะได้กราฟที่ต้องการขึ้นมา

    โดยกราฟใน ggplot2 ประกอบด้วย 7 ส่วน หรือ layers ได้แก่:

    No.LayerDescription
    1Dataชุดข้อมูลสำหรับสร้างกราฟ
    2Aestheticsจับคู่ข้อมูลกับกราฟ (เช่น แกน x และ y)
    3Geometric objectsประเภทกราฟ (เช่น กราฟเส้น กราฟแท่ง)
    4Facetsสร้างกราฟย่อย
    5Statistical transformationsวิเคราะห์ข้อมูล (เช่น หาค่าเฉลี่ย)
    6Coordinatesแกนในการสร้างกราฟ
    7Themeหน้าตาของกราฟ (เช่น สีพื้นหลัง)

    ในการทำงาน เรามักจะเรียกใช้งาน 3 layers แรกเป็นหลัก ได้แก่:

    1. Data
    2. Aesthetics
    3. Geometric objects

    🏁 Getting Started With ggplot2

    ในการเริ่มต้นใช้งาน ggplot2 เราต้องทำ 3 อย่างก่อน คือ:

    .

    ข้อที่ 1. ติดตั้ง ggplot2 บน environment ของเรา:

    install.packages("ggplot2")
    

    Note: ถ้าใครเคยติดตั้งแล้ว สามารถข้ามไปขั้นถัดไปได้เลย

    .

    ข้อที่ 2. เรียกใช้งาน ggplot2:

    library(ggplot2)
    

    Note: เราต้องเรียกใช้งาน ggplot2 ทุกครั้งที่เริ่ม session ใหม่

    .

    ข้อที่ 3. โหลด dataset ที่เราจะใช้สร้างกราฟ

    สำหรับบทความนี้ เราจะใช้ penguins dataset ที่มีข้อมูลของเพนกวิน 3 สายพันธุ์ (เช่น สปีชีส์ น้ำหนัก ความยาวปีก) กัน

    เราสามารถโหลด dataset ได้ดังนี้:

    install.packages("palmerpenguins")
    library(palmerpenguins)
    

    จากนั้น เราสามารถ preview ข้อมูลได้ด้วย head():

    head(penguins)
    

    ผลลัพธ์:

    Note: เราสามารถอ่านคู่มือ penguins ได้ด้วยคำสั่ง ?penguins

    .

    เมื่อทำครบทั้ง 3 ขั้นตอน เราก็พร้อมที่จะสร้างกราฟใน ggplot2 แล้ว


    ✍️ Basic Syntax

    ก่อนไปดูการสร้างกราฟ เรามาดู syntax ของ ggplot2 กันก่อน:

    ggplot(data, aes(x, y, other)) +
    	geom_*() +
    	...
    • ggplot() คือ การเรียกใช้งาน ggplot2
    • data คือ ชุดข้อมูลในการสร้างกราฟ
    • aes() คือ ส่วนจับคู่ข้อมูลกับลักษณะของกราฟ
      • x, y คือ ข้อมูลที่แสดงบนแกน x และ y
      • other คือ ข้อมูลที่จะแสดงผ่านส่วนอื่น ๆ ของกราฟ เช่น สี ขนาด รูปทรง
    • geom_* คือ ประเภทกราฟ
    • คือ function อื่น ๆ ในการตั้งค่ากราฟ (เช่น theme, facet)

    📊 Basic Plotting: Data, Aesthetics, & Geom

    ในการสร้างกราฟ เรามี 3 input เบื้องต้นที่เราต้องกำหนด ได้แก่:

    No.InputDescription
    1DataDataset ในการสร้างกราฟ
    2Aestheticsลักษณะของกราฟที่ใช้แสดงข้อมูล (เช่น แกน x และ y)
    3Geomประเภทกราฟ (เช่น กราฟเส้น กราฟแท่ง)

    Note: ทั้งสามอย่างสะท้อนถึง 3 layers แรกของ ggplot2

    ยกตัวอย่างเช่น

    สร้าง scatter plot ที่แสดงความสัมพันธ์ระหว่างน้ำหนักตัว (body_mass_g) และความยาวปีก (flipper_length_mm) ของเพนกวิน:

    ggplot(penguins, aes(x = body_mass_g,
                         y = flipper_length_mm)) +
      geom_point()
    

    ผลลัพธ์:

    .

    🎨 Aesthetics

    นอกจากแกน x และ y เราแสดงข้อมูลผ่านลักษณะอื่น ๆ ของกราฟได้ เช่น:

    No.ParametreDescription
    1colorสีขอบรูปทรง
    2fillสีในรูปทรง
    3shapeรูปทรง
    4sizeขนาด
    5alphaความโปร่งใส

    ยกตัวอย่างเช่น

    เพิ่มสปีชีส์เข้าไปใน scatter plot:

    ggplot(penguins, aes(x = body_mass_g,
                         y = flipper_length_mm,
                         color = species)) +
      geom_point()
    

    ผลลัพธ์:

    Note: เราใช้ color แทน fill เพราะ จุด default ของ scatter plot ไม่รองรับการเติมสี

    .

    ⏹️ Geom

    เราสามารถเปลี่ยนประเภทกราฟได้ โดยเปลี่ยน geom_*() เช่น:

    No.GeomGraph
    1geom_histogram()Histogram
    2geom_boxplot()Box plot
    3geom_line()Line plot
    4geom_col()Bar plot
    5geom_density()Density plot

    Note: ggplot2 มีรูปแบบกราฟกว่า 40+ แบบให้เลือก เราสามารถดูรูปแบบกราฟต่าง ๆ ได้ที่ Function reference และดูตัวอย่างกราฟได้ที่ The R Gallery

    .

    นอกจากนี้ เรายังสามารถปรับแต่งหน้าตาของกราฟได้ด้วย parametre ต่าง ๆ ใน geom_*() เช่น:

    No.ParametreDescription
    1colorสีขอบรูปทรง
    2fillสีในรูปทรง
    3shapeรูปทรง
    4sizeขนาด
    5alphaความโปร่งใส

    Note:

    • จะสังเกตว่า parametre เหล่านี้ (เรียกว่า attribute) เหมือนกับ parametres ของ aes()
    • ความแตกต่างอยู่ที่ parametre ใน geom_*() จะคงที่ ในขณะที่ parametre ใน aes() จะเปลี่ยนแปลงตามข้อมูล

    .

    ยกตัวอย่างเช่น

    เปลี่ยนจุดข้อมูลให้เป็นกล่องสี่เหลี่ยมใส:

    ggplot(penguins, aes(x = body_mass_g,
                         y = flipper_length_mm,
                         color = species)) +
      geom_point(shape = 22)
    

    ผลลัพธ์:

    จะเห็นได้ว่า จุดข้อมูลเปลี่ยนเป็นสี่เหลี่ยมเหมือนกันหมด และไม่เปลี่ยนตามประเภทเพนกวิน เพราะเรากำหนด argument ใน geom_*()

    .

    Note: เราสามารถดู argument ของ shape และ parametres อื่น ๆ ได้ที่ Aesthetic specifications


    🔧 More Customisations

    จนถึงตอนนี้ เรารู้วิธีสร้างและปรับแต่งกราฟเบื้องต้นกันแล้ว

    เรามาดู 3 วิธีในการปรับแต่งเพิ่มเติม เพื่อให้กราฟของเราดูเป็นมืออาชีพกัน:

    1. Theme
    2. Text
    3. Facet

    .

    🖼️ Theme

    Theme ใน ggplot2 หมายถึง หน้าตากราฟที่ไม่เกี่ยวข้องกับข้อมูล เช่น สีแกน x และ y และสีพื้นหลัง

    เราสามารถปรับ theme ได้โดยการเรียกใช้ theme_*() เช่น:

    ggplot(penguins, aes(x = body_mass_g,
                         y = flipper_length_mm,
                         color = species)) +
      geom_point() +
      
      # Apply classic theme
      theme_classic()
    

    ผลลัพธ์:

    จะเห็นว่า กราฟของเราดูสะอาดตามากขึ้น เมื่อไม่มี gridline

    .

    Note:

    ggplot2 มี built-in themes ให้เลือกใช้ 5 แบบหลัก ได้แก่:

    No.ThemeBackgroundGridline
    1theme_gray()สีเทาสีขาว
    2theme_classic()สีขาวNone
    3theme_bw()สีขาวสีเทา
    4theme_light()สีขาวสีเทา
    5theme_dark()สีเทาเข้มสีเทาอ่อน
    • theme_gray() เป็น default theme ของ ggplot2
    • ดู built-in themes อื่น ๆ ได้ที่ Complete themes
    • เราสามารถเลือกใช้ themes จาก packages อื่นใน R ได้ เช่น ggthemes และ bbcplot

    .

    🔤 Text

    ข้อความเป็นส่วนสำคัญของกราฟ ซึ่งสามารถช่วยให้คนที่ดูกราฟของเราเข้าใจกราฟได้ง่ายขึ้น

    ใน ggplot2 เราสามารถปรับแต่งข้อความได้ 3 วิธี:

    No.SyntaxDescription
    1theme()กำหนดขนาด และ typeface ของข้อความ
    2labs()เพิ่มชื่อกราฟ ชื่อแกน x, y และ legend
    3annotate()เพิ่มโน้ตในกราฟ

    ตัวอย่างเช่น:

    ggplot(penguins, aes(x = body_mass_g,
                           y = flipper_length_mm,
                           color = species)) +
      geom_point() +
      theme_classic() +
      
      # Adjust text size
      theme(plot.title = element_text(size = 16, face = "bold"),
            axis.title.x = element_text(size = 14),
            axis.title.y = element_text(size = 14),
            legend.title = element_text(size = 14),
            legend.text = element_text(size = 12),
            strip.text = element_text(size = 14, face = "bold")) +
      
      # Add a title, labels, and a legend
      labs(title = "Penguin Body Mass vs. Flipper Length",
           x = "Body Mass (g)",
           y = "Flipper Length (mm)",
           color = "Penguin Species") +
      
      # Add annotation
      annotate("text",
               x = 3000,
               y = 225,
               label = "Larger penguins tend to \\n have longer flippers",
               size = 5,
               color = "gray",
               hjust = 0)
    

    ผลลัพธ์:

    จะเห็นได้ว่า กราฟของเรามีชื่อกราฟ คำประกอบแกน x, y และ legend รวมทั้งโน้ตที่ช่วยในการอ่านกราฟ “Larger penguins tend to have longer flippers” เพิ่มขึ้นมา

    .

    ✌️ Facet

    ในบางครั้ง เราอาจต้องการสร้างกราฟย่อย ซึ่งเราสามารถทำได้ด้วย 2 คำสั่งใน ggplot2:

    No.FunctionDividing Factor
    1facet_wrap()1 categorical variable
    2facet_grid()2 categorical variables

    .

    ตัวอย่างเช่น

    ใช้ facet_wrap() แบ่งกราฟตามชนิดเพนกวิน:

    ggplot(penguins, aes(x = body_mass_g,
                         y = flipper_length_mm,
                         color = species)) +
      geom_point() +
      theme_bw() +
      
      # Use facet_wrap()
      facet_wrap(~species)
    

    ผลลัพธ์:

    .

    ใช้ facet_grid() แบ่งตามเพศและชนิดของเพนกวิน:

    ggplot(penguins, aes(x = body_mass_g,
                         y = flipper_length_mm,
                         color = species)) +
      geom_point() +
      theme_bw() +
      
      # Use facet_grid()
      facet_grid(sex~species)
    

    ผลลัพธ์:

    Note: ในกราฟ เรามี row ที่ 3 (NA) เพราะบาง record ไม่มีข้อมูลเพศของเพนกวิน


    🔥 Summary

    ในบทความนี้ เราได้เรียนรู้วิธีใช้ ggplot2 เพื่อสร้างกราฟอย่างมืออาชีพ

    • Syntax ของ ggplot2
    • การตั้งค่า aesthetics
      • x
      • y
      • Aesthetics อื่น ๆ
    • การตั้งค่า geom
      • geom_*()
      • paramatres ของ geom_*()
    • การปรับแต่งกราฟ
      • Theme
      • Text
      • Facet

    📚 Learn More About ggplot2

    .

    😺 GitHub

    สำหรับผู้ที่สนใจ สามารถดู code ทั้งหมดในบทความนี้ได้ที่ GitHub

    .

    📖 Read More About ggplot2

    .

    📰 Cheat Sheets


    📃 References

    Articles:

    Courses


    ✅ R Book for Psychologists: หนังสือภาษา R สำหรับนักจิตวิทยา

    📕 ขอฝากหนังสือเล่มแรกในชีวิตด้วยนะครับ 😆

    🙋 ใครที่กำลังเรียนจิตวิทยาหรือทำงานสายจิตวิทยา และเบื่อที่ต้องใช้ software ราคาแพงอย่าง SPSS และ Excel เพื่อทำข้อมูล

    💪 ผมขอแนะนำ R Book for Psychologists หนังสือสอนใช้ภาษา R เพื่อการวิเคราะห์ข้อมูลทางจิตวิทยา ที่เขียนมาเพื่อนักจิตวิทยาที่ไม่เคยมีประสบการณ์เขียน code มาก่อน

    ในหนังสือ เราจะปูพื้นฐานภาษา R และพาไปดูวิธีวิเคราะห์สถิติที่ใช้บ่อยกัน เช่น:

    • Correlation
    • t-tests
    • ANOVA
    • Reliability
    • Factor analysis

    🚀 เมื่ออ่านและทำตามตัวอย่างใน R Book for Psychologists ทุกคนจะไม่ต้องพึง SPSS และ Excel ในการทำงานอีกต่อไป และสามารถวิเคราะห์ข้อมูลด้วยตัวเองได้ด้วยความมั่นใจ

    แล้วทุกคนจะแปลกใจว่า ทำไมภาษา R ง่ายขนาดนี้ 🙂‍↕️

    👉 สนใจดูรายละเอียดหนังสือได้ที่ meb:

  • data.table: แนะนำ 3 ส่วนวิธีใช้งาน package ทรงพลัง เพื่อทำงานกับข้อมูลขนาดใหญ่อย่างมีประสิทธิภาพและรวดเร็ว ในภาษา R แบบครบ — ตัวอย่างการทำงานกับข้อมูลเที่ยวบินจาก flights dataset

    data.table: แนะนำ 3 ส่วนวิธีใช้งาน package ทรงพลัง เพื่อทำงานกับข้อมูลขนาดใหญ่อย่างมีประสิทธิภาพและรวดเร็ว ในภาษา R แบบครบ — ตัวอย่างการทำงานกับข้อมูลเที่ยวบินจาก flights dataset

    R ได้ชื่อว่าเป็น “statistical programming language” เพราะออกแบบมาเพื่อทำงานกับ data โดยเฉพาะ

    ภาษา R มี packages มากมายที่รองรับการทำงานกับ data ในรูปแบบตาราง (tabular data) หรือ data frame อย่างตัวอย่างในภาพ:

    ตัวอย่าง data frame: flights dataset

    หนึ่งใน packages ที่ได้รับความนิยมในการทำงานกับ data frame โดยเฉพาะงาน data science ได้แก่ data.table

    data.table เป็น package สำหรับ data manipulation ที่มีจุดเด่น 3 อย่าง คือ:

    1. ใช้งานง่าย (แม้จะมีการเขียนที่แตกต่างจาก functions ทั่วไป แต่มี syntax ที่ตายตัว)
    2. ประมวลผลเร็วและประหยัด resource เพราะ data.table optimises code ที่เราเขียน
    3. รองรับการทำงานกับ data ขนาดใหญ่ (เช่น data ที่ใช้ RAM ขนาด 10 ถึง 100 GB ในการประมวลผล)

    ในบทความนี้ เราจะมาดูวิธีการใช้งาน data.table แบบครบจบใน 3 ส่วนกัน:

    1. การใช้งาน data.table เบื้องต้น (syntax และ arguments)
    2. การใช้งาน data.table ขั้นสูง (combining และ chaining)
    3. Special symbols ใน data.table

    ถ้าพร้อมแล้ว มาเริ่มกันเลย


    1. 🏁 Get Started With data.table
    2. ✈️ Example Dataset: flights
      1. 1️⃣ Intro to flights
      2. 2️⃣ Get flights
    3. ✍️ Syntax: DT[i, j, by]
    4. 🍦 1st Argument: i
      1. 1️⃣ Select Rows
      2. 2️⃣ Filter
      3. 3️⃣ Sort
    5. 🧮 2nd Argument: j
      1. 1️⃣ Select Columns
      2. 2️⃣ Compute
      3. 3️⃣ Create Columns
    6. 🤝 3rd Argument: by
    7. 🔗 Combining & Chaining
      1. 1️⃣ Combining
      2. 2️⃣ Chaining
    8. 🍩 Special Symbols
      1. 1️⃣ .N
      2. 2️⃣ .SD
      3. 3️⃣ .SDcols
    9. 😎 Conclusion
    10. 🎒 Learn More About data.table
      1. 😺 GitHub
      2. 📚 อ่านเพิ่มเติมเกี่ยวกับ data.table
      3. 📑 Cheat Sheets ในการใช้งาน data.table
    11. 📃 References
    12. ✅ R Book for Psychologists: หนังสือภาษา R สำหรับนักจิตวิทยา

    🏁 Get Started With data.table

    ในการเริ่มต้นใช้งาน data.table เราจะต้องทำ 2 อย่าง ได้แก่:

    1. ติดตั้ง data.table (ทำครั้งแรกครั้งเดียว)
    2. โหลด data.table (ทำทุกครั้งที่เริ่ม session ใหม่)
    # Install data.table
    install.packages("data.table")
    
    # Load data.table
    library(data.table)
    

    เมื่อทำทั้ง 2 อย่างนี้แล้ว เราก็พร้อมที่จะใช้งาน data.table กันแล้ว


    ✈️ Example Dataset: flights

    1️⃣ Intro to flights

    ในบทความนี้ เราจะมาดูตัวอย่างการใช้ data.table กับ flights ซึ่งมีข้อมูลเที่ยวบินที่ออกจาก New York City ในปี ค.ศ. 2014 เช่น:

    • วันที่
    • สนามบินต้นทางและปลายทาง
    • ระยะเวลาที่เที่ยวบิน delay
    • ระยะเวลาบิน
    • ระยะทาง

    Note: ดูรายละเอียดทั้งหมดของ dataset ได้ที่ GitHub

    .

    2️⃣ Get flights

    เราสามารถเริ่มใช้งาน flights ใน 2 ขั้นตอน:

    ขั้นที่ 1. Download ไฟล์จาก link โดยไฟล์ที่ได้จะเป็น CSV (comma-separated values):

    ขั้นที่ 2. Import ข้อมูลเข้าใน R ด้วย fread() (”fast read”) ซึ่งเป็น function สำหรับโหลดข้อมูลของ data.table:

    # Import the dataset
    flights <- fread("flights14.csv")
    

    เราสามารถดูตัวอย่างข้อมูลได้ด้วย head():

    # Preview the dataset
    head(flights)
    

    ผลลัพธ์:

        year month   day dep_delay arr_delay carrier origin   dest air_time distance  hour
       <int> <int> <int>     <int>     <int>  <char> <char> <char>    <int>    <int> <int>
    1:  2014     1     1        14        13      AA    JFK    LAX      359     2475     9
    2:  2014     1     1        -3        13      AA    JFK    LAX      363     2475    11
    3:  2014     1     1         2         9      AA    JFK    LAX      351     2475    19
    4:  2014     1     1        -8       -26      AA    LGA    PBI      157     1035     7
    5:  2014     1     1         2         1      AA    JFK    LAX      350     2475    13
    6:  2014     1     1         4         0      AA    EWR    LAX      339     2454    18
    

    ✍️ Syntax: DT[i, j, by]

    การใช้งาน data.table ประกอบด้วย 4 ส่วน ดังนี้:

    DT[i, j, by]
    1. DT คือ dataset ที่เราต้องการใช้งาน
    2. i ใช้ทำงานกับ rows
    3. j ใช้ทำงานกับ columns
    4. by ใช้จับกลุ่มข้อมูล

    เราไปดูรายละเอียดการใช้งาน i, j, และ by กัน


    🍦 1st Argument: i

    เราสามารถใช้งาน i ได้ 3 อย่าง:

    1. Select rows: เลือก rows ที่ต้องการ
    2. Filter: กรองข้อมูล
    3. Sort: จัดลำดับข้อมูล

    .

    1️⃣ Select Rows

    เราสามารถใช้ i เพื่อเลือก rows ได้ 3 แบบ:

    1. เลือก 1 row
    2. เลือกหลาย rows
    3. คัด rows ที่ไม่ต้องการออก

    .

    แบบที่ #1. เลือก 1 row

    เช่น เลือก row ที่ 5 จาก flights:

    # Select a row
    flights[5]
    

    ผลลัพธ์:

        year month   day dep_delay arr_delay carrier origin   dest air_time distance  hour
       <int> <int> <int>     <int>     <int>  <char> <char> <char>    <int>    <int> <int>
    1:  2014     1     1         2         1      AA    JFK    LAX      350     2475    13
    

    .

    แบบที่ #2 – เลือกหลาย rows

    ซึ่งเราทำได้โดยการใช้ vector เช่น เลือก rows 1 ถึง 10:

    # Select a range of rows
    flights[1:10]
    

    ผลลัพธ์:

         year month   day dep_delay arr_delay carrier origin   dest air_time distance  hour
        <int> <int> <int>     <int>     <int>  <char> <char> <char>    <int>    <int> <int>
     1:  2014     1     1        14        13      AA    JFK    LAX      359     2475     9
     2:  2014     1     1        -3        13      AA    JFK    LAX      363     2475    11
     3:  2014     1     1         2         9      AA    JFK    LAX      351     2475    19
     4:  2014     1     1        -8       -26      AA    LGA    PBI      157     1035     7
     5:  2014     1     1         2         1      AA    JFK    LAX      350     2475    13
     6:  2014     1     1         4         0      AA    EWR    LAX      339     2454    18
     7:  2014     1     1        -2       -18      AA    JFK    LAX      338     2475    21
     8:  2014     1     1        -3       -14      AA    JFK    LAX      356     2475    15
     9:  2014     1     1        -1       -17      AA    JFK    MIA      161     1089    15
    10:  2014     1     1        -2       -14      AA    JFK    SEA      349     2422    18
    

    หรือเลือก rows 1, 3, 5, 7, และ 9:

    # Select multiple rows at interval
    flights[c(1, 3, 5, 7, 9)]
    

    ผลลัพธ์:

        year month   day dep_delay arr_delay carrier origin   dest air_time distance  hour
       <int> <int> <int>     <int>     <int>  <char> <char> <char>    <int>    <int> <int>
    1:  2014     1     1        14        13      AA    JFK    LAX      359     2475     9
    2:  2014     1     1         2         9      AA    JFK    LAX      351     2475    19
    3:  2014     1     1         2         1      AA    JFK    LAX      350     2475    13
    4:  2014     1     1        -2       -18      AA    JFK    LAX      338     2475    21
    5:  2014     1     1        -1       -17      AA    JFK    MIA      161     1089    15
    

    .

    แบบที่ #3 – คัด rows ที่ไม่ต้องการออก

    ซึ่งเราสามารถทำได้ 2 แบบ คือ:

    1. ใช้ -
    2. ใช้ !

    เช่น คัด row ที่ 1 ออก โดยใช้ -:

    # Deselect a row
    flights[-1]
    

    หรือใช้ !:

    # Deselect a row
    flights[!1]
    

    โดยทั้งสองแบบจะให้ผลลัพธ์แบบเดียวกัน แบบนี้:

             year month   day dep_delay arr_delay carrier origin   dest air_time distance  hour
            <int> <int> <int>     <int>     <int>  <char> <char> <char>    <int>    <int> <int>
         1:  2014     1     1        -3        13      AA    JFK    LAX      363     2475    11
         2:  2014     1     1         2         9      AA    JFK    LAX      351     2475    19
         3:  2014     1     1        -8       -26      AA    LGA    PBI      157     1035     7
         4:  2014     1     1         2         1      AA    JFK    LAX      350     2475    13
         5:  2014     1     1         4         0      AA    EWR    LAX      339     2454    18
        ---                                                                                    
    253311:  2014    10    31         1       -30      UA    LGA    IAH      201     1416    14
    253312:  2014    10    31        -5       -14      UA    EWR    IAH      189     1400     8
    253313:  2014    10    31        -8        16      MQ    LGA    RDU       83      431    11
    253314:  2014    10    31        -4        15      MQ    LGA    DTW       75      502    11
    253315:  2014    10    31        -5         1      MQ    LGA    SDF      110      659     8
    

    .

    2️⃣ Filter

    นอกจากการเลือก rows เรายังสามารถใช้ i เพื่อกรอง data ได้ 3 แบบ:

    1. กรองโดยใช้ 1 เงื่อนไข
    2. กรองโดยใช้หลายเงื่อนไข
    3. กรองโดยใช้ helpers

    .

    แบบที่ #1 – กรองข้อมูลโดยใช้ 1 เงื่อนไข

    เช่น กรอง rows ที่มีระยะทางบิน 500 miles ขึ้นไป:

    # Filter with 1 condition
    flights[distance >= 500]
    

    ผลลัพธ์:

             year month   day dep_delay arr_delay carrier origin   dest air_time distance  hour
            <int> <int> <int>     <int>     <int>  <char> <char> <char>    <int>    <int> <int>
         1:  2014     1     1        14        13      AA    JFK    LAX      359     2475     9
         2:  2014     1     1        -3        13      AA    JFK    LAX      363     2475    11
         3:  2014     1     1         2         9      AA    JFK    LAX      351     2475    19
         4:  2014     1     1        -8       -26      AA    LGA    PBI      157     1035     7
         5:  2014     1     1         2         1      AA    JFK    LAX      350     2475    13
        ---                                                                                    
    198323:  2014    10    31        18       -14      UA    EWR    LAS      291     2227    16
    198324:  2014    10    31         1       -30      UA    LGA    IAH      201     1416    14
    198325:  2014    10    31        -5       -14      UA    EWR    IAH      189     1400     8
    198326:  2014    10    31        -4        15      MQ    LGA    DTW       75      502    11
    198327:  2014    10    31        -5         1      MQ    LGA    SDF      110      659     8
    

    .

    แบบที่ #2 – กรองข้อมูลด้วยหลายเงื่อนไข

    เราสามารถเพิ่มเงื่อนไขการกรองได้ด้วย logical operators:

    OperatorMeaning
    &AND
    |OR
    !NOT

    เช่น กรอง rows ที่:

    • มีระยะทางบิน 500 miles ขึ้นไป และ
    • ออกจากสนามบิน LaGuardia (LGA):
    # Filter with multiple conditions
    flights[distance >= 500 & origin == "LGA"]
    

    ผลลัพธ์:

            year month   day dep_delay arr_delay carrier origin   dest air_time distance  hour
           <int> <int> <int>     <int>     <int>  <char> <char> <char>    <int>    <int> <int>
        1:  2014     1     1        -8       -26      AA    LGA    PBI      157     1035     7
        2:  2014     1     1        -7        -6      AA    LGA    ORD      142      733     5
        3:  2014     1     1        -7         0      AA    LGA    ORD      143      733     6
        4:  2014     1     1        -8       -17      AA    LGA    ORD      139      733     6
        5:  2014     1     1        -2        15      AA    LGA    ORD      145      733     7
       ---                                                                                    
    63251:  2014    10    31        14       -17      UA    LGA    IAH      200     1416    17
    63252:  2014    10    31        24        -5      UA    LGA    IAH      198     1416     6
    63253:  2014    10    31         1       -30      UA    LGA    IAH      201     1416    14
    63254:  2014    10    31        -4        15      MQ    LGA    DTW       75      502    11
    63255:  2014    10    31        -5         1      MQ    LGA    SDF      110      659     8
    

    .

    แบบที่ #3 – กรองโดยใช้ helpers

    เราสามารถกรองข้อมูลโดยใช้ helpers หรือ operators พิเศษ 3 อย่างนี้:

    HelperForSyntax
    %between%กรองข้อมูลตาม rangecol %between% range
    %like%กรองข้อมูลตาม text patterncol %like% pattern
    %chin%กรองข้อมูลอยู่ใน set ที่กำหนดcol %chin% set

    ตัวอย่าง:

    ใช้ %between% เพื่อกรองข้อมูลที่มีระยะทางบินระหว่าง 500 ถึง 1,000 miles:

    # Filter using %between%
    flights[distance %between% c(500, 1000)]
    

    ผลลัพธ์:

            year month   day dep_delay arr_delay carrier origin   dest air_time distance  hour
           <int> <int> <int>     <int>     <int>  <char> <char> <char>    <int>    <int> <int>
        1:  2014     1     1        18        69      AA    JFK    ORD      155      740    17
        2:  2014     1     1        -7        -6      AA    LGA    ORD      142      733     5
        3:  2014     1     1        -7         0      AA    LGA    ORD      143      733     6
        4:  2014     1     1        -8       -17      AA    LGA    ORD      139      733     6
        5:  2014     1     1        -2        15      AA    LGA    ORD      145      733     7
       ---                                                                                    
    79754:  2014    10    31        10        -5      UA    EWR    ORD      110      719     6
    79755:  2014    10    31         5         2      UA    EWR    ORD      132      719    10
    79756:  2014    10    31       427       393      UA    EWR    ORD      100      719    21
    79757:  2014    10    31        -4        15      MQ    LGA    DTW       75      502    11
    79758:  2014    10    31        -5         1      MQ    LGA    SDF      110      659     8
    

    Note: code นี้ให้ผลลัพธ์เดียวกับการเขียน flights[distance >= 500 & distance <= 1000] แต่การใช้ %between% ทำให้ code สั้นและอ่านง่ายกว่า

    .

    ใช้ %like% เพื่อกรองข้อมูลที่สนามบินปลายทางขึ้นต้นด้วย “A” เช่น “ABQ”, “ACK”, “AGS”:

    # Filter using %like%
    flights[dest %like% "^A"]
    

    ผลลัพธ์:

            year month   day dep_delay arr_delay carrier origin   dest air_time distance  hour
           <int> <int> <int>     <int>     <int>  <char> <char> <char>    <int>    <int> <int>
        1:  2014     1     1        -1         1      AA    JFK    AUS      232     1521    17
        2:  2014     1     1        -5        16      B6    JFK    AUS      247     1521    20
        3:  2014     1     1        21        21      B6    JFK    AUS      237     1521     9
        4:  2014     1     1        10         4      B6    JFK    ABQ      280     1826    20
        5:  2014     1     1        10        10      DL    LGA    ATL      126      762    18
       ---                                                                                    
    15630:  2014    10    31        50        43      UA    EWR    ATL      113      746    15
    15631:  2014    10    31        -5       -38      UA    EWR    ATL      111      746     5
    15632:  2014    10    31        -5        -2      UA    EWR    AUS      211     1504    15
    15633:  2014    10    31        -9       -15      UA    EWR    ATL      119      746    11
    15634:  2014    10    31        11       -10      UA    EWR    ATL      109      746     8
    

    ใช้ %chin% เพื่อกรองข้อมูลที่สนามบินปลายทาง คือ ATL, LAX, หรือ ORD:

    # Filter using %chin%
    flights[dest %chin% c("ATL", "LAX", "ORD")]
    

    ผลลัพธ์:

            year month   day dep_delay arr_delay carrier origin   dest air_time distance  hour
           <int> <int> <int>     <int>     <int>  <char> <char> <char>    <int>    <int> <int>
        1:  2014     1     1        14        13      AA    JFK    LAX      359     2475     9
        2:  2014     1     1        -3        13      AA    JFK    LAX      363     2475    11
        3:  2014     1     1         2         9      AA    JFK    LAX      351     2475    19
        4:  2014     1     1         2         1      AA    JFK    LAX      350     2475    13
        5:  2014     1     1         4         0      AA    EWR    LAX      339     2454    18
       ---                                                                                    
    38827:  2014    10    31        10        -5      UA    EWR    ORD      110      719     6
    38828:  2014    10    31         3       -32      UA    EWR    LAX      320     2454    20
    38829:  2014    10    31         5         2      UA    EWR    ORD      132      719    10
    38830:  2014    10    31       427       393      UA    EWR    ORD      100      719    21
    38831:  2014    10    31        10       -27      UA    EWR    LAX      326     2454    10
    

    .

    3️⃣ Sort

    สุดท้าย เราสามารถใช้ i เพื่อเรียงลำดับข้อมูลได้ 3 แบบ:

    1. Sort ascending (A—Z)
    2. Sort descending (Z—A)
    3. Sort by multiple columns

    .

    แบบที่ #1 – Sort ascending

    เช่น จัดเรียงตามชื่อสนามบินต้นทาง จาก A—Z:

    # Sort ascending
    flights[order(origin)]
    

    ผลลัพธ์:

             year month   day dep_delay arr_delay carrier origin   dest air_time distance  hour
            <int> <int> <int>     <int>     <int>  <char> <char> <char>    <int>    <int> <int>
         1:  2014     1     1         4         0      AA    EWR    LAX      339     2454    18
         2:  2014     1     1        -5       -17      AA    EWR    MIA      161     1085    16
         3:  2014     1     1       191       185      AA    EWR    DFW      214     1372    16
         4:  2014     1     1        -1        -2      AA    EWR    DFW      214     1372    14
         5:  2014     1     1        -3       -10      AA    EWR    MIA      154     1085     6
        ---                                                                                    
    253312:  2014    10    31        24        -5      UA    LGA    IAH      198     1416     6
    253313:  2014    10    31         1       -30      UA    LGA    IAH      201     1416    14
    253314:  2014    10    31        -8        16      MQ    LGA    RDU       83      431    11
    253315:  2014    10    31        -4        15      MQ    LGA    DTW       75      502    11
    253316:  2014    10    31        -5         1      MQ    LGA    SDF      110      659     8
    

    .

    แบบที่ #2 – Sorting descending

    เราเรียงข้อมูลแบบ descending (Z—A) ได้ 2 วิธี:

    1. ใช้ decreasing = TRUE
    2. ใช้ -

    เช่น จัดเรียงตามชื่อสนามบินต้นทาง จาก Z-A โดยใช้ decreasing = TRUE:

    # Sort descending with decreasing = TRUE
    flights[order(origin, decreasing = TRUE)]
    

    หรือโดยใช้ -:

    # Sort descending with -
    flights[order(-origin)]
    

    เราจะได้ผลลัพธ์แบบเดียวกัน:

             year month   day dep_delay arr_delay carrier origin   dest air_time distance  hour
            <int> <int> <int>     <int>     <int>  <char> <char> <char>    <int>    <int> <int>
         1:  2014     1     1        -8       -26      AA    LGA    PBI      157     1035     7
         2:  2014     1     1        -7        -6      AA    LGA    ORD      142      733     5
         3:  2014     1     1        -7         0      AA    LGA    ORD      143      733     6
         4:  2014     1     1        -8       -17      AA    LGA    ORD      139      733     6
         5:  2014     1     1        -2        15      AA    LGA    ORD      145      733     7
        ---                                                                                    
    253312:  2014    10    31        41        19      UA    EWR    SFO      344     2565    12
    253313:  2014    10    31       427       393      UA    EWR    ORD      100      719    21
    253314:  2014    10    31        10       -27      UA    EWR    LAX      326     2454    10
    253315:  2014    10    31        18       -14      UA    EWR    LAS      291     2227    16
    253316:  2014    10    31        -5       -14      UA    EWR    IAH      189     1400     8
    

    .

    แบบที่ #3 – Sort by multiple columns

    เช่น จัดเรียงตามชื่อสนามบินต้นทางและปลายทาง ตามลำดับ:

    # Sort by multiple columns
    flights[order(origin, dest)]
    

    ผลลัพธ์:

             year month   day dep_delay arr_delay carrier origin   dest air_time distance  hour
            <int> <int> <int>     <int>     <int>  <char> <char> <char>    <int>    <int> <int>
         1:  2014     1     2        -2       -25      EV    EWR    ALB       30      143     7
         2:  2014     1     3        88        79      EV    EWR    ALB       29      143    23
         3:  2014     1     4       220       211      EV    EWR    ALB       32      143    15
         4:  2014     1     4        35        19      EV    EWR    ALB       32      143     7
         5:  2014     1     5        47        42      EV    EWR    ALB       26      143     8
        ---                                                                                    
    253312:  2014    10    29         0         9      MQ    LGA    XNA      174     1147     6
    253313:  2014    10    29        -5       -16      MQ    LGA    XNA      162     1147    14
    253314:  2014    10    30        -4       -23      MQ    LGA    XNA      154     1147     6
    253315:  2014    10    30        -7       -11      MQ    LGA    XNA      157     1147    14
    253316:  2014    10    31        -5       -11      MQ    LGA    XNA      165     1147     6
    

    🧮 2nd Argument: j

    เราสามารถใช้ j เพื่อทำงานได้ 3 อย่าง ได้แก่:

    1. Select columns: เลือก columns ที่ต้องการ
    2. Compute: วิเคราะห์ข้อมูล
    3. Create columns: สร้าง columns ใหม่

    .

    1️⃣ Select Columns

    เราสามารถใช้ j เพื่อเลือก columns ได้ 3 แบบ:

    1. เลือก 1 column
    2. เลือกหลาย columns
    3. คัด columns ที่ไม่ต้องการออก

    .

    แบบที่ #1 – เลือก 1 column

    เช่น เลือก column สนามบินต้นทาง:

    # Select a column
    flights[, "origin"]
    

    ผลลัพธ์:

            origin
            <char>
         1:    JFK
         2:    JFK
         3:    JFK
         4:    LGA
         5:    JFK
        ---       
    253312:    LGA
    253313:    EWR
    253314:    LGA
    253315:    LGA
    253316:    LGA
    

    Note: เราสามารถใช้ตำแหน่ง (1, 2, 3, …) แทนชื่อ columns ("origin") ได้ แต่ไม่เป็นที่นิยม เพราะ columns อาจขยับตำแหน่งได้ และทำให้ผลลัพธ์เปลี่ยนไปได้

    .

    แบบที่ #2 – เลือกหลาย columns

    เราใช้ j เพื่อเลือกหลาย columns ได้ 3 วิธี:

    1. Vector
    2. List หรือ .()
    3. ..

    เช่น เลือก 3 columns คือ:

    • สนามบินต้นทาง
    • สนามบินปลายทาง
    • ระยะเวลาบิน

    โดยใช้ vector:

    # Select multiple columns with a vector
    flights[, c("origin", "dest", "air_time")]
    

    ผลลัพธ์:

            origin   dest air_time
            <char> <char>    <int>
         1:    JFK    LAX      359
         2:    JFK    LAX      363
         3:    JFK    LAX      351
         4:    LGA    PBI      157
         5:    JFK    LAX      350
        ---                       
    253312:    LGA    IAH      201
    253313:    EWR    IAH      189
    253314:    LGA    RDU       83
    253315:    LGA    DTW       75
    253316:    LGA    SDF      110
    

    โดยใช้ list:

    # Select multiple columns with a list
    flights[, list(origin, dest, air_time)]
    

    หรือใช้ .() ซึ่งเป็น shorthand สำหรับ list:

    # Select multiple columns using .()
    flights[, .(origin, dest, air_time)]
    

    ผลลัพธ์:

            origin   dest air_time
            <char> <char>    <int>
         1:    JFK    LAX      359
         2:    JFK    LAX      363
         3:    JFK    LAX      351
         4:    LGA    PBI      157
         5:    JFK    LAX      350
        ---                       
    253312:    LGA    IAH      201
    253313:    EWR    IAH      189
    253314:    LGA    RDU       83
    253315:    LGA    DTW       75
    253316:    LGA    SDF      110
    

    โดยใช้ .. ซึ่งเรามักใช้วิธีนี้เมื่อต้องการเลือก columns แบบ dynamic:

    # Select multiple columns using ..
    
    ## Create a vector of column names
    cols <- c("origin", "dest", "air_time")
    
    ## Select using ..
    flights[, ..cols]
    

    ผลลัพธ์:

            origin   dest air_time
            <char> <char>    <int>
         1:    JFK    LAX      359
         2:    JFK    LAX      363
         3:    JFK    LAX      351
         4:    LGA    PBI      157
         5:    JFK    LAX      350
        ---                       
    253312:    LGA    IAH      201
    253313:    EWR    IAH      189
    253314:    LGA    RDU       83
    253315:    LGA    DTW       75
    253316:    LGA    SDF      110
    

    Note: ความแตกต่างระหว่าง vector และ list หรือ .() และ .. คือ:

    • vector ให้ผลลัพธ์ที่เป็น vector
    • List หรือ .() และ .. ให้ผลลัพธ์เป็น data.table (data frame ของ data.table)

    .

    แบบที่ #3 – คัด columns ที่ไม่ต้องการออก

    เราสามารถคัด columns ที่ไม่ต้องการออกได้ 2 วิธี:

    1. ใช้ -
    2. ใช้ !

    เช่น เอาชื่อสายการบินออก โดยใช้ -:

    # Deselect a column using -
    flights[, -c("carrier")]
    

    หรือใช้ !:

    # Deselect a column using !
    flights[, !c("carrier")]
    

    ผลลัพธ์:

             year month   day dep_delay arr_delay origin   dest air_time distance  hour
            <int> <int> <int>     <int>     <int> <char> <char>    <int>    <int> <int>
         1:  2014     1     1        14        13    JFK    LAX      359     2475     9
         2:  2014     1     1        -3        13    JFK    LAX      363     2475    11
         3:  2014     1     1         2         9    JFK    LAX      351     2475    19
         4:  2014     1     1        -8       -26    LGA    PBI      157     1035     7
         5:  2014     1     1         2         1    JFK    LAX      350     2475    13
        ---                                                                            
    253312:  2014    10    31         1       -30    LGA    IAH      201     1416    14
    253313:  2014    10    31        -5       -14    EWR    IAH      189     1400     8
    253314:  2014    10    31        -8        16    LGA    RDU       83      431    11
    253315:  2014    10    31        -4        15    LGA    DTW       75      502    11
    253316:  2014    10    31        -5         1    LGA    SDF      110      659     8
    

    .

    2️⃣ Compute

    นอกจากการเลือก columns เรายังสามารถใช้ j เพื่อวิเคราะห์หรือข้อมูล (summarise, aggregate) ได้

    เช่น หาค่าเฉลี่ยของระยะเวลาบิน:

    # Calculate mean
    flights[, mean(air_time)]
    

    ผลลัพธ์:

    [1] 156.7228
    

    หรือ หาค่าเฉลี่ย และ standard deviation (SD) ของระยะเวลาบิน:

    # Calculate mean and SD
    flights[, .(avg_air_time = mean(air_time),
                sd_air_time = sd(air_time))]
    

    ผลลัพธ์:

       avg_air_time sd_air_time      n
              <num>       <num>  <int>
    1:     156.7228    96.12978 253316
    

    Note: เราสามารถวิเคราะห์ข้อมูลโดยไม่ตั้งชื่อให้กับผลลัพธ์ได้ (avg_air_time, sd_air_time, n) แต่การตั้งชื่อจะช่วยให้เราอ่าน output ได้ง่ายขึ้น

    .

    3️⃣ Create Columns

    สุดท้าย เราสามารถใช้ j สร้าง columns ใหม่ได้ร่วมกับ:

    1. := สำหรับสร้าง 1 column
    2. `:=` สำหรับสร้างหลาย columns

    เช่น สร้าง column ความเร็วในการบิน (ระยะทาง / เวลา) ด้วย :=:

    # Creating 1 new column
    flights[, speed := distance / (air_time / 60)]
    

    ผลลัพธ์:

        year month   day dep_delay arr_delay carrier origin   dest air_time distance  hour    speed
       <int> <int> <int>     <int>     <int>  <char> <char> <char>    <int>    <int> <int>    <num>
    1:  2014     1     1        14        13      AA    JFK    LAX      359     2475     9 413.6490
    2:  2014     1     1        -3        13      AA    JFK    LAX      363     2475    11 409.0909
    3:  2014     1     1         2         9      AA    JFK    LAX      351     2475    19 423.0769
    4:  2014     1     1        -8       -26      AA    LGA    PBI      157     1035     7 395.5414
    5:  2014     1     1         2         1      AA    JFK    LAX      350     2475    13 424.2857
    6:  2014     1     1         4         0      AA    EWR    LAX      339     2454    18 434.3363
    

    Note:

    • เราหาร air_time ด้วย 60 เพื่อแปลงหน่วยจากนาทีเป็นชั่วโมง และทำให้ผลลัพธ์ที่ได้เป็นหน่วย miles/hour
    • สังเกตว่า column ใหม่จะอยู่ท้ายสุดของ data.table

    หรือ สร้าง 2 columns พร้อมกัน เช่น:

    • ความเร็วในการบิน (ระยะทาง / เวลา)
    • ระยะเวลาที่ delay โดยรวม (delay ขาออก + delay ขาเข้า)

    ด้วย `:=`:

    # Creating multiple new column
    flights[, `:=`(speed = distance / (air_time / 60),
                   total_delay = dep_delay + arr_delay)]
    

    ผลลัพธ์:

        year month   day dep_delay arr_delay carrier origin   dest air_time distance  hour    speed total_delay
       <int> <int> <int>     <int>     <int>  <char> <char> <char>    <int>    <int> <int>    <num>       <int>
    1:  2014     1     1        14        13      AA    JFK    LAX      359     2475     9 413.6490          27
    2:  2014     1     1        -3        13      AA    JFK    LAX      363     2475    11 409.0909          10
    3:  2014     1     1         2         9      AA    JFK    LAX      351     2475    19 423.0769          11
    4:  2014     1     1        -8       -26      AA    LGA    PBI      157     1035     7 395.5414         -34
    5:  2014     1     1         2         1      AA    JFK    LAX      350     2475    13 424.2857           3
    6:  2014     1     1         4         0      AA    EWR    LAX      339     2454    18 434.3363           4
    

    🤝 3rd Argument: by

    เราใช้ by เพื่อจับกลุ่มข้อมูล ซึ่งมีประโยชน์มากเวลาที่เราต้องการวิเคราะห์ข้อมูลเป็น ๆ กลุ่ม

    เราสามารถใช้ by ได้ 2 แบบ:

    1. จับกลุ่มด้วย 1 column
    2. จับกลุ่มด้วยหลาย columns

    .

    แบบที่ #1 – จับกลุ่มด้วย 1 column

    เช่น หาค่าเฉลี่ยของ delay ขาออก ตามชื่อสนามบินต้นทาง:

    # Group by 1 column
    flights[, mean(dep_delay), by = origin]
    

    ผลลัพธ์:

       origin       V1
       <char>    <num>
    1:    JFK 11.44617
    2:    LGA 10.60500
    3:    EWR 15.21248
    

    .

    แบบที่ #2 – จับกลุ่มด้วยหลาย columns

    เราจับกลุ่มด้วยหลาย columns ได้ด้วย 2 วิธี คือ:

    1. Vector
    2. List หรือ .()

    เช่น หาค่าเฉลี่ยของ delay ขาออก โดยจับกลุ่มตามชื่อสนามบินต้นทางและปลายทาง ตามลำดับ

    วิธีที่ 1. ใช้ vector:

    # Group by with a vector
    flights[, mean(dep_delay), by = c("origin", "dest")]
    

    ผลลัพธ์:

         origin   dest        V1
         <char> <char>     <num>
      1:    JFK    LAX  8.359718
      2:    LGA    PBI 10.168617
      3:    EWR    LAX 15.882631
      4:    JFK    MIA 10.008364
      5:    JFK    SEA 10.858953
     ---                        
    217:    LGA    AVL -6.500000
    218:    LGA    GSP  6.000000
    219:    LGA    SBN  5.000000
    220:    EWR    SBN -1.500000
    221:    LGA    DAL -6.266667
    

    วิธีที่ 2. ใช้ list:

    # Group by with a list
    flights[, mean(dep_delay), by = list(origin, dest)]
    

    หรือใช้ .():

    # Group by with .()
    flights[, mean(dep_delay), by = .(origin, dest)]
    

    ผลลัพธ์:

         origin   dest        V1
         <char> <char>     <num>
      1:    JFK    LAX  8.359718
      2:    LGA    PBI 10.168617
      3:    EWR    LAX 15.882631
      4:    JFK    MIA 10.008364
      5:    JFK    SEA 10.858953
     ---                        
    217:    LGA    AVL -6.500000
    218:    LGA    GSP  6.000000
    219:    LGA    SBN  5.000000
    220:    EWR    SBN -1.500000
    221:    LGA    DAL -6.266667
    

    Note: เช่นเดียวกับการเลือก columns …

    • ถ้าเราใช้ vector เราจะได้ผลลัพธ์เป็น vector
    • ถ้าใช้ list หรือ .() เราจะได้ data.table

    🔗 Combining & Chaining

    เราสามารถปลอดล็อกพลังที่แท้จริงของ data.table ได้ด้วย 2 วิธี:

    1. Combining: ใช้ i, j, by ร่วมกัน เพื่อตอบโจทย์ที่ซับซ้อน
    2. Chaining: เชื่อมต่อ data.table เข้าด้วยกัน

    .

    1️⃣ Combining

    ยกตัวอย่างเช่น:

    • หาค่าเฉลี่ยของความเร็ว
    • เฉพาะเที่ยวบินที่มีระยะทางตั้งแต่ 500 miles ขึ้นไป
    • โดยจับกลุ่มตามชื่อสนามบินต้นทาง:
    # Combining
    flights[distance >= 500, 
            .(avg_speed = mean(distance / (air_time / 60))), 
            by = origin]
    

    อธิบาย code:

    • distance >= 500 เลือกเฉพาะข้อมูลที่มีระยะทางตั้งแต่ 500 miles ขึ้นไป
    • .(avg_speed = mean(distance / (air_time / 60))) หาค่าเฉลี่ยของความเร็ว
    • by = origin] จับกลุ่มข้อมูลด้วยสนามบินต้นทาง

    ผลลัพธ์:

       origin avg_speed
       <char>     <num>
    1:    JFK  436.6284
    2:    LGA  407.5462
    3:    EWR  417.1765
    

    .

    2️⃣ Chaining

    Chaining คือ การนำ code มาต่อกัน เพื่อส่ง output ต่อกันเป็นทอด ๆ:

    DT[...][...][...]

    เช่น ค้นหาสนามบินปลายทาง 5 อันดับแรกที่มีค่าเฉลี่ย delay ขาเข้ามากที่สุด ในเดือนสิงหาคม:

    # Chaining
    flights[month == 8,
            .(avg_arr_delay = mean(arr_delay)),
            by = dest][order(-avg_arr_delay)][1:5]
    

    อธิบาย code:

    • month == 8 เลือกข้อมูลจากเดือนสิงหาคม
    • .(avg_arr_delay = mean(arr_delay)) คำนวณค่าเฉลี่ย delay ขาเข้า
    • by = dest จับกลุ่มตามสนามบินปลายทาง
    • [order(-avg_arr_delay)] จัดลำดับตามค่าเฉลี่ย delay ขาเข้า แบบ descending
    • [1:5] เลือกเฉพาะ 5 rows แรกมาแสดง

    ผลลัพธ์:

         dest avg_arr_delay
       <char>         <num>
    1:    LIT      37.06452
    2:    DSM      22.85714
    3:    CAK      19.60976
    4:    TYS      19.44681
    5:    TVC      19.00000
    

    🍩 Special Symbols

    เพื่อช่วยให้เราทำงานได้ง่ายขึ้น data.table มี special symbols 3 ตัวที่เราสามารถเรียกใช้ในการทำงานได้:

    1. .N
    2. .SD
    3. .SDcols

    .

    1️⃣ .N

    .N เป็น special symbol ที่เก็บจำนวน rows ของ data.table เอาไว้ (เช่น 500)

    เรามักใช้งาน .N ใน 2 กรณีหลัก ๆ ได้แก่:

    1. เลือก rows
    2. นับจำนวนข้อมูล

    .

    กรณีที่ 1. เลือก rows

    เช่น เลือก row ที่ 500 จนถึง row สุดท้าย:

    # Select rows with .N
    flights[500:.N]
    

    ผลลัพธ์:

             year month   day dep_delay arr_delay carrier origin   dest air_time distance  hour
            <int> <int> <int>     <int>     <int>  <char> <char> <char>    <int>    <int> <int>
         1:  2014     1     1        81        86      WN    EWR    HOU      222     1411    17
         2:  2014     1     1        -3        -4      WN    EWR    MDW      128      711     7
         3:  2014     1     1         0        22      WN    EWR    MDW      144      711    12
         4:  2014     1     1        88       190      WN    EWR    MDW      130      711    21
         5:  2014     1     1        45        63      WN    EWR    MDW      141      711    16
        ---                                                                                    
    252813:  2014    10    31         1       -30      UA    LGA    IAH      201     1416    14
    252814:  2014    10    31        -5       -14      UA    EWR    IAH      189     1400     8
    252815:  2014    10    31        -8        16      MQ    LGA    RDU       83      431    11
    252816:  2014    10    31        -4        15      MQ    LGA    DTW       75      502    11
    252817:  2014    10    31        -5         1      MQ    LGA    SDF      110      659     8
    

    .

    กรณีที่ 2. นับจำนวนข้อมูล

    เช่น นับจำนวนข้อมูลการบินตามสนามบินต้นทางแต่ละแห่ง:

    # Compute with .N
    flights[, .N, by = origin]
    

    ผลลัพธ์:

       origin     N
       <char> <int>
    1:    JFK 81483
    2:    LGA 84433
    3:    EWR 87400
    

    .

    2️⃣ .SD

    .SD ย่อมาจาก “Subset of Data” ซึ่งหมายถึง ชุดข้อมูลย่อยที่เกิดจากการจับกลุ่มด้วย by

    เรามักใช้ .SD ในการคำนวณคู่กับ lapply() function เพื่อวิเคราะห์ข้อมูลตามกลุ่ม

    เช่น หาค่าสูงสุดของแต่ละ columns ในแต่ละเดือน:

    # Compute with .SD
    flights[,
            lapply(.SD, max, na.rm = TRUE),
            by = month]
    

    ผลลัพธ์:

        month  year   day dep_delay arr_delay carrier origin   dest air_time distance  hour
        <int> <int> <int>     <int>     <int>  <char> <char> <char>    <int>    <int> <int>
     1:     1  2014    31       973       996      WN    LGA    XNA      688     4983    24
     2:     2  2014    28      1014      1007      WN    LGA    XNA      685     4983    24
     3:     3  2014    31       920       925      WN    LGA    XNA      706     4983    24
     4:     4  2014    30      1241      1223      WN    LGA    XNA      664     4983    24
     5:     5  2014    31       889       879      WN    LGA    XNA      650     4983    24
     6:     6  2014    30      1071      1073      WN    LGA    XNA      640     4983    24
     7:     7  2014    31      1087      1090      WN    LGA    XNA      638     4983    24
     8:     8  2014    31       978       964      WN    LGA    XNA      635     4983    24
     9:     9  2014    30      1056      1115      WN    LGA    XNA      635     4983    23
    10:    10  2014    31      1498      1494      WN    LGA    XNA      662     4983    24
    

    .

    3️⃣ .SDcols

    .SDcols เป็น special symbol ที่เก็บชื่อ columns ของ .SD เอาไว้

    เรามักใช้ .SDcols คู่กับ .SD และ lapply() เพื่อวิเคราะห์เฉพาะ columns ที่ต้องการ

    เช่น หาเวลา delay สูงสุดของขาเข้าและขาออกในแต่ละเดือน:

    # Compute with .SDcols
    flights[,
            lapply(.SD, max, na.rm = TRUE),
            by = month,
            .SDcols = c("arr_delay", "dep_delay")]
    

    ผลลัพธ์:

        month arr_delay dep_delay
        <int>     <int>     <int>
     1:     1       996       973
     2:     2      1007      1014
     3:     3       925       920
     4:     4      1223      1241
     5:     5       879       889
     6:     6      1073      1071
     7:     7      1090      1087
     8:     8       964       978
     9:     9      1115      1056
    10:    10      1494      1498
    

    😎 Conclusion

    ในบทความนี้ เราได้ไปดูวิธีใช้ data.table เพื่อทำทำงานกับข้อมูลขนาดใหญ่กัน

    เราได้เห็นว่า data.table มีหลักการเขียนดังนี้:

    DT[i, j, by]

    และแต่ละ argument มีการใช้งานดังนี้:

    .

    Argument i:

    Use CaseExample
    Select rowsflights[1:5]
    Filterflights[distance >= 500]
    Sortflights[order(origin)]

    .

    Argument j:

    Use CaseExample
    Select columnsflights[, .(origin, dest)]
    Computeflights[, mean(air_time)]
    Create columnsflights[, speed := distance / (air_time / 60)]

    .

    Argument by:

    Use CaseExample
    Group dataflights[by = origin]

    .

    Special symbols:

    SymbolMeaning
    .Nจำนวน rows
    .SDSubset of Data
    .SDcolscolumns ใน Subset of Data

    .

    เราสามารถใช้ทุก arguments ร่วมกัน (combining) หรือเชื่อมต่อ data.table (chaining) เพื่อตอบโจทย์ที่ซับซ้อนได้


    🎒 Learn More About data.table

    .

    😺 GitHub

    ดู code ตัวอย่างทั้งหมดในบทความนี้ได้ที่ GitHub

    .

    📚 อ่านเพิ่มเติมเกี่ยวกับ data.table

    .

    📑 Cheat Sheets ในการใช้งาน data.table


    📃 References


    ✅ R Book for Psychologists: หนังสือภาษา R สำหรับนักจิตวิทยา

    📕 ขอฝากหนังสือเล่มแรกในชีวิตด้วยนะครับ 😆

    🙋 ใครที่กำลังเรียนจิตวิทยาหรือทำงานสายจิตวิทยา และเบื่อที่ต้องใช้ software ราคาแพงอย่าง SPSS และ Excel เพื่อทำข้อมูล

    💪 ผมขอแนะนำ R Book for Psychologists หนังสือสอนใช้ภาษา R เพื่อการวิเคราะห์ข้อมูลทางจิตวิทยา ที่เขียนมาเพื่อนักจิตวิทยาที่ไม่เคยมีประสบการณ์เขียน code มาก่อน

    ในหนังสือ เราจะปูพื้นฐานภาษา R และพาไปดูวิธีวิเคราะห์สถิติที่ใช้บ่อยกัน เช่น:

    • Correlation
    • t-tests
    • ANOVA
    • Reliability
    • Factor analysis

    🚀 เมื่ออ่านและทำตามตัวอย่างใน R Book for Psychologists ทุกคนจะไม่ต้องพึง SPSS และ Excel ในการทำงานอีกต่อไป และสามารถวิเคราะห์ข้อมูลด้วยตัวเองได้ด้วยความมั่นใจ

    แล้วทุกคนจะแปลกใจว่า ทำไมภาษา R ง่ายขนาดนี้ 🙂‍↕️

    👉 สนใจดูรายละเอียดหนังสือได้ที่ meb: