Category: Data analytics

  • Basic LangChain: วิธีใช้ LangChain เพื่อทำงานกับ LLM อย่างง่าย ใน 5 ขั้นตอน—ตัวอย่างการสร้าง AI ตอบคำถามเรื่อง Mental Model

    Basic LangChain: วิธีใช้ LangChain เพื่อทำงานกับ LLM อย่างง่าย ใน 5 ขั้นตอน—ตัวอย่างการสร้าง AI ตอบคำถามเรื่อง Mental Model

    langchain เป็น framework สำหรับสร้างแอปพลิเคชั่นที่ใช้ large language model (LLM) ที่ช่วยลดความยุ่งยากการเรียกใช้งาน API โดยตรง

    langchain มีข้อดี 3 อย่าง:

    1. Modular: ใช้งานง่าย ด้วยการเขียนเป็นส่วน ๆ หรือ module (เหมือนเลโก้)
    2. Use case: รองรับการใช้งานหลายหลาก เพราะสามารถประกอบ module เข้าด้วยกันได้หลายแบบ (ต่อเลโก้ได้หลายแบบ)
    3. Integration: ใช้งานร่วมเครื่องมือได้กับหลากหลาย เช่น OpenAI, Hugging Face, databricks

    ในบทความนี้ เรามาดูวิธีใช้ langchain เพื่อทำงานกับ LLM อย่างง่ายกัน

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


    1. 🧠 Mental Model
    2. 🤖 Step 1. Set LLM
    3. 💬 Step 2. Set Prompt
    4. 📦 Step 3. Set Output Structure
    5. ⛓️‍💥 Step 4. Chain
    6. 🏃 Step 5. Run
      1. ☝️ Single Run
      2. 🎳 Batch Run
    7. 💪 Summary
    8. 🫵 Your Turn
    9. 📄 References

    🧠 Mental Model

    การใช้งาน langchain มีอยู่ 5 ขั้นตอน ได้แก่:

    1. Set LLM: เลือก LLM ที่ต้องการ
    2. Set prompt: สร้าง prompt สำหรับคุยกับ LLM
    3. Set output structure: กำหนดหน้าตา output ที่ต้องการ
    4. Chain: เชื่อม LLM และ prompt เข้าด้วยกัน เพื่อสร้าง pipeline ในการเรียกใช้ LLM
    5. Run: เรียกใช้งาน LLM

    เราไปดูการใช้งาน ผ่านการสร้าง chatbot ตอบคำถามเกี่ยวกับ mental model กัน


    🤖 Step 1. Set LLM

    langchain รองรับการใช้งาน LLM หลายเจ้า เช่น:

    ในตัวอย่าง เราจะเลือกใช้ Gemini โดยเริ่มจากโหลด module สำหรับเชื่อมกับ Gemini:

    # Import package
    from langchain_google_genai import ChatGoogleGenerativeAI
    

    แล้วสร้าง LLM instance ขึ้นมา:

    # Create model instance
    llm = ChatGoogleGenerativeAI(
        model="gemini-2.5-flash",
        temperature=0.5,
        api_key="YOUR_API_KEY"
    )
    
    • model: ชื่อ LLM ที่เราต้องการใช้งาน
    • temperature: ระดับความสุ่มของคำตอบจาก LLM (ค่ายิ่งสูง คำตอบยิ่งมีความหลากหลาย ส่วนยิ่งค่าน้อย คำตอบจะยิ่งมีความคล้ายคลึงกัน)
    • api_key: API key สำหรับใช้งาน LLM (ดูวิธีการสร้าง Gemini API key ฟรี)

    💬 Step 2. Set Prompt

    ในขั้นที่ 2 เราจะสร้าง prompt สำหรับคุยกับ LLM กัน:

    1. โหลด module
    2. กำหนด prompt

    ขั้นย่อยที่ 1. โหลด module สำหรับสร้าง prompt:

    # Import package
    from langchain_core.prompts import ChatPromptTemplate
    

    ขั้นย่อยที่ 2. กำหนด prompt โดยแยกระหว่าง:

    1. System prompt: บทบาทและสไตล์การตอบคำถามของ LLM (เช่น ผู้เชี่ยวชาญด้าน mental model)
    2. User prompt: คำถามที่จะส่งให้ LLM (เช่น บอกให้อธิบาย mental model ที่ต้องการ)

    ตัวอย่าง system และ user prompts:

    # Define system prompt
    system_prompt = """
    You are an expert curator of mental models across science, philosophy, and applied reasoning.
    
    Your task is to explain mental models clearly and accurately using a fixed schema.
    
    If the origin of a model is unclear or debated, state that explicitly.
    
    Do not invent historical sources. Be concise and concrete.
    """
    
    # Define user prompt
    user_prompt = "Explain the following mental model: {model_query}"
    

    จากนั้น ประกอบ prompts เข้าด้วยกัน:

    # Create prompt template
    prompts = ChatPromptTemplate.from_messages(
        [
            # System prompt
            ("system", system_prompt.strip()),
    
            # User prompt
            ("human", user_prompt)
        ]
    )
    

    เราสามารถดูตัวอย่าง prompt ได้ด้วย .format_messages():

    # Inspect prompt template
    prompts.format_messages(model_query="Pareto Principle")
    

    ผลลัพธ์:

    [SystemMessage(content='You are an expert curator of mental models across science, philosophy, and applied reasoning.\\n\\nYour task is to explain mental models clearly and accurately using a fixed schema.\\n\\nIf the origin of a model is unclear or debated, state that explicitly.\\n\\nDo not invent historical sources. Be concise and concrete.', additional_kwargs={}, response_metadata={}),
     HumanMessage(content='Explain the following mental model: Pareto Princinple', additional_kwargs={}, response_metadata={})]
    

    📦 Step 3. Set Output Structure

    ในขั้นที่ 3 เราจะกำหนดหน้าตา output ที่เราต้องการ

    เช่น ถ้าเราต้องการให้คืนค่า JSON แบบนี้:

    {
    "model_name": "",
    "origin": "",
    "description": "",
    "example": "",
    "tags": []
    }

    เรากำหนดได้โดยใช้ pydantic และ typing packages แบบนี้:

    # Import packages
    from pydantic import BaseModel, Field
    from typing import List, Literal
    
    # Define output structure
    class MentalModel(BaseModel):
    
        # Mental model name
        model_name: str = Field(description="The commonly accepted name of the mental model")
    
        # Source/origin
        origin: str = Field(
            description="Where the model comes from (person, book, field, or cultural origin)"
        )
    
        # Brief description
        description: str = Field(
            description="A brief explanation of what the mental model is and why it matters"
        )
    
        # Example
        example: str = Field(
            description="A concrete real-world example illustrating the mental model"
        )
    
        # Tags
        tags: List[str] = Field(
            description="Short tags such as decision-making, systems thinking, learning, philosophy"
        )
    

    Note: ดูวิธีใช้ Pydantic

    หลังกำหนดหน้าตา output แล้ว ให้ใส่เข้าไปใน LLM instance แบบนี้:

    # Add output structure to LLM
    llm_with_structured_output = llm.with_structured_output(MentalModel)
    

    ⛓️‍💥 Step 4. Chain

    ในขั้นที่ 4 ให้เราสร้าง chain โดยเชื่อม LLM instance เข้ากับ prompts ด้วย pipe operator (|):

    # Build chain
    chain = prompts | llm_with_structured_output
    

    Note: ให้มองว่า | เป็นลูกศรชี้ทางขวา (prompt → llm)


    🏃 Step 5. Run

    ในขั้นสุดท้าย เราจะเรียกใช้งาน chain ซึ่งทำได้ 2 แบบ:

    1. Single run: เรียกใช้ครั้งเดียว
    2. Batch run: เรียกใช้หลายครั้งพร้อมกัน

    .

    ☝️ Single Run

    เราเรียกใช้งานครั้งเดียวด้วย .invoke()

    ในตัวอย่าง เราจะถามเกี่ยวกับ “compound interest” กัน:

    # Run query
    result = chain.invoke({"model_query": "Compound Interest"})
    

    แสดงผลลัพธ์ใน console:

    # Import package
    import json
    
    # Load result
    result_dict = result.model_dump()
    
    # Print
    print(json.dumps(result_dict, indent=4))
    

    ผลลัพธ์:

    {
        "model_name": "Compound Interest",
        "origin": "Finance, Mathematics; concept dates back to ancient times, formalized in the Renaissance.",
        "description": "Compound interest is the interest on a loan or deposit calculated based on both the initial principal and the accumulated interest from previous periods. It is often called 'interest on interest' and leads to exponential growth over time, making it a powerful force in finance for both wealth creation and debt accumulation.",
        "example": "If you invest $1,000 at an annual interest rate of 5% compounded annually, after the first year you'll have $1,050. In the second year, the 5% interest is calculated on $1,050, not just the original $1,000, leading to a balance of $1,102.50. This snowball effect accelerates over decades, significantly increasing the total return compared to simple interest.",
        "tags": [
            "Finance",
            "Economics",
            "Wealth Building",
            "Decision-making",
            "Long-term thinking"
        ]
    }
    

    .

    🎳 Batch Run

    สำหรับการรันหลายครั้งพร้อมกัน เราจะใช้ .batch() แบบนี้:

    # Create list of mental models
    mental_model_queries = [
        "First Principles Thinking",
        "Occam's Razor",
        "Confirmation Bias"
    ]
    
    # Create batch inputs
    batch_inputs = [{"model_query": query} for query in mental_model_queries]
    
    # Run queries
    results = chain.batch(batch_inputs)
    
    # Instantiate collector
    query_collector = [result.model_dump() for result in results]
    

    แสดงผลลัพธ์ใน console:

    # Instantiate counter
    i = 1
    
    # Loop through elements in collector
    for result in query_collector:
    
        # Print result
        print(f"👉 Query {i}:")
        print(json.dumps(result, indent=4))
        print("\\n")
    
        # Add 1 to counter
        i += 1
    

    ผลลัพธ์:

    👉 Query 1:
    {
        "model_name": "First Principles Thinking",
        "origin": "Often attributed to Aristotle; popularized in modern business by Elon Musk.",
        "description": "First Principles Thinking involves breaking down complex problems into their most basic, fundamental truths or 'first principles,' rather than reasoning by analogy or conventional wisdom. It matters because it allows for innovative solutions by challenging assumptions and building new knowledge from the ground up.",
        "example": "Instead of accepting the high cost of batteries for electric cars, Elon Musk famously broke down a battery into its constituent raw materials (cobalt, nickel, lithium, etc.) to understand their actual cost, then sought ways to procure and assemble them more efficiently, leading to significant cost reductions and innovation.",
        "tags": [
            "Problem-solving",
            "Innovation",
            "Critical Thinking",
            "Decision-making"
        ]
    }
    
    👉 Query 2:
    {
        "model_name": "Occam's Razor",
        "origin": "William of Ockham (14th-century philosopher and theologian)",
        "description": "Occam's Razor is a problem-solving principle stating that among competing hypotheses that explain an event or phenomenon equally well, the simplest solution is most likely the correct one. It advocates for parsimony, suggesting that one should not multiply entities beyond necessity, thereby favoring theories with fewer assumptions.",
        "example": "If you hear hoofbeats outside, it is more likely to be horses than zebras, assuming you are in a location where horses are common and zebras are not. The 'horse' explanation is simpler and requires fewer extraordinary assumptions.",
        "tags": [
            "Philosophy",
            "Decision-making",
            "Problem-solving",
            "Critical thinking",
            "Science"
        ]
    }
    
    👉 Query 3:
    {
        "model_name": "Confirmation Bias",
        "origin": "Psychology; early concepts traced to Francis Bacon's Novum Organum (1620)",
        "description": "Confirmation bias is the tendency to search for, interpret, favor, and recall information in a way that confirms one's pre-existing beliefs or hypotheses. It matters because it can lead to flawed reasoning, poor decision-making, and resistance to new or contradictory evidence, hindering objective analysis.",
        "example": "A person who believes a certain stock will perform well might selectively read news articles and analyst reports that support this positive outlook, while ignoring or downplaying any negative news or warnings about the company.",
        "tags": [
            "cognitive bias",
            "decision-making",
            "psychology",
            "critical thinking"
        ]
    }
    

    💪 Summary

    เราจะได้เห็นได้ว่า langchain เป็น package ที่ใช้ทำงานกับ LLM ได้อย่างง่าย ๆ ใน 5 ขั้นตอน:

    Set LLM: เลือก model
    Set prompt: กำหนด system และ user prompt
    Set output: กำหนด output structure
    Chain: สร้าง pipeline
    Run: เรียกใช้งาน (single & batch)

    🫵 Your Turn

    สำหรับคนที่สนใจศึกษา langchain เพิ่มเติม:


    📄 References

  • วิธีใช้ jsonlite เพื่อทำงานกับ JSON ในภาษา R: fromJSON(), toJSON(), read_json(), และ write_json() — ตัวอย่างการทำงานกับข้อมูลขนม

    วิธีใช้ jsonlite เพื่อทำงานกับ JSON ในภาษา R: fromJSON(), toJSON(), read_json(), และ write_json() — ตัวอย่างการทำงานกับข้อมูลขนม

    ในบทความนี้ เราจะไปดูวิธีการใช้ 4 functions จาก jsonlite package สำหรับทำงานกับ JSON (JavaScript Object Notation) ในภาษา R กัน:

    1. fromJSON()
    2. toJSON()
    3. read_json()
    4. write_json()

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


    1. 🤔 What Is JSON?
    2. 📦 What Is jsonlite?
    3. 🏁 Getting Started
    4. ⬇️ Function 1. fromJSON()
    5. ⬆️ Function 2. toJSON()
    6. 📖 Function 3. read_json()
    7. ✍️ Function 4. write_json()
    8. 💪 Summary
    9. 😺 GitHub
    10. 📃 References

    🤔 What Is JSON?

    JSON เป็นโครงสร้างข้อมูลที่พบได้บ่อยในระบบคอมพิวเตอร์และแอปพลิเคชันต่าง ๆ เพราะเป็นรูปแบบข้อมูลที่อ่านได้ง่ายทั้งคนและคอมพิวเตอร์

    ตัวอย่าง JSON ที่เก็บข้อมูลขนม:

    [
      {
        "snack_name": "Corn Chips",
        "brand": "Nibble & Dip",
        "price_usd": 2.99,
        "is_vegan": true
      },
      {
        "snack_name": "Pita Chips",
        "brand": "DipMates",
        "price_usd": 4.25,
        "is_vegan": false
      },
      {
        "snack_name": "Tortilla Chips",
        "brand": "Casa Crunch",
        "price_usd": 3.49,
        "is_vegan": true
      }
    ]
    

    Note: อ่านเพิ่มเติมเกี่ยวกับ JSON ได้ที่ What is JSON?


    📦 What Is jsonlite?

    jsonlite เป็น package ขนาดเบาสำหรับทำงานกับ JSON ในภาษา R และมี 4 functions หลักให้เรียกใช้งาน ได้แก่:

    1. fromJSON(): โหลด JSON string (character ที่มีข้อมูลแบบ JSON) เป็น R object (เช่น data frame)
    2. toJSON(): เปลี่ยน R object เป็น JSON string
    3. read_json(): โหลดไฟล์ JSON เป็น R object
    4. write_json(): เปลี่ยน R object เป็นไฟล์ JSON

    เราไปดูวิธีใช้ jsonlite และ 4 functions นี้กัน


    🏁 Getting Started

    ก่อนเริ่มใช้งาน jsonlite เราจะต้องทำ 2 อย่าง ได้แก่:

    1. ติดตั้ง package ด้วย install.packages() (ทำครั้งแรกครั้งเดียว)
    2. โหลด package ด้วย library() (ทำทุกครั้งที่เปิด session ใหม่)
    # Install jsonlite
    install.packages("jsonlite")
    
    # Load jsonlite
    library(jsonlite)
    

    ⬇️ Function 1. fromJSON()

    fromJSON() ใช้เปลี่ยน JSON ที่เป็นอยู่ใน character (JSON string) ให้เป็น R object เช่น list และ data frame

    เช่น เราสามารถเปลี่ยน JSON string แบบนี้:

    # Create a JSON string
    snacks_json_string <- '
    [
      {
        "snack_name": "Corn Chips",
        "brand": "Nibble & Dip",
        "price_usd": 2.99,
        "is_vegan": true
      },
      {
        "snack_name": "Pita Chips",
        "brand": "DipMates",
        "price_usd": 4.25,
        "is_vegan": false
      },
      {
        "snack_name": "Tortilla Chips",
        "brand": "Casa Crunch",
        "price_usd": 3.49,
        "is_vegan": true
      }
    ]
    '
    
    

    ให้เป็น R object ได้แบบนี้:

    # Convert to R object
    snacks_r_obj <- fromJSON(snacks_json_string)
    
    # View the df
    snacks_r_obj
    

    ผลลัพธ์:

          snack_name        brand price_usd is_vegan
    1     Corn Chips Nibble & Dip      2.99     TRUE
    2     Pita Chips     DipMates      4.25    FALSE
    3 Tortilla Chips  Casa Crunch      3.49     TRUE
    

    Note: fromJSON() จะเลือกประเภท R object ให้โดยอัตโนมัติ เช่น ถ้า JSON มีโครงสร้างคล้าย data frame (มีข้อมูลซ้ำ ๆ ที่ดูเหมือน rows และ columns) fromJSON() จะเปลี่ยน JSON string ให้เป็น data frame


    ⬆️ Function 2. toJSON()

    toJSON() ใช้เปลี่ยน R object ให้เป็น JSON string

    เช่น เปลี่ยน data frame นี้:

    # Create a data frame
    snacks_df <- data.frame(
      snack_name = c("Seaweed Thins", "Chickpea Puffs", "BBQ Potato Crisps"),
      brand      = c("OceanBite", "LegumeLab", "Spud & Spark"),
      price_usd  = c(2.45, 3.35, 3.10),
      is_vegan   = c(TRUE, TRUE, FALSE),
      stringsAsFactors = FALSE
    )
    

    ให้เป็น JSON string:

    # Convert to JSON string
    snacks_json_string <- toJSON(snacks_df)
    
    # View the JSON string
    snacks_json_string
    

    ผลลัพธ์:

    [{"snack_name":"Seaweed Thins","brand":"OceanBite","price_usd":2.45,"is_vegan":true},{"snack_name":"Chickpea Puffs","brand":"LegumeLab","price_usd":3.35,"is_vegan":true},{"snack_name":"BBQ Potato Crisps","brand":"Spud & Spark","price_usd":3.1,"is_vegan":false}]
    

    สังเกตว่า ผลลัพธ์ที่ได้มาอ่านยาก เพราะข้อมูลอยู่ในบรรทัดเดียวกันหมด

    ทั้งนี้ เราเปลี่ยนให้ผลลัพธ์อ่านง่ายขึ้นได้ โดยใช้ pretty argument แบบนี้:

    # Convert to JSON string (pretty)
    snacks_json_string_pretty <- toJSON(snacks_df,
    pretty = TRUE)
    # View the JSON string (pretty)
    snacks_json_string_pretty

    ผลลัพธ์:

    [
      {
        "snack_name": "Seaweed Thins",
        "brand": "OceanBite",
        "price_usd": 2.45,
        "is_vegan": true
      },
      {
        "snack_name": "Chickpea Puffs",
        "brand": "LegumeLab",
        "price_usd": 3.35,
        "is_vegan": true
      },
      {
        "snack_name": "BBQ Potato Crisps",
        "brand": "Spud & Spark",
        "price_usd": 3.1,
        "is_vegan": false
      }
    ]
    

    จะเห็นว่า ตอนนี้ JSON string อ่านง่ายกว่าก่อนหน้านี้มาก


    📖 Function 3. read_json()

    read_json() ใช้โหลดไฟล์ JSON เข้ามาใน R

    เช่น เรามีไฟล์ชื่อ snacks.json ที่มีข้อมูลแบบนี้:

    [
      {
        "snack_name": "Plantain Chips",
        "brand": "TropiBite",
        "price_usd": 3.15,
        "is_vegan": true
      },
      {
        "snack_name": "Rice Crackers",
        "brand": "ZenMunch",
        "price_usd": 2.25,
        "is_vegan": true
      },
      {
        "snack_name": "Pretzel Sticks",
        "brand": "Twist & Dip",
        "price_usd": 3.75,
        "is_vegan": true
      }
    ]
    

    เราสามารถโหลดเข้ามาใน R ด้วย read_json() ได้แบบนี้:

    # Read the JSON file
    snacks_from_json_file <- read_json("snacks.json")
    
    # View the result
    snacks_from_json_file
    

    ผลลัพธ์:

    [[1]]
    [[1]]$snack_name
    [1] "Plantain Chips"
    
    [[1]]$brand
    [1] "TropiBite"
    
    [[1]]$price_usd
    [1] 3.15
    
    [[1]]$is_vegan
    [1] TRUE
    
    [[2]]
    [[2]]$snack_name
    [1] "Rice Crackers"
    
    [[2]]$brand
    [1] "ZenMunch"
    
    [[2]]$price_usd
    [1] 2.25
    
    [[2]]$is_vegan
    [1] TRUE
    
    [[3]]
    [[3]]$snack_name
    [1] "Pretzel Sticks"
    
    [[3]]$brand
    [1] "Twist & Dip"
    
    [[3]]$price_usd
    [1] 3.75
    
    [[3]]$is_vegan
    [1] TRUE
    

    ทั้งนี้ read_json() มี simplifyVector argument ที่ช่วยโหลดข้อมูลที่เหมือน data frame ให้เป็น data frame (แทน list) ได้แบบนี้:

    # Read the JSON file (simplified)
    snacks_from_json_file_simplified <- read_json("snacks.json",
                                                  simplifyVector = TRUE)
    
    # View the result (simplified)
    snacks_from_json_file_simplified
    

    ผลลัพธ์:

          snack_name       brand price_usd is_vegan
    1 Plantain Chips   TropiBite      3.15     TRUE
    2  Rice Crackers    ZenMunch      2.25     TRUE
    3 Pretzel Sticks Twist & Dip      3.75     TRUE
    

    ✍️ Function 4. write_json()

    write_json() ใช้เปลี่ยน R object ให้เป็นไฟล์ JSON

    เช่น เปลี่ยน data frame นี้:

    # Create a list
    snacks_df <- data.frame(
      snack_name = c("Cassava Chips", "Lentil Crisps", "Cheese Puffs"),
      brand      = c("RootRush", "Pulse & Crunch", "CheezyPop"),
      price_usd  = c(2.85, 2.65, 3.99),
      is_vegan   = c(TRUE, TRUE, FALSE),
      stringsAsFactors = FALSE
    )
    

    ให้เป็นไฟล์ JSON แบบนี้:

    # Write to JSON
    write_json(snacks_df,
               "snacks_df.json")
    

    ผลลัพธ์:

    [{"snack_name":"Cassava Chips","brand":"RootRush","price_usd":2.85,"is_vegan":true},{"snack_name":"Lentil Crisps","brand":"Pulse & Crunch","price_usd":2.65,"is_vegan":true},{"snack_name":"Cheese Puffs","brand":"CheezyPop","price_usd":3.99,"is_vegan":false}]
    

    เช่นเดียวกับ toJSON(), write_json() มี pretty argument ที่ทำให้ผลลัพธ์อ่านง่ายขึ้นได้:

    # Write to JSON (pretty)
    write_json(snacks_df,
               "snacks_df_pretty.json", 
               pretty = TRUE)
    

    ผลลัพธ์:

    [
      {
        "snack_name": "Cassava Chips",
        "brand": "RootRush",
        "price_usd": 2.85,
        "is_vegan": true
      },
      {
        "snack_name": "Lentil Crisps",
        "brand": "Pulse & Crunch",
        "price_usd": 2.65,
        "is_vegan": true
      },
      {
        "snack_name": "Cheese Puffs",
        "brand": "CheezyPop",
        "price_usd": 3.99,
        "is_vegan": false
      }
    ]
    

    💪 Summary

    ในบทความนี้ เราได้ไปทำความรู้จักกับ 4 functions จาก jsonlite ซึ่งเป็น package สำหรับทำงานกับ JSON ในภาษา R:

    1. fromJSON(): JSON string → R object
    2. toJSON(): R object → JSON string
    3. read_json(): ไฟล์ JSON → R object
    4. write_json(): R object → JSON

    😺 GitHub

    ดูตัวอย่าง code และไฟล์ JSON ทั้งหมดในบทความนี้ได้ที่ GitHub


    📃 References

  • สรุป 5 keywords สำหรับ handle exceptions ใน Python: try, except, else, finally, raise — ตัวอย่างโค้ดการจ่ายเงินออนไลน์

    สรุป 5 keywords สำหรับ handle exceptions ใน Python: try, except, else, finally, raise — ตัวอย่างโค้ดการจ่ายเงินออนไลน์

    Exception หมายถึง error ที่เกิดขึ้นกับ code ที่มี syntax ถูกต้อง

    ยกตัวอย่างเช่น การหารเลขด้วย 0:

    print(5 / 0)
    

    ผลลัพธ์:

    ZeroDivisionError
    

    Exception สามารถทำให้ code หยุดทำงานหรือทำงานผิดพลาดได้

    ดังนั้น ในการเขียน code เราควรกำหนดวิธีในการจัดการกับ exception เพื่อป้องกันไม่ให้ code ทำงานผิดพลาด

    ใน Python เรามี 5 keywords สำหรับจัดการ exception ได้:

    1. try
    2. except
    3. else
    4. finally
    5. raise

    เราไปดูตัวอย่างการใช้งานทั้ง 5 keywords ผ่านตัวอย่าง code การจ่ายเงินออนไลน์กัน


    1. 🔨 try, except
    2. 🤔 else
    3. ☝️ finally
    4. 👋 raise
    5. 💪 สรุป 5 Keywords
    6. 📚 Further Reading: Python Exceptions
    7. 😺 GitHub
    8. 📃 References

    🔨 try, except

    try และ except เป็น keywords ที่ใช้ร่วมกัน โดยใน try เราจะใส่ code ที่เราคิดว่าอาจจะเกิด exception ขึ้นได้

    ส่วนใน except เราจะใส่สิ่งที่เราต้องการให้เกิดขึ้นเมื่อเกิด exception ขึ้น

    ยกตัวอย่างเช่น เราเขียน code เพื่อเช็กว่า payment มีค่ามากกว่า 0 หรือไม่ แต่ payment ที่ใส่เข้ามาอาจไม่ใช่ตัวเลข ซึ่งจะทำให้ code ของเราหยุดทำงาน:

    # Without try, except
    
    # Set payment
    payment = "one thousand"
    
    # Validate payment
    if float(payment) < 0:
        print("Payment cannot be negative.")
    

    ผลลัพธ์:

    ValueError
    

    เราสามารถใช้ try และ except ช่วยให้ code ทำงานต่อได้ พร้อมทำให้บอกเราให้รู้ว่า เกิดข้อผิดพลาดอะไรขึ้น:

    # Set payment
    payment = "one thousand"
    
    # Code that may raise exception
    try:
        if float(payment) < 0:
            print("Payment cannot be negative.")
    
    # Print when exception occurs
    except ValueError:
        print("Payment must be a number.")
    
    

    ผลลัพธ์:

    Payment must be a number.
    

    🤔 else

    else ทำงานคล้าย except แต่แทนที่จะส่งค่าบางอย่างกลับมาเมื่อเกิด exception, else จะทำงานเมื่อไม่มี exception เกิดขึ้นใน try

    ยกตัวอย่างเช่น ใช้ else เพื่อแสดงข้อความว่ากำลังประมวลผล เมื่อ payment เป็นตัวเลข:

    # Set payment
    payment = 500
    
    # Code that may raise exception
    try:
        if float(payment) < 0:
            print("Payment cannot be negative.")
    
    # Print when exception occurs
    except ValueError as e:
        print(f"Error: {e}")
    
    # Print when exception does not occur
    else:
        print("Processing payment ...")
    

    ผลลัพธ์:

    Processing payment ...
    

    ☝️ finally

    finally จะส่งค่ากลับมาไม่ว่าจะเกิด exception ขึ้นหรือไม่ก็ตาม

    ยกตัวอย่างเช่น ใช้ finally แสดงข้อความขอบคุณลูกค้า ไม่ว่า payment จะผ่านหรือไม่ก็ตาม:

    # Set payment
    payment = 500
    
    # Code that may raise exception
    try:
        if float(payment) < 0:
            print("Payment cannot be negative.")
    
    # Print when exception occurs
    except ValueError as e:
        print(f"Error: {e}")
    
    # Print when exception does not occur
    else:
        print("Processing payment ...")
    
    # Print no matter what
    finally:
        print("Thank you for your payment.")
    

    ผลลัพธ์:

    Processing payment ...
    Thank you for your payment.
    

    👋 raise

    สุดท้าย เราจะใช้ raise กำหนด exception ได้เอง

    ยกตัวอย่างเช่น ใช้ raise เพื่อแจ้งเตือนเมื่อ payment ติดลบ:

    # Set payment
    payment = -50
    
    # Code that may raise exception
    try:
        if not isinstance(payment, (int, float)):
            raise TypeError("Payment must be a number.")
        if payment < 0:
            raise ValueError("Payment cannot be negative.")
    
    # Print when exception occurs
    except (TypeError, ValueError) as e:
        print(f"Error: {e}")
    
    # Print when exception does not occur
    else:
        print("Processing payment ...")
    
    # Print no matter what
    finally:
        print("Thank you for your payment.")
    

    ผลลัพธ์:

    Error: Payment cannot be negative.
    Thank you for your payment.
    

    💪 สรุป 5 Keywords

    ในบทความนี้ เราได้เรียนรู้วิธีใช้ 5 keywords เพื่อจัดการ exception ใน Python ได้แก่:

    1. try: รัน code ที่เราคิดว่าอาจเกิด exception
    2. except: code ที่จะรันเมื่อเกิด exception จาก try
    3. else: code ที่รันเมื่อไม่เกิด exception จาก try
    4. finally: code ที่จะรันไม่ว่า try จะเกิด exception หรือไม่
    5. raise: code สำหรับแสดง exception ที่กำหนดเอง

    ตัวอย่าง code:

    # Set payments
    payments = {
        "Alex": "one thousand",
        "Barbara": -50,
        "Carter": 500
    }
    
    # Loop through payments
    for name, payment in payments.items():
        
        # Print name and payment
        print(f"{name} paying {payment}.")
        
        # Code that may raise exception
        try:
            if not isinstance(payment, (int, float)):
                raise TypeError("Payment must be a number.")
            if payment < 0:
                raise ValueError("Payment cannot be negative.")
    
        # Print when exception occurs
        except (TypeError, ValueError) as e:
            print(f"Error: {e}")
    
        # Print when exception does not occur
        else:
            print("Processing payment ...")
    
        # Print no matter what
        finally:
            print("Thank you for your payment.")
            
        # Print divider
        print("\\n -------------------------------------------------- \\n")
    

    ผลลัพธ์:

    Alex paying one thousand.
    Error: Payment must be a number.
    Thank you for your payment.
    
     -------------------------------------------------- 
    
    Barbara paying -50.
    Error: Payment cannot be negative.
    Thank you for your payment.
    
     -------------------------------------------------- 
    
    Carter paying 500.
    Processing payment ...
    Thank you for your payment.
    
     -------------------------------------------------- 
    
    
    

    📚 Further Reading: Python Exceptions

    ศึกษาประเภทของ exception ใน Python ได้ที่: Python Built-in Exceptions


    😺 GitHub

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


    📃 References

  • Function in R: ความหมาย, ส่วนประกอบ, และประเภท function ในภาษา R สำหรับผู้เริ่มต้น พร้อมตัวอย่าง

    Function in R: ความหมาย, ส่วนประกอบ, และประเภท function ในภาษา R สำหรับผู้เริ่มต้น พร้อมตัวอย่าง

    Function เป็น 1 ใน 2 องค์ประกอบหลักในภาษา R เคียงข้างกับ object

    ในขณะที่ object คือ สิ่งที่มีอยู่ในภาษา R, function คือ สิ่งที่เกิดขึ้นในภาษา R

    ภาษา R จะทำงานไม่ได้ ถ้าขาดทั้ง 2 อย่างไป

    ในบทความนี้ เราจะมีวิธีใช้งาน function ในภาษา R กัน:

    1. Function คืออะไร?
    2. ส่วนประกอบของ function
    3. ประเภทของ function
    4. การดูรายละเอียดของ function

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


    1. 🤔 What Is a Function?
    2. 🧠 Anatomy of Function
    3. 🗃️ Types of Functions
      1. 📦 Base R Function
      2. 📥 Package Function
      3. 🎁 Custom Function
    4. ❓ Get Help
    5. 💪 Summary
    6. 😺 GitHub
    7. 📃 References
    8. ✅ R Book for Psychologists: หนังสือภาษา R สำหรับนักจิตวิทยา

    🤔 What Is a Function?

    Function คือ code ที่เราเรียกใช้งานซ้ำ ๆ ได้ ซึ่งช่วยให้เราเขียน code ได้ง่ายขึ้น

    เช่น แทนที่เราจะหาผลรวมของ 1–5 โดยพิมพ์ตัวเลขทีละตัว:

    1 + 2 + 3 + 4 + 5
    

    เราสามารถใช้ function ช่วยได้แบบนี้:

    sum(1:5)
    

    และถ้าเราต้องการหาผลลัพธ์ของเลขชุดอื่น (เช่น 15–20) เราสามารถใช้ function เดียวกันได้:

    sum(15:20)
    

    จะเห็นได้ว่า function ทำให้เราเขียน code ได้ง่ายและสะดวกขึ้นมาก


    🧠 Anatomy of Function

    Function ประกอบด้วย 2 ส่วน:

    1. Name หรือ ชื่อของ function (เช่น round)
    2. Argument หรือ input สำหรับ function (เช่น 1:5 และ 15:20)

    โดย argument แบ่งได้เป็น 2 ประเภท:

    1. Positional argument หรือ input ตามตำแหน่งใน function
    2. Keyword argument หรือ input ตาม keywords

    ยกตัวอย่าง เช่น sample() ซึ่งเป็น function สุ่มตัวอย่าง และมี 2 arguments:

    1. ชุดข้อมูล (เช่น 1:10)
    2. จำนวนที่ต้องการสุ่ม (เช่น 3)

    เราสามารถเขียนแบบ positional และ keyword argument ได้แบบนี้:

    # Positional arguments
    sample(1:10, 3)
    
    # Keyword arguments
    sample(x = 1:10, size = 3)
    

    จากตัวอย่าง จะเห็นว่า positional argument เขียนง่ายกว่า แต่ keyword argument ช่วยให้อ่าน code ได้ง่ายกว่า

    เราควรใช้ positional argument เมื่อใช้ function ที่ไม่ซับซ้อน เช่น sum() ที่ต้องการแค่ 1 argument

    และควรใช้ keyword argument กับ function ที่มีหลาย arguments


    🗃️ Types of Functions

    Function แบ่งได้เป็น 3 ประเภท ได้แก่:

    1. Base R function
    2. Package function
    3. Custom function

    .

    📦 Base R Function

    Base R function เป็น function ที่มาพร้อมกับภาษา R และเรียกใช้งานได้โดยไม่ต้องติดตั้ง package เพิ่มเติม เช่น:

    • mean()
    • sum()
    • length()
    • round()
    • seq()

    .

    📥 Package Function

    Package function เป็น function ที่คนอื่นสร้างไว้และเราสามารถโหลดมาใช้ได้

    ในการเรียกใช้งาน เราจะต้องทำ 2 อย่างก่อน:

    1. ติดตั้ง package ด้วย install.packages() (ทำครั้งแรกครั้งเดียว)
    2. โหลด package ทุกครั้งที่เริ่มต้น session ด้วย library()

    ถ้าข้าม 2 ขั้นตอนนี้ไป เราจะไม่สามารถใช้งาน function ได้

    เช่น เรียกใช้ sample_n() เพื่อสุ่มข้อมูลจาก data frame (ตารางข้อมูล):

    # Data frame of my friends
    friends <- data.frame(
      name = c("Alice", "Bob", "Charlie", "David", "Eve", "Frank", "Grace", "Heidi"),
      age = c(28, 32, 25, 30, 29, 35, 27, 31)
    )
    
    # friends data frame:
    #       name age
    #  1   Alice  28
    #  2     Bob  32
    #  3 Charlie  25
    #  4   David  30
    #  5     Eve  29
    #  6   Frank  35
    #  7   Grace  27
    #  8   Heidi  31
    
    # Sample 3 of my friends
    sample_n(friends, 3)
    

    ผลลัพธ์:

    Error in sample_n(friends, 3) : could not find function "sample_n"
    

    จะเห็นได้ว่า R ส่ง error กลับมา ซึ่งเราแก้ได้โดยติดตั้งและโหลด package ก่อนเรียกใช้งาน sample_n():

    # Install package
    install.packages("dplyr")
    
    # Load package
    library(dplyr)
    

    ซึ่งจะทำให้เราใช้งาน function ได้สำเร็จ:

    # Sample 3 of my friends
    sample_n(friends, 3)
    

    ผลลัพธ์:

       name age
    1   Bob  32
    2 Heidi  31
    3 Grace  27
    

    .

    🎁 Custom Function

    Custom function เป็น function ที่เราเขียนขึ้นเอง เพื่อตอบโจทย์ที่ function อื่นไม่สามารถทำได้

    เราสามารถสร้าง custom function ได้ด้วย function() {} เช่น สร้าง function เพื่อคำนวณพื้นที่วงกลม:

    # Custome function to find circle area
    circle_area <- function(radius) {
    
    	# Calculate area
      area <- pi * (radius^2)
      
      # Return area
      print(area)
    }
    

    ในตัวอย่าง function จะคำนวณพื้นที่วงกลมโดยใช้ 1 argument 1 คือ radius และ print ค่าใน console

    หลังจากสร้าง function แล้ว เราสามารถเรียกใช้งาน function ได้เหมือน function อื่น ๆ:

    # Calculate circle area where radius is 14
    circle_area(14)
    

    ผลลัพธ์:

    [1] 615.7522
    

    ❓ Get Help

    สุดท้าย เราสามารถดูรายละเอียดของ function ได้ 2 วิธี:

    1. ?: ดูคู่มือการใช้ function
    2. args(): ดู argument ของ function

    เช่น ดูคู่มือของ round() ซึ่งเป็น function สำหรับปัดจุดทศนิยม:

    # Read round() documentation
    ?round
    

    เราจะเห็นคู่มือการใช้งาน round() ในหน้าต่างของเรา:

    หรือดู arguments ของ round():

    # Learn about round() arguments
    args(round)
    

    ผลลัพธ์:

    function (x, digits = 0, ...) 
    NULL
    

    💪 Summary

    ในบทความนี้ เราได้ทำความรู้จักกับ function ซึ่งเป็น 1 ใน 2 องค์ประกอบที่สำคัญในภาษา R กัน:

    1. Function คือ code ที่สามารถเรียกใช้งานซ้ำได้
    2. Function ประกอบด้วย 2 ส่วน: name และ argument
    3. Argument มี 2 ประเภท: positional และ keyword argument
    4. Function มี 3 ประเภท:
      1. Base R function ที่มาพร้อมภาษา R
      2. Package function ที่มากับ packages
      3. Custom function ที่เราสร้างเอง
    5. ดูรายละเอียดของ function ได้ด้วย ? และ args()

    😺 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:

  • วิธีใช้ polars: package ทรงพลังสำหรับทำงานกับ tabular data ใน Python — ตัวอย่างการทำงานกับ IKEA Products dataset

    วิธีใช้ polars: package ทรงพลังสำหรับทำงานกับ tabular data ใน Python — ตัวอย่างการทำงานกับ IKEA Products dataset

    polars เป็น package สำหรับทำงานกับข้อมูลในรูปแบบตาราง (tabular data) ใน Python และถูกพัฒนาด้วย Rust และ Apache Arrow ซึ่งทำให้ polars ประมวลผลได้เร็วและมีประสิทธิภาพสูง

    polars เป็นทางเลือกสำหรับคนที่เบื่อกับข้อจำกัดของ pandas ซึ่งเป็น package ยอดนิยมสำหรับทำงานกับข้อมูลในรูปแบบตาราง โดย polars ได้เปรียบ pandas อยู่ 3 อย่าง:

    1. Fast: ประมวลผลเร็วกว่า
    2. Intuitive: มี syntax ที่ใช้ง่ายกว่า
    3. Lazy: รองรับการเขียนแบบ lazy evaluation (ดูรายละเอียดเพิ่มเติมด้านล่าง) ทำให้ประมวลผลได้มีประสิทธิภาพมากกว่า

    Note: ดูวิธีการใช้ pandas ได้ที่บทความนี้

    Source: https://pola.rs/

    ในบทความนี้ เราจะมาดูวิธีใช้ polars ผ่านตัวอย่างการทำงานกับ IKEA Products dataset ที่มีข้อมูลเฟอร์นิเจอร์จาก IKEA กัน

    โดยบทความแบ่งเป็น 9 ส่วนดังนี้:

    1. Import package and dataset: โหลด package และ dataset
    2. Explore: สำรวจ dataset ก่อนทำงานกับข้อมูล
    3. Select: เลือกข้อมูล
    4. Filter: กรองข้อมูล
    5. Sort: จัดเรียงข้อมูล
    6. Aggregate: หาค่าทางสถิติ
    7. Mutate: เพิ่ม ลบ แก้ไข column
    8. Lazy: การทำงานแบบ lazy
    9. Chaining: การเชื่อมต่อ function

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


    1. 📦 Section 1. Import Package & Dataset
    2. 🧭 Section 2. Explore
      1. 🔷 2.1 shape
      2. 🗺️ 2.2 schema
      3. 🐵 2.3 head()
      4. 🔎 2.4 glimpse()
      5. 📝 2.5 describe()
    3. 🫳 Section 3. Select
      1. 🔲 3.1 Using []
      2. 🔪 3.2 Using slice() & select()
    4. 👀 Section 4. Filter
      1. ☝️ 4.1 One Condition
      2. 🖐️ 4.2 Multiple Conditions
    5. ↕️ Section 5. Sort
      1. ⬆️ 5.1 Ascending
      2. ⬇️ 5.2 Descending
      3. 🖐️ 5.3 Multiple Columns
    6. 🧮 Section 6. Aggregate
      1. 🏠 6.1 Basic
      2. 🏘️ 6.2 Group By
    7. 💪 Section 7. Mutate
      1. ➕ 7.1 Add Columns
      2. 🗑️ 7.2 Remove Columns
    8. 🥱 Section 8. Lazy
    9. 🔗 Section 9. Chaining
    10. ⭐️ Summary
    11. ⏭️ Next Step: DIY
    12. 📃 References

    📦 Section 1. Import Package & Dataset

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

    เราจะโหลด package ด้วย import แบบนี้:

    import polars as pl
    

    Note: ก่อนโหลด เราจะต้องติดตั้ง package ซึ่งเราสามารถทำได้ด้วย pip install

    และโหลด dataset ด้วย read_csv() เพราะข้อมูลเป็นไฟล์ CSV:

    df = pl.read_csv("ikea_products.csv")
    

    ตอนนี้ เรามีข้อมูลพร้อมจะทำงานต่อแล้ว


    🧭 Section 2. Explore

    ในขั้นที่ 2 เราจะสำรวจข้อมูลที่เพิ่งโหลดเสร็จ ซึ่งเราทำได้ 5 วิธี:

    1. shape
    2. schema
    3. head()
    4. glimpse()
    5. describe()

    .

    🔷 2.1 shape

    shape เป็น attribute สำหรับเช็กจำนวน rows และ columns ใน dataset:

    df.shape
    

    ผลลัพธ์:

    จากผลลัพธ์ จะเห็นว่า dataset มีข้อมูล 3,694 rows และมี 14 columns

    .

    🗺️ 2.2 schema

    schema เป็น attribute สำหรับแสดงชื่อและประเภทข้อมูลของ columns:

    df.schema
    

    ผลลัพธ์:

    .

    🐵 2.3 head()

    head() เป็น method สำหรับดู n rows แรกของข้อมูล เช่น ดู 10 แรกของข้อมูล:

    df.head(10)
    

    ตัวอย่างผลลัพธ์:

    .

    🔎 2.4 glimpse()

    glimpse() เป็น method สำหรับดูโครงสร้างข้อมูล ซึ่งประกอบด้วย:

    1. จำนวน rows และ columns
    2. ชื่อ column
    3. ประเภทข้อมูล
    4. ตัวอย่างข้อมูล
    df.glimpse()
    

    ตัวอย่างผลลัพธ์:

    .

    .

    📝 2.5 describe()

    describe() เป็น method สำหรับแสดง summary statistics ของ columns:

    1. count: จำนวนข้อมูล
    2. null_count: จำนวนข้อมูลที่เป็นค่าว่าง
    3. mean: ค่าเฉลี่ย
    4. std: ค่าเบี่ยงเบนมาตรฐาน (standard deviation)
    5. min: ค่าต่ำสุด
    6. 25%, 50%, 75%: ข้อมูลที่ quartile ที่ 1, 2, และ 3
    7. max: ค่าสูงสุด
    df.describe()
    

    ตัวอย่างผลลัพธ์:


    🫳 Section 3. Select

    เรามี 2 วิธีในการเลือก rows และ columns จากข้อมูล:

    1. ใช้ []
    2. ใช้ slice() และ select()

    .

    🔲 3.1 Using []

    เราจะใช้ [] โดยกำหนด rows และ columns ที่ต้องการแบบนี้:

    df[rows, cols]
    

    ถ้าเราต้องการ rows หรือ columns ทั้งหมด ให้เราเว้นข้อมูลส่วนนั้นไว้ เช่น เลือกข้อมูล 10 rows แรก และ columns ทั้งหมด:

    df[:10]
    

    ตัวอย่างผลลัพธ์:

    หรือเลือกเฉพาะ columns ชื่อ ประเภท และราคา และ rows ทั้งหมด:

    df[["name", "category", "price"]]
    

    ผลลัพธ์:

    ถ้าต้องการทั้ง rows และ columns ให้เรากำหนดทั้งสองอย่าง เช่น ข้อมูล 10 rows แรก โดยเลือกเฉพาะ columns ชื่อ ประเภท และราคา:

    df[0:10, ["name", "category", "price"]]
    

    ผลลัพธ์:

    .

    🔪 3.2 Using slice() & select()

    เราสามารถใช้ slice() และ select() เพื่อเลือกข้อมูลแทนการใช้ [] ได้ โดย:

    1. ใช้ slice() เลือก rows
    2. ใช้ select() เลือก columns

    เช่น เลือกข้อมูล 10 rows แรก:

    df.slice(0, 10)
    

    ตัวอย่างผลลัพธ์:

    เลือก columns ชื่อ ประเภท และราคา:

    df.select(["name", "category", "price"])
    

    ผลลัพธ์:

    สุดท้าย เราสามารถใช้ทั้ง slice() และ select() ร่วมกันเพื่อเลือกทั้ง rows และ columns ได้แบบนี้:

    df.slice(0, 10).select(["name", "category", "price"])
    

    ผลลัพธ์:


    👀 Section 4. Filter

    เรากรองข้อมูลได้ด้วย filter() ซึ่งรับรองการกรองแบบ 1 เงื่อนไข และมากกว่า 1 เงื่อนไข

    .

    ☝️ 4.1 One Condition

    ตัวอย่างการกรองแบบ 1 เงื่อนไข เช่น เลือกเฉพาะข้อมูลของ outdoor furniture:

    df.filter(pl.col("category") == "Outdoor furniture")
    

    Note: สังเกตว่า เราใช้ col() เพื่อระบุ column ที่ต้องการ

    ตัวอย่างผลลัพธ์:

    .

    🖐️ 4.2 Multiple Conditions

    สำหรับการกรองหลายเงื่อนไข เราจะใช้ logical operator ช่วย:

    OperatorMeaning
    &And
    |Or
    ~Not

    เช่น เลือกข้อมูล outdoor furniture ที่ราคาสูงกว่า 1,000:

    df.filter(
        (pl.col("category") == "Outdoor furniture") &
        (pl.col("price") > 1000)
    )
    

    ตัวอย่างผลลัพธ์:


    ↕️ Section 5. Sort

    สำหรับจัดลำดับข้อมูล เราจะใช้ sort() ซึ่งรองรับการใช้งาน 3 กรณี:

    1. Ascending: เรียงจากน้อยไปมาก (A–Z)
    2. Descending: เรียงจากมากไปน้อย (Z–A)
    3. Multiple columns: เรียงลำดับหลาย columns พร้อมกัน

    .

    ⬆️ 5.1 Ascending

    Default ในการจัดลำดับของ sort() คือ เรียงจากน้อยไปมาก เช่น จัดเรียงข้อมูลตามราคา:

    df.sort("price")
    

    ตัวอย่างผลลัพธ์:

    .

    ⬇️ 5.2 Descending

    ถ้าต้องการจัดเรียงแบบมากไปน้อย เราจะต้องกำหนด argument descending=True:

    df.sort("price", descending=True)
    

    ตัวอย่างผลลัพธ์:

    .

    🖐️ 5.3 Multiple Columns

    ถ้าต้องการจัดลำดับหลาย columns พร้อมกัน เราจะกำหนด columns และวิธีจัดเรียง (ascending vs descending) เช่น จัดเรียงตามประเภทเฟอร์นิเจอร์ (A–Z) และราคา (Z–A):

    df.sort(
        ["category", "price"],
        descending=[False, True]
    )
    

    ตัวอย่างผลลัพธ์:


    🧮 Section 6. Aggregate

    Aggregate คือ การสรุปข้อมูล เช่น หาค่าเฉลี่ย และทำได้ 2 วิธี:

    1. แบบไม่จัดกลุ่ม ด้วยคำสั่ง select()
    2. แบบจัดกลุ่ม ด้วยคำสั่ง group_by() และ agg()

    .

    🏠 6.1 Basic

    ตัวอย่างสรุปข้อมูลโดยไม่จัดกลุ่ม เช่น หาค่าเฉลี่ย ค่าต่ำสุด และค่าสูงสุดของราคาเฟอร์นิเจอร์:

    df.select(
        pl.col("price").mean().alias("Mean"),
        pl.col("price").min().alias("Min"),
        pl.col("price").max().alias("Max")
    )
    

    Note: alias() ใช้ตั้งชื่อ column

    ผลลัพธ์:

    .

    🏘️ 6.2 Group By

    ตัวอย่างสรุปข้อมูลแบบจัดกลุ่ม เช่น หาค่าเฉลี่ย ค่าต่ำสุด และค่าสูงสุดของราคาเฟอร์นิเจอร์ ตามประเภทเฟอร์นิเจอร์:

    df.group_by("category").agg(
        pl.col("price").mean().alias("Mean"),
        pl.col("price").min().alias("Min"),
        pl.col("price").max().alias("Max")
    )
    

    ตัวอย่างผลลัพธ์:


    💪 Section 7. Mutate

    Mutate หมายถึง การปรับเปลี่ยน columns ที่มีอยู่ เช่น เพิ่มหรือลบ columns

    .

    ➕ 7.1 Add Columns

    ตัวอย่างการเพิ่ม columns เช่น:

    1. เพิ่ม column ส่วนลด (discount) โดยราคามากกว่า 1,000 จะลด 15% และราคาน้อยกว่านั้นจะลด 10% และ
    2. เพิ่ม column แสดงราคาหลังใช้ส่วนลดแล้ว (price_discounted)

    เราสามารถเขียน code ได้ดังนี้:

    df.with_columns(
        discount = pl.when(pl.col("price") > 1000)
        .then(0.15)
        .otherwise(0.10),
    ).with_columns(
        price_discounted = pl.col("price") * (1 - pl.col("discount"))
    )
    

    Note: เราใช้ when(), then(), otherwise() ช่วยกำหนดเงื่อนไขที่ต้องการ

    ตัวอย่างผลลัพธ์:

    สังเกตว่า columns ใหม่จะอยู่ต่อท้ายสุด

    .

    🗑️ 7.2 Remove Columns

    เราลบ column ได้ด้วย drop() เช่น ลบ columns ราคาเก่า (old_price) และการขายออนไลน์ (sellable_online):

    df.drop(["old_price", "sellable_online"])
    

    ตัวอย่างผลลัพธ์:


    🥱 Section 8. Lazy

    Lazy evaluation เป็นการประมวลผลที่จะรันก็ต่อเมื่อได้รับคำสั่ง ซึ่งช่วยให้การทำงานมีประสิทธิภาพมากขึ้น เพราะการประมวลผลจะไม่เกิดขึ้นจนกว่าจะจำเป็น

    Note: การประมวลผลในทันทีโดยไม่รอคำสั่ง เรียกว่า eager evaluation

    การทำงานแบบ lazy evaluation มีอยู่ 3 ขั้นตอน:

    ขั้นที่ 1. สร้าง LazyFrame ซึ่งเป็นข้อมูลสำหรับ lazy evaluation ด้วย lazy():

    df_lz = df.lazy()
    

    ขั้นที่ 2. เขียนคำสั่งที่ต้องการ เช่น เลือก columns:

    execution = df_lz.select(["name", "category", "price"])
    

    ขั้นที่ 3. สั่งให้ประมวลผลด้วยคำสั่ง collect():

    execution.collect()
    

    ผลลัพธ์:


    🔗 Section 9. Chaining

    Chaining เป็นการเชื่อมต่อ function เพื่อส่งผลลัพธ์จาก function หนึ่งไปยังอีก function หนึ่ง:

    df.function1().function2().function3()...

    Chaining ช่วยให้เราตอบโจทย์ที่ซับซ้อนขึ้นได้ เช่น:

    สำหรับเฟอร์นิเจอร์ที่ Francis Cayouette ออกแบบ ประเภทไหนจัดว่าเป็น “Premium” (ราคาสูงกว่า 1,000) และ “Affordable” (ราคาน้อยกว่า 1,000)

    เราสามารถใช้ polars เพื่อตอบโจทย์ได้แบบนี้:

    df_lz.filter(
        pl.col("designer") == "Francis Cayouette"
    ).group_by(
        "category"
    ).agg(
        pl.col("price").mean().round().alias("avg_price")
    ).with_columns(
        pl.when(pl.col("avg_price") > 1000)
        .then(pl.lit("Premium"))
        .otherwise(pl.lit("Affordable"))
        .alias("price_label")
    ).sort(
        "avg_price",
        descending=True
    ).select(
        [
            "category",
            "price_label",
            "avg_price"
        ]
    ).collect()
    

    ผลลัพธ์:


    ⭐️ Summary

    ในบทความนี้ เราได้เห็นวิธีการใช้ polars เพื่อทำงานกับข้อมูลในรูปแบบตาราง ซึ่งสามารถสรุปเป็นการเขียน code 9 กลุ่มได้ดังนี้:

    Section 1. Import package & dataset:

    • import polars as pl
    • pl.read_csv()

    Section 2. Explore:

    • df.shape
    • df.schema
    • df.head()
    • df.glimpse()
    • df.describe()

    Section 3. Select:

    • df[rows, cols]
    • pl.slice()
    • pl.select()

    Section 4. Filter:

    • df.filter()
    • pl.col()
    • &, |, ~

    Section 5. Sort:

    • df.sort()

    Section 6. Aggregate:

    • df.select()
    • df.group_by().agg()
    • alias()

    Section 7. Mutate:

    • df.with_columns()
    • pl.when().then().otherwise()
    • df.drop()

    Section 8. Lazy:

    • df.lazy()
    • collect()

    Section 9. Chaining:

    • df.function1().function2().function()...

    ⏭️ Next Step: DIY

    ใครที่อยากฝึกใช้ polars สามารถดูตัวอย่าง code และ dataset ได้ที่ GitHub


    📃 References


    🔔 ใครที่ชอบบทความนี้ ฝากกด subscribe และติดตามกันได้ที่:

  • AI Literacy: สรุป 31 ข้อคิดการใช้ AI ให้อยู่รอด จาก session แชร์ความรู้ให้กับนักศึกษา ม.หอการค้าไทย

    AI Literacy: สรุป 31 ข้อคิดการใช้ AI ให้อยู่รอด จาก session แชร์ความรู้ให้กับนักศึกษา ม.หอการค้าไทย

    สัปดาห์ที่แล้ว ผมมีโอกาสแชร์ความรู้การใช้ AI ในหัวข้อ AI literacy ให้กับนักศึกษาคณะการศึกษาปฐมวัย มหาวิทยาลัยหอการค้าไทย

    ในบทความนี้ ผมจะมาสรุป 31 ข้อคิดที่ผมแชร์ใน session โดยแบ่งเป็น 5 กลุ่ม:

    1. Why AI literacy: ความสำคัญของ AI literacy
    2. Working with AI: แนวคิดการทำงานกับ AI
    3. How to prompt: วิธีเขียน prompt
    4. Future trends: แนวโน้มของ AI ในอนาคต
    5. Be human: การเป็นมนุษย์ในยุคของ AI

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


    1. 🤖 Part I. Why AI Literacy
    2. 💼 Part II. Working With AI
    3. 👷 Part III. How to Prompt
    4. 🚀 Part IV. Future Trends
    5. 😌 Part V. Be Human

    🤖 Part I. Why AI Literacy

    .

    ข้อ 1. Pareto Principle (80/20 rule)

    Pareto principle เป็น mental model หรือแนวคิดช่วยตัดสินใจที่บอกว่า 80% ของความสำเร็จมักมาจาก 20% ของสิ่งที่เราทำ

    ในยุคที่ AI เข้ามามีบทบาทในหลายด้านของชีวิต ทักษะ AI เป็นสิ่งง่าย ๆ ที่เราทำได้เพื่อช่วยให้เราอยู่รอด

    การเรียนรู้เกี่ยวกับ AI คือ 20% ที่เราทำได้ เพื่อให้โอกาสอยู่รอดถึง 80%

    .

    ข้อ 2. What is AI literacy?

    AI literacy คือ ความเข้าใจและความสามารถในการใช้งาน AI ได้อย่างมีประสิทธิภาพ

    .

    ข้อ 3. AI can do many things

    AI สามารถทำได้หลายอย่าง เช่น:

    • Content: สร้าง content เช่น ข้อความ ภาพ เสียง และวิดีโอ
    • Analysis: วิเคราะห์ข้อมูลขนาดใหญ่อย่างรวดเร็ว
    • Automation: ทำงานโดยอัตโนมัติ (เช่น คุยกับลูกค้าในขณะที่เราหลับ)

    .

    ข้อ 4. Jobs at risk

    ความสามารถของ AI ทำให้มีหลายงานเสี่ยงที่จะถูกแทนที่ แม้กระทั่งงานที่ปกติจะต้องใช้มนุษย์ เช่น:

    • ล่าม/นักแปลภาษา
    • นักเขียน
    • โปรแกรมเมอร์
    • Customer service

    เมื่อเป็นอย่างนี้ AI จะมาแทนที่มนุษย์ไหม?

    .

    ข้อ 5. AI still has limitations

    แม้ AI จะทำได้หลายอย่าง แต่ก็ยังมีข้อจำกัดอยู่ เช่น:

    .

    ข้อ 6. We must not fear AI, but people who use AI

    ด้วยข้อจำกัดของ AI เรายังไม่ต้องกลัวว่า AI จะมาแทนที่เรา

    แต่เราควรจะกลัวคนที่ใช้ AI เป็นมากกว่า

    AI won’t replace people, but maybe people that use AI will replace people that don’t. — Andrew Ng

    คนที่ใช้ AI เป็นสามารถไปได้ไกลกว่าคนอื่น

    เช่น ถ้าไม่ใช้ AI เราอาจจะใช้เวลา 2 วันเพื่อเขียนรายงานส่งอาจารย์

    แต่เมื่อใช้ AI เราอาจใช้เวลาแค่ 2 ชั่วโมง และมีเวลาสำหรับอ่านหนังสือสอบมากขึ้น ทำให้เรามีโอกาสได้เกรดที่ดีกว่าคนอื่น

    .

    ข้อ 7. The one who survives is the one who levels up

    แต่ละครั้งที่มีเทคโนโลยีใหม่เกิดขึ้น คนที่อยู่รอด คือ คนที่ยกระดับตัวเอง

    สมัยก่อน เราผลิตหนังสือโดยใช้ scribe หรือชาวบ้านที่ฝึกคัดลอกหนังสือมาโดยเฉพาะ scribe ใช้เวลาฝึกฝนนานหลายปีกว่าจะสามารถคัดหนังสือได้

    วันหนึ่ง เครื่องพิมพ์ถูกพัฒนาขึ้น เราสามารถพิมพ์หนังสือได้หลายพันหน้าในวันเดียว โดยไม่ต้องพึ่ง scribe

    ความต้องการ scribe ลดน้อยลงเรื่อย ๆ และ scribe ที่ยึดติดกับวิธีการผลิตหนังสือแบบเดิม ก็ค่อย ๆ หายไปพร้อมกับความต้องการของตลาด

    ส่วน scribe ที่ปรับตัวเข้าหาเทคโนโลยี และฝึกควบคุมเครื่องพิมพ์ ยังคงอยู่รอดต่อไป

    การมาถึงของ AI ก็เหมือนเครื่องพิมพ์ ถ้าเราไม่เรียนรู้ที่จะใช้ AI เราก็จะค่อย ๆ ถูกลืม เหมือนกับ scribe ที่ยังคัดหนังสือด้วยมือ

    .

    ข้อ 8. We are at a crossroad: choose

    AI พัฒนาเร็วขึ้นและก้าวกระโดดมากขึ้นเรื่อย ๆ

    ในช่วงแรกที่ ChatGPT เปิดตัวใหม่ ๆ เราต้องรอนานหลายเดือนกว่าจะได้ใช้ ChatGPT เวอร์ชั่นใหม่ที่มีความสามารถไม่ต่างจากเวอร์ชั่นก่อนหน้ามากนัก

    ในปัจจุบัน เราจะเห็น ChatGPT มีการอัปเดตที่ถี่ขึ้น และในอัปเดตแต่ละครั้ง ChatGPT มีความสามารถมากกว่าเวอร์ชั่นก่อนมาก

    การที่ AI พัฒนาเร็วขึ้นเรื่อย ๆ ทำให้เรามีเวลาปรับตัวน้อยลงเรื่อย ๆ

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

    The people who will come out of this well won’t be the ones who mastered one tool. They’ll be the ones who got comfortable with the pace of change itself. — Matt Shumer


    💼 Part II. Working With AI

    .

    ข้อ 9. Maslow’s hammer

    I suppose it is tempting, if the only tool you have is a hammer, to treat everything as if it were a nail. — Abraham Maslow

    Maslow’s hammer เป็น mental model ที่บอกว่า เครื่องมือสามารถจำกัดมุมมองของเราได้

    เช่น ถ้าเรามีค้อน เราจะมองทุกอย่างเป็นตะปู

    ในยุคของ AI เราอาจมองว่าทุกอย่างแก้ได้ด้วย AI:

    • ทำงานเร็วขึ้น
    • ผิดพลาดน้อยลง
    • มีเวลามากขึ้น

    แต่ไม่ใช่ทุกปัญหาจะแก้ได้ด้วย AI เพราะ AI ไม่ใช่เครื่องมือสำหรับแก้ทุกอย่าง

    ถ้าเราอยากตอกตะปู เราจะต้องใช้ค้อน ไม่ใช่ AI

    การใช้ AI ที่ถูกต้อง คือ เริ่มต้นจากปัญหาและความต้องการของเรา แล้วเลือกเครื่องมือที่ตอบโจทย์ ซึ่งเครื่องมือนั้นอาจจะเป็น AI หรือไม่ก็ได้

    .

    ข้อ 10. AI is built in man’s image

    AI เกิดจากการ train model ด้วยข้อมูลจากอินเทอร์เน็ตซึ่งมาจากมนุษย์

    Human -> Data -> Train -> AI

    เพราะ AI ถูกสร้างจากข้อมูลของมนุษย์ และเรามองได้ว่า AI เป็นเหมือนเป็นมนุษย์คนหนึ่ง

    .

    ข้อ 11. AI as capable but junior assistant

    ถ้าเรามอง AI เป็นคน AI จะเป็นเหมือนผู้ช่วยที่มีความรู้รอบด้านและมีศักยภาพสูง

    แต่สิ่งเดียวที่ผู้ช่วยคนนี้ยังขาดไป คือ ทิศทาง

    .

    ข้อ 12. Even a fried egg is hard to get right

    การทำงานกับ AI ก็เหมือนสั่งไข่ดาว แม้จะดูง่าย แต่ก็ไม่ง่ายอย่างที่คิด

    บางครั้ง เราอยากกินไข่ไม่สุก แต่ได้แบบสุกมาแทน

    บางครั้ง เราอยากให้ AI สร้างรูปในแบบที่เราคิด แต่ไม่เคยได้ภาพนั้นสักที

    .

    ข้อ 13. Principal-agent dilemma

    Principal-agent dilemma เป็น mental model ที่บอกว่า คนทำงาน (agent) มักทำตามความต้องการของคนสั่ง (principal) ไม่ได้ เพราะทั้งสองฝ่ายมีข้อมูลไม่เท่ากัน

    ในตัวอย่าง เราไม่ได้ไข่ดาวที่ต้องการ เพราะคนทอดไข่ไม่รู้ว่าเราชอบไข่สุกหรือไม่สุก

    เช่นเดียวกัน AI สร้างรูปที่เราต้องการไม่ได้ เพราะ AI ไม่รู้ว่ารูปที่เราคิดต้องการเป็นยังไง

    .

    ข้อ 14. Fixing the egg

    ถ้าเราอยากได้ไข่ดาวที่ต้องการ เราจะต้องทำให้ AI รู้เท่ากับเรา เช่น ให้ข้อมูลอย่าง:

    1. Goal: ภาพปลายทางที่เราต้องการ (ภาพแมวน่ารัก)
    2. Steps: ขั้นตอนที่จะไปถึงจุดหมาย (วาดแมวก่อน แล้วค่อยวาดองค์ประกอบอื่น ๆ ในภาพ)
    3. Constraints: ข้อจำกัดหรือสิ่งที่ไม่ควรทำ (เช่น ไม่เอาแมวสีดำ ฉากหลังต้องดูสดใส)

    .

    ข้อ 15. Human in the loop: taste and iterate

    Taste: เมื่อไข่ดาวมาเสิร์ฟ เราจะไม่รู้ว่าไข่ดาวอร่อยไหม จนกว่าจะได้ลองชิมด้วยตัวเอง

    การทำงานกับ AI ก็เช่นกัน เราไม่ควรจะบอกว่า สิ่งที่ AI ส่งกลับมาดีไหม จนกว่าจะได้เช็กด้วยตัวเอง

    Iterate: ถ้าชิมแล้วไข่ดาวไม่อร่อย เราจะบอกกับคนทอดว่า ไม่อร่อยเพราะอะไร และจะทำยังไงให้อร่อยมากขึ้น และรอชิมไข่จานต่อไป

    ถ้าสิ่งที่ AI ส่งกลับมาไม่ตรงใจ เราควรจะบอก AI ว่าอะไรที่ยังไม่ถูกใจ เพื่อให้ AI ปรับผลลัพธ์และส่งกลับมาให้เราเช็กจนกว่าเราจะพอใจกับงานของ AI

    .

    ข้อ 16. Be accountable

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

    แม้ทนายจะอ้างว่ารู้เท่าไม่ถึงการณ์ว่า AI ที่บริษัทให้ใช้สามารถสร้างข้อมูลที่ไม่มีอยู่จริงได้ และตัวเองควรตรวจสอบข้อมูลจาก AI ก่อน ศาลยังสั่งให้ทนายงดว่าความด้วยตัวเองเป็นเวลา 2 ปี โดยในระยะเวลานี้จะต้องทำงานเป็นลูกจ้างของคนอื่น และต้องรายงานต่อศาลทุกไตรมาส

    ดังนั้น ไม่ว่างานของ AI จะดูดีขนาดไหน เราควรจะตรวจสอบด้วยตัวเองก่อนที่จะนำงานไปใช้จริง


    👷 Part III. How to Prompt

    .

    ข้อ 17. Prompt and prompt engineering

    Prompt คือ คำสั่งสำหรับทำงานกับ AI ซึ่งจะเป็น:

    • ข้อความ
    • ภาพ
    • เสียง

    หรือสื่ออื่น ๆ ก็ได้

    Prompt engineering คือ การออกแบบ prompt เพื่อทำให้ AI ทำงานได้อย่างมีประสิทธิภาพสูงสุด

    .

    ข้อ 18. Effective prompts

    Prompt ที่ดีมีลักษณะ 3 อย่าง:

    1. Clear: ชัดเจนว่า สิ่งที่ต้องทำคืออะไร
    2. Specific: มีความเจาะจง ไม่คลุมเครือ
    3. Structured: มีโครงสร้างที่ดี รู้ว่าข้อมูลไหนคืออะไรและต้องใช้ยังไง

    นอกจากนี้ ทั้ง 3 อย่างต้องทำงานภายในเป้าหมายและขอบเขตงานที่เราต้องทำ

    .

    ข้อ 19. How and what of prompting

    การเขียน prompt ที่เราจะต้องรู้มี 2 อย่าง:

    1. Prompting technique (how): วิธีเขียน prompt ให้ AI เข้าใจ
    2. Prompting framework (what): สิ่งที่เราจะควรใส่ลงใน prompt

    .

    ข้อ 20. Prompting technique: n-shot

    n-shot technique เป็นการสั่ง AI โดยให้ตัวอย่าง (shot) และแบ่งได้เป็น 3 ประเภท:

    • Zero-shot: สั่งโดยไม่ให้ตัวอย่าง
    • One-shot: สั่งโดยให้ 1 ตัวอย่าง
    • Few-shot: สั่งโดยให้หลายตัวอย่าง

    เราจะใช้ shot น้อยเมื่อต้องการให้คำตอบของ AI มีความหลากหลาย (มีความสร้างสรรค์)

    และใช้ shot เยอะเมื่อต้องการให้คำตอบของ AI ใกล้เคียงกับภาพที่เราต้องการมากที่สุด

    ตัวอย่างการใช้ n-shot:

    จะสังเกตว่า ยิ่งให้ shot เยอะ คำตอบของ AI ก็จะยิ่งใกล้เคียงกับตัวอย่างมากขึ้น (zero-shot ให้สัตว์ป่า แต่ few-shot ให้สัตว์เลี้ยง)

    .

    ข้อ 21. Prompting technique: COT

    COT ย่อมาจาก chain-of-thought ซึ่งเป็นวิธีเขียน prompt โดยกำหนดวิธีคิดให้กับ AI

    เช่น แทนที่ให้ AI แก้โจทย์เลขในทันที:

    A ซื้อส้ม 2 ลูก ลูกละ 10 บาท A ต้องจ่ายเงินเท่าไร

    เราจะสอนให้ AI คิดก่อน:

    A ซื้อส้ม 2 ลูก ลูกละ 10 บาท
    วิธีคิด:
    1. หาว่า ส้มราคาลูกละเท่าไร
    2. คูณจำนวนราคาด้วยจำนวนส้มที่ต้องซื้อ
    A ต้องจ่ายเงินเท่าไร

    COT เหมาะกับงานที่ซับซ้อนหรือมีหลายขั้นตอน เช่น:

    • แก้สมการเลข
    • วิเคราะห์งานวิจัย
    • การวางแผนเชิงกลยุทธ์

    .

    ข้อ 22. Prompting framework: theatre model

    Theatre model เป็นแนวการเขียน prompt ที่มนุษย์เป็นเหมือนผู้กำกับ และ AI เป็นนักแสดงบนเวทีของเรา

    Theatre model ประกอบด้วย 6 ส่วน ได้แก่:

    1. Role: บทบาทของ AI
    2. Context: setting ของละคร (บริบทในการทำงาน)
    3. Task: การเดินเรื่อง (เป้าหมาย ขั้นตอน และข้อจำกัด)
    4. Output format: จุดจบของเรื่องจะเป็นยังไง (ส่งที่ AI ต้องส่งให้เรา)
    5. Input: อุปกรณ์ที่จะให้นักแสดงใช้ (ข้อมูลสำหรับ AI)
    6. Execution: “Action!” (คำสั่งให้ AI)

    ตัวอย่างการใช้ theatre model เพื่อสร้างสูตรอาหารใหม่:

    PartExample
    Roleคุณเป็น cook มืออาชีพ มีประสบการณ์ทำงานอาหารไทยและนานาชาติมากกว่า 30 ปี
    Contextคุณกำลังเข้าร่วมแข่งอยู่ในรายการทำอาหาร เพื่อชิงเงินรางวัล 10 ล้านบาท โจทย์คืออาหารไทยฟิวชั่น
    Taskคิดสูตรอาหารไทยฟิวชัน โดยต้องมีวัตถุดิบที่กำหนดอยู่ในอาหาร

    ตั้งชื่อจาน และบอกวิธีการเตรียมอาหาร

    อาหารจะต้องมีความเป็นไทย และถูกปากคนทุกชาติ

    ห้ามเป็นอาหารที่มีอยู่แล้ว
    Output formatส่งกลับมาในรูปแบบนี้:

    ชื่ออาหาร:
    xxx

    ขั้นตอนการทำ:
    xxx
    Inputวัตถุดิบที่ต้องมี:
    1. ใบโหระพา
    2. เนื้อไก่
    3. ผักชี
    Executionคิดสูตรอาหารเลย

    .

    ข้อ 23. Annotation

    เพื่อช่วยให้ AI เข้าใจ prompt ได้มากขึ้น เราควรจัด format ให้อ่านง่ายโดยใช้ XML tags และ markdown:

    • XML tags เช่น <example>ตัวอย่าง</example>
    • Markdown เช่น # และ *

    อ่านเพิ่มเติมเกี่ยวกับ XML tags และ markdown

    .

    ข้อ 24. Iterate

    Prompt แรกอาจจะไม่ให้ในสิ่งที่เราต้องการเสมอไป

    สิ่งที่เราต้องทำ คือ วิเคราะห์ว่า ผลลัพธ์ยังขาดอะไรไป และมีส่วนไหนของ prompt ที่เราปรับได้ แล้วส่ง prompt ที่แก้แล้วให้ AI อีกครั้ง

    ทำอย่างนี้วนไปจนกว่าจะได้ผลลัพธ์ที่เราต้องการ

    .

    ข้อ 25. Ask AI

    ถ้าไม่รู้ว่าจะเขียน prompt ยังไง หรือ prompt ยังขาดอะไรไป เราสามารถถาม AI ได้ให้ช่วยเราได้

    ตัวอย่าง:


    .

    ข้อ 26. AI, more agentic

    AI จะทำงานแบบอัตโนมัติมากขึ้น และมีมนุษย์เข้ามาเกี่ยวข้องน้อยลง

    .

    ข้อ 27. Human and AI getting closer

    เพราะ AI จะทำงานได้ด้วยตัวเองมากขึ้น AI จะเข้ามามีบทบาทในการทำงานมากขึ้น ทำให้มนุษย์จะทำงานกับ AI อย่างใกล้ชิดมากขึ้น


    😌 Part V. Be Human

    .

    ข้อ 28. Humans required

    แม้ว่า AI จะสามารถทำงานหลาย ๆ อย่างแทนมนุษย์ได้ แต่ในบางงาน เรายังต้องการมนุษย์ด้วยกันเองอยู่ เช่น:

    • นักบิน: แม้ AI จะขับเครื่องบินได้ แต่เราก็อยากให้มีนักบินที่สามารถแก้ปัญหาเฉพาะหน้าอยู่ในห้องนักบิน
    • หมอ: แม้ AI จะวินิจฉัยโรคได้แม่นยำกว่ามนุษย์ แต่เราก็ยังต้องการให้มีคนบอกข่าวดี/ร้ายเป็นคนที่เข้าใจความรู้สึกของเรา
    • Customer service: บางครั้ง เราก็ต้องการคุยกับคนมากกว่า chatbot ที่ตอบเป็น pattern

    .

    ข้อ 29. Skill, like muscle

    ทักษะก็เป็นเหมือนกล้ามเนื้อ เมื่อไม่ได้ใช้งาน ก็จะอ่อนแอลงเรื่อย ๆ

    ถ้าเราใช้ AI ทำทุกอย่างให้เรา ทักษะที่เราเคยมีก็จะค่อย ๆ หายไป

    .

    ข้อ 30. What not to outsource to AI

    4 ทักษะที่เราควรฝึกพัฒนา และไม่ควรให้ AI ทำแทนเรา ได้แก่:

    1. Thinking: การคิด เพราะถ้าเราคิดไม่ได้แล้ว เราจะไม่ประเมินงานของ AI ได้ว่าดี/ไม่ดี
    2. Learning: ถ้าเราไม่เรียนรู้สิ่งใหม่ ๆ เราจะถูกทิ้งไว้ข้างหลัง โดยเฉพาะในยุคที่การเปลี่ยนแปลงเกิดขึ้นอย่างรวดเร็ว
    3. Writing and reading: การเขียนและการอ่านเป็นทักษะที่ช่วยให้เราคิดและเรียนรู้ได้อย่างมีประสิทธิภาพ
    4. Empathy: การเข้าใจคนอื่นเป็นทักษะที่ช่วยให้เราเข้าใจคนอื่นและเชื่อมโยงถึงกันและกันในแบบที่ AI ยังไม่สามารถทำได้

    .

    ข้อ 31. When to use AI

    3 กรณีที่เราจะใช้ AI:

    1. Routine: ใช้ AI ทำงานจำเจหรืองานที่ต้องเป็นประจำ เพื่อที่เราจะได้โฟกัสงานที่ต้องใช้ความคิดมากขึ้น
    2. What and how: ใช้ AI ทำงานในขณะที่เราโฟกัสกับภาพใหญ่ ซึ่งได้แก่ when (ทำเมื่อไร) และ why (ทำไมต้องทำ)
    3. Brainstorm: ใช้ AI ช่วยระดมความคิด เพราะ AI มีข้อมูลเยอะ และช่วยให้เห็นมุมมองที่เราคิดไม่ถึงมาก่อนได้

    🔔 ใครที่ชอบบทความนี้ ฝากกด subscribe และติดตามกันได้ที่:

  • โหลดข้อมูลจาก database ใน 4 ขั้นตอน ด้วย sqlalchemy และ pandas ใน Python — ตัวอย่างการทำงานกับ Chinook database

    โหลดข้อมูลจาก database ใน 4 ขั้นตอน ด้วย sqlalchemy และ pandas ใน Python — ตัวอย่างการทำงานกับ Chinook database

    ในบทความนี้ เราจะมาดู 4 ขั้นตอนในการโหลดข้อมูลจาก database ด้วย sqlalchemy และ pandas libraries ใน Python ผ่านตัวอย่างการทำงานกับ Chinook database กัน:

    1. Import libraries
    2. Connect to the database
    3. List the tables
    4. Get the table

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


    1. ⬇️ 1. Import Libraries
    2. 🛜 2. Connect to the Database
    3. 📋 3. List the Tables
    4. 🪑 4. Get the Table
    5. 😺 GitHub
    6. 📃 References

    ⬇️ 1. Import Libraries

    ในขั้นแรก เราจะโหลด sqlalchemy และ pandas กัน:

    # Import packages
    from sqlalchemy import create_engine, inspect
    import pandas as pd
    

    Note: ถ้ายังไม่เคยติดตั้ง libraries ให้ใช้คำสั่ง !pip install ก่อนใช้ import


    🛜 2. Connect to the Database

    ในขั้นที่ 2 เราจะเชื่อมต่อกับ database

    ในตัวอย่าง เราจะเชื่อมต่อกับ SQLite database บนเครื่อง ซึ่งเราสามารถทำได้ด้วย create_engine() แบบนี้:

    # Connect to the database
    engine = create_engine("sqlite:///chinook.sqlite")
    

    Note: ดาวน์โหลด chinook.sqlite ได้ที่ GitHub


    📋 3. List the Tables

    ในขั้นที่ 3 เราจะโหลดรายชื่อ tables ใน database เพื่อเลือก tables ที่เราต้องการ

    เราจะใช้ 2 คำสั่ง ได้แก่:

    • inspect(): function สำหรับสร้าง object ที่เก็บ metadata ของ database เอาไว้
    • .get_table_names(): method สำหรับแสดงรายชื่อ tables ใน database
    # Get the inspector
    inspector = inspect(engine)
    
    # List the table names
    tables = inspector.get_table_names()
    
    # Print the table names
    print(tables)
    

    ผลลัพธ์:

    ['Album', 'Artist', 'Customer', 'Employee', 'Genre', 'Invoice', 'InvoiceLine', 'MediaType', 'Playlist', 'PlaylistTrack', 'Track']
    

    🪑 4. Get the Table

    ในขั้นสุดท้าย เราจะโหลดข้อมูลจาก table ที่ต้องการ โดยใช้ pd.read_sql():

    # Set the query
    brazil_customers_query = """
    SELECT FirstName, LastName, Phone, Email
    FROM Customer
    WHERE Country = 'Brazil';
    """
    
    # Query the database
    df = pd.read_sql(brazil_customers_query, engine)
    
    # Display the df
    print(df)
    

    ผลลัพธ์:

       FirstName   LastName               Phone                          Email
    0       Luís  Gonçalves  +55 (12) 3923-5555           luisg@embraer.com.br
    1    Eduardo    Martins  +55 (11) 3033-5446       eduardo@woodstock.com.br
    2  Alexandre      Rocha  +55 (11) 3055-3278               alero@uol.com.br
    3    Roberto    Almeida  +55 (21) 2271-7000  roberto.almeida@riotur.gov.br
    4   Fernanda      Ramos  +55 (61) 3363-5547       fernadaramos4@uol.com.br
    

    😺 GitHub

    ดูตัวอย่าง code ทั้งหมดได้ที่ GitHub


    📃 References

  • สร้าง chatbot ส่วนตัว ใน 5 ขั้นตอน ด้วย OpenAI library ใน Python — ตัวอย่างการสร้าง Gemini chatbot

    สร้าง chatbot ส่วนตัว ใน 5 ขั้นตอน ด้วย OpenAI library ใน Python — ตัวอย่างการสร้าง Gemini chatbot

    ในบทความนี้ เราจะมาดูวิธีสร้าง chatbot ส่วนตัว ด้วย openai library ใน Python ใน 5 ขั้นตอนกัน:

    1. Import libraries
    2. Create a client
    3. Create a chat history
    4. Create a chat function
    5. Chat

    Note: เราจะรัน code ตัวอย่างบน Google Colab ซึ่งทุกคนสามารถดูได้ Gemini Chatbot in Google Colab

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


    1. 🏁 Step 1. Import Libraries
    2. 💁‍♂️ Step 2. Create a Client
    3. 🙊 Step 3. Create a Chat History
    4. 📨 Step 4. Create a Chat Function
    5. 💬 Step 5. Chat
    6. 👍 Google Colab
    7. 📃 References

    🏁 Step 1. Import Libraries

    ในขั้นแรก เราจะโหลด 2 libraries ที่เกี่ยวข้อง ซึ่งได้แก่:

    1. openai: สำหรับเรียกใช้ API ของ AI service *
    2. display และ Markdown: สำหรับแสดง markdown text (อย่างคำตอบที่ส่งมาจาก AI) ให้อ่านง่าย
    # Import libraries
    
    # For Gemini
    from openai import OpenAI
    
    # For text rendering
    from IPython.display import display, Markdown
    

    Note: * openai library ถูกออกแบบสำหรับ OpenAI API แต่สามารถใช้งานกับ AI อื่น ๆ ได้ เช่น:


    💁‍♂️ Step 2. Create a Client

    ในขั้นที่ 2 เราจะสร้าง client เพื่อเชื่อมต่อกับ AI ที่เป็น “สมอง” ของ chatbot ด้วย OpenAI() ซึ่งต้องการ 2 arguments ได้แก่:

    1. api_key: รหัส API ของเรา
    2. base_url: URL สำหรับเรียกใช้ API

    ในตัวอย่าง เราจะเรียกใช้ Gemini ซึ่งเราสามารถกำหนด arguments ได้ดังนี้:

    # Create client
    client = OpenAI(
        api_key="YOUR_API_KEY_HERE",
        base_url="<https://generativelanguage.googleapis.com/v1beta/openai/>"
    )
    

    Note:

    • ใส่ API key ใน "YOUR_API_KEY_HERE"
    • ดูวิธีสร้าง API key ฟรีได้ที่ Using Gemini API keys
    • สำหรับคนที่จะเรียกใช้ OpenAI API (ChatGPT) แทน Gemini เราสามารถข้ามการเขียน base_url ไปได้

    🙊 Step 3. Create a Chat History

    ในขั้นที่ 3 เราจะสร้าง chat history เพื่อเก็บ:

    1. System prompt ที่กำหนดพฤติกรรมของ chatbot (ในตัวอย่าง เราจะกำหนดให้เป็นผู้ช่วยที่กระตือรือร้น)
    2. ประวัติการพูดคุยระหว่างเรากับ chatbot ซึ่งจะทำให้ chatbot จำสิ่งที่คุยกันได้
    # Set system prompt
    system_prompt = """
    You are a helpful, cheerful, and optimistic assistant.
    
    Be concise, validate answers, and admit when you don’t know.
    
    Make responses clear, easy to read, and sprinkle in playful emoji.
    """
    
    # Instantiate chat history
    chat_history = [
        {
            "role": "system",
            "content": system_prompt
        }
    ]
    

    📨 Step 4. Create a Chat Function

    ในขั้นที่ 4 เราจะสร้าง function ที่จะทำให้เราถาม-ตอบกับ chatbot แบบ real-time ได้:

    # Create a function for chatbot
    def chatbot(model="gemini-2.5-flash"):
    
        # Set chat history as global variable
        global chat_history
    
        # Print chat header
        display(Markdown("# 🟢 --- Chat Begins ---"))
    
        # Print chat instruction
        print("ℹ️ Type \\"end chat\\" to exit.")
    
        # Loop through conversation
        while True:
    
            # Render user prompt display
            display(Markdown("## 🧑‍💻 You:"))
    
            # Get user input
            user_prompt = input("")
    
            # Check if user wants to exit chat
            if user_prompt.lower() == "end chat":
    
                # Print goodbye message
                display(Markdown("## ✨ Assistant:\\n" + "👋 See you later!"))
    
                # End chat
                break
    
            # Append user input to chat history
            chat_history.append(
                {
                    "role": "user",
                    "content": user_prompt
                }
            )
    
            # Get response
            response = client.chat.completions.create(
    
                # Set prompt
                messages=chat_history,
    
                # Set model
                model=model
            )
    
            # Append response to history
            chat_history.append(
                {
                    "role": "assistant",
                    "content": response.choices[0].message.content
                }
            )
    
            # Render response
            display(Markdown("## ✨ Assistant:\\n" + response.choices[0].message.content + "\\n"))
    

    💬 Step 5. Chat

    ในขั้นสุดท้าย เราจะเรียกใช้งาน chatbot() เพื่อเริ่มคุยกับ AI เลย:

    # Start chatting
    chatbot()
    

    ผลลัพธ์:


    👍 Google Colab

    ดูตัวอย่าง code ทั้งหมดได้ที่ Google Colab


    📃 References

  • Basic R—รวบรวม 13 บทความสอนทำงานกับ data ในภาษา R: Intro to R, Importing Data, Data Manipulation, และ Data Visualisation

    Basic R—รวบรวม 13 บทความสอนทำงานกับ data ในภาษา R: Intro to R, Importing Data, Data Manipulation, และ Data Visualisation

    ในปีนี้ ผมเริ่มหันมาฝึกใช้ภาษา R อย่างจริงจังมากขึ้น หลังจากเรียนคอร์สออนไลน์จาก DataRockie และ DataCamp มา

    และเพื่อช่วยให้ผมเข้าใจภาษา R มากขึ้น ผมได้เขียนสรุปการใช้งานภาษา R เบื้องต้นไว้ ทั้งหมด 13 บทความ ซึ่งผมได้รวบรวมไว้เป็น 4 กลุ่ม ดังนี้:

    1. Introduction to R: แนะนำภาษา R และการทำงานกับ R เบื้องต้น
    2. Importing data: การนำเข้าข้อมูลในภาษา R
    3. Data manipulation: การแปลงข้อมูลดิบให้พร้อมสำหรับการวิเคราะห์
    4. Data visualisation: การแสดงข้อมูลในรูปแบบกราฟ

    .

    Group 1. Introduction to R (3 บทความ):

    1. R foundation: แนะนำภาษา R—ความแตกต่างระหว่าง R และ Python, data types, และ data structures ในภาษา R
    2. R control flow: สอนใช้ if, for, while เพื่อควบคุมการทำงานของภาษา R
    3. R functions (รอลงบทความนะครับ 😆): สอนสร้างและใช้งาน functions ในภาษา R

    .

    Group 2. Importing data (5 บทความ):

    1. Working with data frame: แนะนำ 10 วิธีในการทำงานกับ data frame ซึ่งเป็น data structure ที่พบบ่อยที่สุดในภาษา R
    2. Working with data frame using SQL: สอนการทำงานกับ data frame ด้วย SQL
    3. Working with flat files (รอลงบทความนะครับ 😆): แนะนำการใช้ 3 packages สำหรับ import ข้อมูลจาก flat files
    4. Working with Excel: แนะนำ 2 packages สำหรับทำงานกับ Excel
    5. Working with database: แนะนำวิธีทำงานกับ database ผ่าน DBI package

    .

    Group 3. Data manipulation (4 บทความ):

    1. dplyr package: แนะนำ 5 functions ยอดนิยมสำหรับ data manipulation
    2. dbplyr package: แนะนำการใช้ dplyr functions เพื่อทำงานกับ database
    3. dtplyr package: แนะนำการใช้ dplyr functions เพื่อทำงานกับข้อมูลขนาดใหญ่
    4. data.table package: แนะนำ package ยอดนิยมสำหรับทำงานกับข้อมูลขนาดใหญ่

    .

    Group 4. Data visualisation (1 บทความ):

    1. ggplot2 package: แนะนำวิธีใช้ package เพื่อสร้าง data viz แบบองค์กรระดับโลก

    👉 Tie-In: Machine Learning in R

    สำหรับคนที่สนใจ machine learning ในภาษา R สามารถดู 13 บทความการทำ machine learning ในรูปแบบต่าง ๆ ได้ที่นี่


    ✅ 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:

  • Python for AI: รวบรวม 8 บทความการทำงานกับ AI ใน Python

    Python for AI: รวบรวม 8 บทความการทำงานกับ AI ใน Python

    ในช่วงที่ผ่านมา ผมมีโอกาสแชร์การใช้ Python เพื่อทำงานกับ AI จากการที่ผมได้ทำงานเกี่ยวกับ AI มากขึ้น

    เพื่อช่วยในการแชร์ ผมได้สรุปเนื้อหาไว้ใน 8 บทความ (5 กลุ่ม) ซึ่งทุกคนสามารถอ่านตามได้ดังนี้:

    🐍 Session #1. Intro to Python:

    • Intro to Python: แนะนำการใช้งานและประเภทข้อมูลใน Python

    🔁 Session #2. Control flow:

    • Control flow: สอนใช้ statement เช่น if, for, while เพื่อควบคุมการทำงานของ Python

    💻 Session #3. Functions:

    • Functions: สอนการสร้าง function ใน Python

    📦 Session #4. Packages and files:

    • open(): สอนการทำงานกับไฟล์ด้วย base Python
    • json package: สอนการทำงานกับ JSON ด้วย json package
    • pd.read_csv(): สอนการทำงานกับ CSV ด้วย pandas package

    🤖 Session #5. AI packages:

    • openai package: สอนการทำงานกับ AI API ผ่าน openai package
    • google-genai package: สอนการใช้ google-genai เพื่อทำงานกับ Gemini API
  • สรุป 10 วิธีใช้งาน data frame ในภาษา R: creating, indexing, subsetting, filtering, sorting, และอื่น ๆ — ตัวอย่างการทำงานกับ Jujutsu Kaisen data frame

    สรุป 10 วิธีใช้งาน data frame ในภาษา R: creating, indexing, subsetting, filtering, sorting, และอื่น ๆ — ตัวอย่างการทำงานกับ Jujutsu Kaisen data frame

    Data frame เป็นหนึ่งใน data structure ที่พบบ่อยที่สุดในการทำงานกับข้อมูล

    Data frame เก็บข้อมูลในรูปแบบตาราง โดย:

    • 1 row = 1 รายการ (เช่น ข้อมูลของ John)
    • 1 column = 1 ประเภทข้อมูล (เช่น อายุ)

    ตัวอย่าง data frame:

    ในบทความนี้ เราจะมาสรุป 10 วิธีในการทำงานกับ data frame กัน:

    1. Creating: การสร้าง data frame
    2. Previewing: การดูข้อมูล data frame
    3. Indexing: การเลือก columns ที่ต้องการ
    4. Subsetting: การเลือก rows และ columns ที่ต้องการ
    5. Filtering: การกรองข้อมูล
    6. Sorting: การจัดลำดับข้อมูล
    7. Aggregating: การสรุปข้อมูล
    8. Adding columns: การเพิ่ม columns ใหม่
    9. Removing columns: การลบ columns
    10. Binding: การเชื่อมข้อมูลใหม่เข้ากับ data frame

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


    1. 1️⃣ Creating
    2. 2️⃣ Previewing
      1. 👀 View()
      2. 🙊 head()
      3. 🐒 tail()
      4. 🏗️ str()
      5. 🧮 summary()
      6. 💠 dim()
      7. 🚣 nrow()
      8. 🏦 ncol()
    3. 3️⃣ Indexing
      1. 💰 Using $
      2. 🔳 Using [[]]
    4. 4️⃣ Subsetting
      1. 🍽️ df[rows, cols]
      2. 🔪 subset()
    5. 5️⃣ Filtering
      1. 🍽️ df[rows, cols]
      2. 🔪 subset()
    6. 6️⃣ Sorting
      1. ⬇️ Ascending
      2. ⬆️ Descending
      3. ↔️ Sort by Multiple Columns
    7. 7️⃣ Aggregating
    8. 8️⃣ Adding Columns
    9. 9️⃣ Removing Columns
    10. 🔟 Binding
      1. 🤝 rbind()
      2. 🤲 cbind()
    11. 😺 GitHub
    12. 📃 References
    13. ✅ R Book for Psychologists: หนังสือภาษา R สำหรับนักจิตวิทยา

    1️⃣ Creating

    เราสามารถสร้าง data frame ด้วย data.frame() ซึ่งต้องการ ชื่อ column และ vector ที่เก็บข้อมูลของ column นั้น ๆ:

    # Create a data frame
    jjk_df <- data.frame(
      ID = 1:10,
      Name = c("Yuji Itadori", "Megumi Fushiguro", "Nobara Kugisaki", "Satoru Gojo",
               "Maki Zenin", "Toge Inumaki", "Panda", "Kento Nanami", "Yuta Okkotsu", "Suguru Geto"),
      Age = c(15, 16, 16, 28, 17, 17, 18, 27, 17, 27),
      Grade = c("1st Year", "1st Year", "1st Year", "Special", "2nd Year",
                "2nd Year", "2nd Year", "Special", "Special", "Special"),
      CursedEnergy = c(80, 95, 70, 999, 60, 85, 75, 200, 300, 400),
      Technique = c("Divergent Fist", "Ten Shadows", "Straw Doll", "Limitless",
                    "Heavenly Restriction", "Cursed Speech", "Gorilla Mode",
                    "Ratio Technique", "Rika", "Cursed Spirit Manipulation"),
      Missions = c(25, 30, 20, 120, 35, 28, 40, 90, 55, 80)
    )
    
    # View the result
    jjk_df
    

    ผลลัพธ์:

       ID             Name Age    Grade CursedEnergy                  Technique Missions
    1   1     Yuji Itadori  15 1st Year           80             Divergent Fist       25
    2   2 Megumi Fushiguro  16 1st Year           95                Ten Shadows       30
    3   3  Nobara Kugisaki  16 1st Year           70                 Straw Doll       20
    4   4      Satoru Gojo  28  Special          999                  Limitless      120
    5   5       Maki Zenin  17 2nd Year           60       Heavenly Restriction       35
    6   6     Toge Inumaki  17 2nd Year           85              Cursed Speech       28
    7   7            Panda  18 2nd Year           75               Gorilla Mode       40
    8   8     Kento Nanami  27  Special          200            Ratio Technique       90
    9   9     Yuta Okkotsu  17  Special          300                       Rika       55
    10 10      Suguru Geto  27  Special          400 Cursed Spirit Manipulation       80
    

    2️⃣ Previewing

    เรามี 8 functions สำหรับดูข้อมูล data frame:

    No.FunctionFor
    1View()ดูข้อมูลทั้งหมด
    2head()ดูข้อมูล 6 rows แรก
    3tail()ดูข้อมูล 6 rows สุดท้าย
    4str()ดูโครงสร้างข้อมูล
    5summary()ดูสถิติข้อมูล
    6dim()ดูจำนวน rows และ columns
    7nrow()ดูจำนวน rows
    8ncol()ดูจำนวน columns

    เราไปดูตัวอย่างทั้ง 8 functions กัน

    .

    👀 View()

    View() ใช้ดูข้อมูลทั้งหมดใน data frame:

    # View the whole data frame
    View(jjk_df)
    

    เราจะเห็นผลลัพธ์ในหน้าต่างใหม่:

    Note: เนื่องจาก View() แสดงข้อมูลทั้งหมด จึงเหมาะกับการใช้งานกับ data frame ขนาดเล็ก

    .

    head() ใช้ดูข้อมูล 6 rows แรกใน data frame:

    # View the first 6 rows
    head(jjk_df)
    

    ผลลัพธ์:

      ID             Name Age    Grade CursedEnergy            Technique Missions
    1  1     Yuji Itadori  15 1st Year           80       Divergent Fist       25
    2  2 Megumi Fushiguro  16 1st Year           95          Ten Shadows       30
    3  3  Nobara Kugisaki  16 1st Year           70           Straw Doll       20
    4  4      Satoru Gojo  28  Special          999            Limitless      120
    5  5       Maki Zenin  17 2nd Year           60 Heavenly Restriction       35
    6  6     Toge Inumaki  17 2nd Year           85        Cursed Speech       28
    

    .

    🐒 tail()

    tail() ใช้ดูข้อมูล 6 rows สุดท้ายใน data frame:

    # View the last 6 rows
    tail(jjk_df)
    

    ผลลัพธ์:

       ID         Name Age    Grade CursedEnergy                  Technique Missions
    5   5   Maki Zenin  17 2nd Year           60       Heavenly Restriction       35
    6   6 Toge Inumaki  17 2nd Year           85              Cursed Speech       28
    7   7        Panda  18 2nd Year           75               Gorilla Mode       40
    8   8 Kento Nanami  27  Special          200            Ratio Technique       90
    9   9 Yuta Okkotsu  17  Special          300                       Rika       55
    10 10  Suguru Geto  27  Special          400 Cursed Spirit Manipulation       80
    

    .

    🏗️ str()

    str() ใช้ดูโครงสร้างข้อมูลของ data frame:

    # View the data frame structure
    str(jjk_df)
    

    ผลลัพธ์:

    'data.frame':	10 obs. of  7 variables:
     $ ID          : int  1 2 3 4 5 6 7 8 9 10
     $ Name        : chr  "Yuji Itadori" "Megumi Fushiguro" "Nobara Kugisaki" "Satoru Gojo" ...
     $ Age         : num  15 16 16 28 17 17 18 27 17 27
     $ Grade       : chr  "1st Year" "1st Year" "1st Year" "Special" ...
     $ CursedEnergy: num  80 95 70 999 60 85 75 200 300 400
     $ Technique   : chr  "Divergent Fist" "Ten Shadows" "Straw Doll" "Limitless" ...
     $ Missions    : num  25 30 20 120 35 28 40 90 55 80
    

    จากผลลัพธ์ เราจะเห็นข้อมูล 5 อย่าง ได้แก่:

    1. จำนวน rows (obs.)
    2. จำนวน columns (variables)
    3. ชื่อ columns (เช่น ID)
    4. ประเภทข้อมูลของแต่ละ column (เช่น int)
    5. ตัวอย่างข้อมูลของแต่ละ column (เช่น 1 2 3 4 5 6 7 8 9 10)

    .

    🧮 summary()

    summary() ใช้สรุปข้อมูลใน data frame เช่น:

    • ค่าเฉลี่ย (Mean)
    • จำนวนข้อมูล (Length)
    # View the summary
    summary(jjk_df)
    

    ผลลัพธ์:

           ID            Name                Age           Grade            CursedEnergy     Technique            Missions     
     Min.   : 1.00   Length:10          Min.   :15.00   Length:10          Min.   : 60.00   Length:10          Min.   : 20.00  
     1st Qu.: 3.25   Class :character   1st Qu.:16.25   Class :character   1st Qu.: 76.25   Class :character   1st Qu.: 28.50  
     Median : 5.50   Mode  :character   Median :17.00   Mode  :character   Median : 90.00   Mode  :character   Median : 37.50  
     Mean   : 5.50                      Mean   :19.80                      Mean   :236.40                      Mean   : 52.30  
     3rd Qu.: 7.75                      3rd Qu.:24.75                      3rd Qu.:275.00                      3rd Qu.: 73.75  
     Max.   :10.00                      Max.   :28.00                      Max.   :999.00                      Max.   :120.00 
    

    .

    💠 dim()

    dim() ใช้แสดงจำนวน rows และ columns ใน data frame:

    # View the dimensions
    dim(jjk_df)
    

    ผลลัพธ์:

    [1] 10  7
    

    .

    🚣 nrow()

    nrow() ใช้แสดงจำนวน rows ใน data frame:

    # Get the number of rows
    nrow(jjk_df)
    

    ผลลัพธ์:

    [1] 10
    

    .

    🏦 ncol()

    ncol() ใช้แสดงจำนวน columns ใน data frame:

    # Get the number of columns
    ncol(jjk_df)
    

    ผลลัพธ์:

    [1] 7
    

    3️⃣ Indexing

    Indexing หมายถึง การเลือก columns ที่ต้องการ ซึ่งเราทำได้ 2 วิธี:

    1. ใช้ $ (นิยมใช้)
    2. ใช้ [[]]

    💰 Using $

    เราสามารถใช้ $ ได้แบบนี้:

    df$col
    

    ยกตัวอย่างเช่น เลือก column Name:

    # Index with $
    jjk_df$Name
    

    ผลลัพธ์:

     [1] "Yuji Itadori"     "Megumi Fushiguro" "Nobara Kugisaki"  "Satoru Gojo"      "Maki Zenin"      
     [6] "Toge Inumaki"     "Panda"            "Kento Nanami"     "Yuta Okkotsu"     "Suguru Geto"   
    

    .

    🔳 Using [[]]

    เราสามารถใช้ [[]] ได้แบบนี้:

    df[["col"]]
    

    ยกตัวอย่างเช่น เลือก column Name:

    # Index with [[]]
    jjk_df[["Name"]]
    

    ผลลัพธ์:

     [1] "Yuji Itadori"     "Megumi Fushiguro" "Nobara Kugisaki"  "Satoru Gojo"      "Maki Zenin"      
     [6] "Toge Inumaki"     "Panda"            "Kento Nanami"     "Yuta Okkotsu"     "Suguru Geto"   
    

    4️⃣ Subsetting

    Subsetting คือ การเลือก rows และ columns จาก data frame ซึ่งเราทำได้ 2 วิธี:

    1. ใช้ df[rows, cols] syntax
    2. ใช้ subset()

    .

    🍽️ df[rows, cols]

    เราสามารถใช้ df[rows, cols] ได้ 3 แบบ:

    1. เลือก rows
    2. เลือก columns
    3. เลือก rows และ columns

    แบบที่ 1. เลือก rows อย่างเดียว:

    # Subset rows only
    jjk_df[1:5, ]
    

    ผลลัพธ์:

      ID             Name Age    Grade CursedEnergy            Technique Missions
    1  1     Yuji Itadori  15 1st Year           80       Divergent Fist       25
    2  2 Megumi Fushiguro  16 1st Year           95          Ten Shadows       30
    3  3  Nobara Kugisaki  16 1st Year           70           Straw Doll       20
    4  4      Satoru Gojo  28  Special          999            Limitless      120
    5  5       Maki Zenin  17 2nd Year           60 Heavenly Restriction       35
    
    

    แบบที่ 2. เลือก columns อย่างเดียว:

    # Subset columns only
    jjk_df[, "Name"]
    

    ผลลัพธ์:

     [1] "Yuji Itadori"     "Megumi Fushiguro" "Nobara Kugisaki"  "Satoru Gojo"      "Maki Zenin"      
     [6] "Toge Inumaki"     "Panda"            "Kento Nanami"     "Yuta Okkotsu"     "Suguru Geto" 
    
    

    แบบที่ 3. เลือก rows และ columns:

    # Subset rows and columns
    jjk_df[1:5, c("Name", "Technique")]
    
    

    ผลลัพธ์:

                  Name            Technique
    1     Yuji Itadori       Divergent Fist
    2 Megumi Fushiguro          Ten Shadows
    3  Nobara Kugisaki           Straw Doll
    4      Satoru Gojo            Limitless
    5       Maki Zenin Heavenly Restriction
    

    .

    🔪 subset()

    เราสามารถ subset ข้อมูลได้ด้วย subset() ซึ่งต้องการ 2 arguments:

    subset(x, select)
    
    1. x = data frame
    2. select = columns ที่ต้องการเลือก
    # Subset using susbet() - select conlumns only
    subset(jjk_df, select = c("Name", "Technique"))
    

    ผลลัพธ์:

                   Name                  Technique
    1      Yuji Itadori             Divergent Fist
    2  Megumi Fushiguro                Ten Shadows
    3   Nobara Kugisaki                 Straw Doll
    4       Satoru Gojo                  Limitless
    5        Maki Zenin       Heavenly Restriction
    6      Toge Inumaki              Cursed Speech
    7             Panda               Gorilla Mode
    8      Kento Nanami            Ratio Technique
    9      Yuta Okkotsu                       Rika
    10      Suguru Geto Cursed Spirit Manipulation
    

    ในกรณีที่เราต้องการเลือก rows ด้วย เราจะต้องกำหนด rows ใน x:

    # Subset using susbet() - select both rows and columns
    subset(jjk_df[1:5, ], select = c("Name", "Technique"))
    

    ผลลัพธ์:

                  Name            Technique
    1     Yuji Itadori       Divergent Fist
    2 Megumi Fushiguro          Ten Shadows
    3  Nobara Kugisaki           Straw Doll
    4      Satoru Gojo            Limitless
    5       Maki Zenin Heavenly Restriction
    

    5️⃣ Filtering

    เราสามารถกรองข้อมูลใน data frame ได้ 2 วิธี:

    1. ใช้ df[rows, cols] syntax
    2. ใช้ subset()

    .

    🍽️ df[rows, cols]

    เราสามารถกรองข้อมูลด้วย df[rows, cols] โดยกำหนดเงื่อนไขการกรองใน rows

    เช่น กรองข้อมูลตัวละครที่อยู่ปี 1:

    # Filter using df[rows, cols] - 1 condition
    jjk_df[jjk_df$Grade == "1st Year", ]
    

    ผลลัพธ์:

      ID             Name Age    Grade CursedEnergy      Technique Missions
    1  1     Yuji Itadori  15 1st Year           80 Divergent Fist       25
    2  2 Megumi Fushiguro  16 1st Year           95    Ten Shadows       30
    3  3  Nobara Kugisaki  16 1st Year           70     Straw Doll       20
    

    ในกรณีที่เรามีมากกว่า 1 เงื่อนไข เราสามารถใช้ logical operators ช่วยได้:

    OperatorMeaning
    &AND
    |OR
    !NOT

    ยกตัวอย่างเช่น กรองข้อมูลตัวละครที่อยู่ปี 1 และมีอายุ 15 ปี:

    # Filter using df[rows, cols] - multiple conditions
    jjk_df[jjk_df$Grade == "1st Year" & jjk_df$Age == 15, ]
    

    ผลลัพธ์:

      ID         Name Age    Grade CursedEnergy      Technique Missions
    1  1 Yuji Itadori  15 1st Year           80 Divergent Fist       25
    

    .

    🔪 subset()

    เราสามารถใช้ subset() เพื่อกรองข้อมูลได้แบบนี้:

    # Filter using subset() - 1 condition
    subset(jjk_df, Grade == "1st Year")
    

    ผลลัพธ์:

      ID             Name Age    Grade CursedEnergy      Technique Missions
    1  1     Yuji Itadori  15 1st Year           80 Divergent Fist       25
    2  2 Megumi Fushiguro  16 1st Year           95    Ten Shadows       30
    3  3  Nobara Kugisaki  16 1st Year           70     Straw Doll       20
    

    เราสามารถเพิ่มเงื่อนไขการกรองได้ด้วย logical operator เช่น:

    # Filter using subset() - multiple conditions
    subset(jjk_df, Grade == "1st Year" & Age == 15)
    

    ผลลัพธ์:

      ID         Name Age    Grade CursedEnergy      Technique Missions
    1  1 Yuji Itadori  15 1st Year           80 Divergent Fist       25
    

    6️⃣ Sorting

    สำหรับการเรียงข้อมูล เราจะใช้ order() ซึ่งเพื่อเรียงข้อมูลได้ 3 แบบ:

    1. Ascending (A–Z)
    2. Descending (Z–A)
    3. Sort by multiple columns: จัดเรียงด้วยหลาย columns

    .

    ⬇️ Ascending

    ยกตัวอย่างเช่น เรียงลำดับตามจำนวนภารกิจ (Missions):

    # Sort ascending (default)
    jjk_df[order(jjk_df$Missions), ]
    

    ผลลัพธ์:

       ID             Name Age    Grade CursedEnergy                  Technique Missions
    3   3  Nobara Kugisaki  16 1st Year           70                 Straw Doll       20
    1   1     Yuji Itadori  15 1st Year           80             Divergent Fist       25
    6   6     Toge Inumaki  17 2nd Year           85              Cursed Speech       28
    2   2 Megumi Fushiguro  16 1st Year           95                Ten Shadows       30
    5   5       Maki Zenin  17 2nd Year           60       Heavenly Restriction       35
    7   7            Panda  18 2nd Year           75               Gorilla Mode       40
    9   9     Yuta Okkotsu  17  Special          300                       Rika       55
    10 10      Suguru Geto  27  Special          400 Cursed Spirit Manipulation       80
    8   8     Kento Nanami  27  Special          200            Ratio Technique       90
    4   4      Satoru Gojo  28  Special          999                  Limitless      120
    

    .

    ⬆️ Descending

    เราสามารถเรียงข้อมูลแบบ descending ได้ 2 วิธี:

    1. ใช้ decreasing
    2. ใช้ -

    วิธีที่ 1. ใช้ decreasing:

    # Sort descending with decreasing
    jjk_df[order(jjk_df$Missions, decreasing = TRUE), ]
    

    ผลลัพธ์:

       ID             Name Age    Grade CursedEnergy                  Technique Missions
    4   4      Satoru Gojo  28  Special          999                  Limitless      120
    8   8     Kento Nanami  27  Special          200            Ratio Technique       90
    10 10      Suguru Geto  27  Special          400 Cursed Spirit Manipulation       80
    9   9     Yuta Okkotsu  17  Special          300                       Rika       55
    7   7            Panda  18 2nd Year           75               Gorilla Mode       40
    5   5       Maki Zenin  17 2nd Year           60       Heavenly Restriction       35
    2   2 Megumi Fushiguro  16 1st Year           95                Ten Shadows       30
    6   6     Toge Inumaki  17 2nd Year           85              Cursed Speech       28
    1   1     Yuji Itadori  15 1st Year           80             Divergent Fist       25
    3   3  Nobara Kugisaki  16 1st Year           70                 Straw Doll       20
    

    วิธีที่ 2. ใช้ -:

    # Sort descending with -
    jjk_df[order(-jjk_df$Missions), ]
    

    ผลลัพธ์:

       ID             Name Age    Grade CursedEnergy                  Technique Missions
    4   4      Satoru Gojo  28  Special          999                  Limitless      120
    8   8     Kento Nanami  27  Special          200            Ratio Technique       90
    10 10      Suguru Geto  27  Special          400 Cursed Spirit Manipulation       80
    9   9     Yuta Okkotsu  17  Special          300                       Rika       55
    7   7            Panda  18 2nd Year           75               Gorilla Mode       40
    5   5       Maki Zenin  17 2nd Year           60       Heavenly Restriction       35
    2   2 Megumi Fushiguro  16 1st Year           95                Ten Shadows       30
    6   6     Toge Inumaki  17 2nd Year           85              Cursed Speech       28
    1   1     Yuji Itadori  15 1st Year           80             Divergent Fist       25
    3   3  Nobara Kugisaki  16 1st Year           70                 Straw Doll       20
    

    .

    ↔️ Sort by Multiple Columns

    เราสามารถจัดเรียงข้อมูลได้มากกว่า 1 column ด้วยการเลือก columns ที่ต้องการจัดเรียงเพิ่ม

    เช่น จัดเรียงด้วย:

    • Grade
    • จำนวนภารกิจ (Missions)
    # Sort by multiple columns
    jjk_df[order(jjk_df$Grade, jjk_df$Missions), ]
    

    ผลลัพธ์:

       ID             Name Age    Grade CursedEnergy                  Technique Missions
    3   3  Nobara Kugisaki  16 1st Year           70                 Straw Doll       20
    1   1     Yuji Itadori  15 1st Year           80             Divergent Fist       25
    2   2 Megumi Fushiguro  16 1st Year           95                Ten Shadows       30
    6   6     Toge Inumaki  17 2nd Year           85              Cursed Speech       28
    5   5       Maki Zenin  17 2nd Year           60       Heavenly Restriction       35
    7   7            Panda  18 2nd Year           75               Gorilla Mode       40
    9   9     Yuta Okkotsu  17  Special          300                       Rika       55
    10 10      Suguru Geto  27  Special          400 Cursed Spirit Manipulation       80
    8   8     Kento Nanami  27  Special          200            Ratio Technique       90
    4   4      Satoru Gojo  28  Special          999                  Limitless      120
    

    7️⃣ Aggregating

    เราสามารถสรุปข้อมูลโดยใช้ statistics functions เช่น:

    FunctionFor
    mean()หาค่าเฉลี่ย
    median()หาค่ามัธยฐาน
    min()หาค่าต่ำสุด
    max()หาค่าสูงสุด
    sd()หาค่า standard deviation

    ยกตัวอย่างเช่น หาค่าเฉลี่ย Cursed Energy (CursedEnergy):

    # Find average Cursed Energy
    mean(jjk_df$CursedEnergy)
    

    ผลลัพธ์:

    [1] 236.4
    

    8️⃣ Adding Columns

    เราสามารถเพิ่ม columns ใหม่ได้ด้วยแบบนี้:

    df$new_col <- value
    

    ยกตัวอย่างเช่น เพิ่ม column Ranking:

    # Add a column
    jjk_df$Ranking <- ifelse(jjk_df$CursedEnergy > 100, "High", "Low")
    
    # View the result
    jjk_df
    

    ผลลัพธ์:

       ID             Name Age    Grade CursedEnergy                  Technique Missions Ranking
    1   1     Yuji Itadori  15 1st Year           80             Divergent Fist       25     Low
    2   2 Megumi Fushiguro  16 1st Year           95                Ten Shadows       30     Low
    3   3  Nobara Kugisaki  16 1st Year           70                 Straw Doll       20     Low
    4   4      Satoru Gojo  28  Special          999                  Limitless      120    High
    5   5       Maki Zenin  17 2nd Year           60       Heavenly Restriction       35     Low
    6   6     Toge Inumaki  17 2nd Year           85              Cursed Speech       28     Low
    7   7            Panda  18 2nd Year           75               Gorilla Mode       40     Low
    8   8     Kento Nanami  27  Special          200            Ratio Technique       90    High
    9   9     Yuta Okkotsu  17  Special          300                       Rika       55    High
    10 10      Suguru Geto  27  Special          400 Cursed Spirit Manipulation       80    High
    

    9️⃣ Removing Columns

    เราสามารถลบ columns ได้ด้วยวิธีเดียวกันกับการเพิ่ม columns:

    df$col <- NULL
    

    ยกตัวอย่างเช่น ลบ column Ranking:

    # Remove a column
    jjk_df$Ranking <- NULL
    
    # View the result
    jjk_df
    

    ผลลัพธ์:

       ID             Name Age    Grade CursedEnergy                  Technique Missions
    1   1     Yuji Itadori  15 1st Year           80             Divergent Fist       25
    2   2 Megumi Fushiguro  16 1st Year           95                Ten Shadows       30
    3   3  Nobara Kugisaki  16 1st Year           70                 Straw Doll       20
    4   4      Satoru Gojo  28  Special          999                  Limitless      120
    5   5       Maki Zenin  17 2nd Year           60       Heavenly Restriction       35
    6   6     Toge Inumaki  17 2nd Year           85              Cursed Speech       28
    7   7            Panda  18 2nd Year           75               Gorilla Mode       40
    8   8     Kento Nanami  27  Special          200            Ratio Technique       90
    9   9     Yuta Okkotsu  17  Special          300                       Rika       55
    10 10      Suguru Geto  27  Special          400 Cursed Spirit Manipulation       80
    

    🔟 Binding

    เราสามารถเชื่อม data frame ได้ 2 แบบ:

    1. rbind(): เชื่อม row
    2. cbind(): เชื่อม column

    .

    🤝 rbind()

    rbind() ใช้เชื่อม data frame กับ row ใหม่ และต้องการ 2 arguments:

    rbind(df1, df2)
    
    1. df1 = data frame ที่ 1
    2. df2 = data frame ที่ 2

    ยกตัวอย่างเช่น เพิ่มชื่อตัวละครใหม่ (Hajime Kashimo):

    # Create a new data frame
    new_sorcerer <- data.frame(
      ID = 11,
      Name = "Hajime Kashimo",
      Age = 25,
      Grade = "Special",
      CursedEnergy = 500,
      Technique = "Lightning",
      Missions = 60
    )
    
    # Bind the data frames by rows
    jjk_df <- rbind(jjk_df, new_sorcerer)
    
    # View the result
    jjk_df
    

    ผลลัพธ์:

       ID             Name Age    Grade CursedEnergy                  Technique Missions
    1   1     Yuji Itadori  15 1st Year           80             Divergent Fist       25
    2   2 Megumi Fushiguro  16 1st Year           95                Ten Shadows       30
    3   3  Nobara Kugisaki  16 1st Year           70                 Straw Doll       20
    4   4      Satoru Gojo  28  Special          999                  Limitless      120
    5   5       Maki Zenin  17 2nd Year           60       Heavenly Restriction       35
    6   6     Toge Inumaki  17 2nd Year           85              Cursed Speech       28
    7   7            Panda  18 2nd Year           75               Gorilla Mode       40
    8   8     Kento Nanami  27  Special          200            Ratio Technique       90
    9   9     Yuta Okkotsu  17  Special          300                       Rika       55
    10 10      Suguru Geto  27  Special          400 Cursed Spirit Manipulation       80
    11 11   Hajime Kashimo  25  Special          500                  Lightning       60
    

    .

    🤲 cbind()

    cbind() ใช้เชื่อม data frame กับ column ใหม่ และต้องการ 2 arguments ได้แก่:

    cbind(df, vector)
    
    1. df = data frame
    2. vector = vector ที่เก็บข้อมูลของ column ใหม่

    ยกตัวอย่างเช่น เพิ่ม column ที่บอกว่าตัวละครเป็นครูหรือไม่ (IsTeacher):

    # Bind a column
    jjk_df <- cbind(
      jjk_df,
      IsTeacher = c(FALSE, FALSE, FALSE, TRUE, FALSE,
                    FALSE, FALSE, TRUE, FALSE, TRUE, FALSE)
    )
    
    # View the result
    jjk_df
    

    ผลลัพธ์:

       ID             Name Age    Grade CursedEnergy                  Technique Missions IsTeacher
    1   1     Yuji Itadori  15 1st Year           80             Divergent Fist       25     FALSE
    2   2 Megumi Fushiguro  16 1st Year           95                Ten Shadows       30     FALSE
    3   3  Nobara Kugisaki  16 1st Year           70                 Straw Doll       20     FALSE
    4   4      Satoru Gojo  28  Special          999                  Limitless      120      TRUE
    5   5       Maki Zenin  17 2nd Year           60       Heavenly Restriction       35     FALSE
    6   6     Toge Inumaki  17 2nd Year           85              Cursed Speech       28     FALSE
    7   7            Panda  18 2nd Year           75               Gorilla Mode       40     FALSE
    8   8     Kento Nanami  27  Special          200            Ratio Technique       90      TRUE
    9   9     Yuta Okkotsu  17  Special          300                       Rika       55     FALSE
    10 10      Suguru Geto  27  Special          400 Cursed Spirit Manipulation       80      TRUE
    11 11   Hajime Kashimo  25  Special          500                  Lightning       60     FALSE
    

    😺 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:

  • Machine Learning in R: รวบรวม 13 บทความสอนสร้าง Machine Learning ในภาษา R

    Machine Learning in R: รวบรวม 13 บทความสอนสร้าง Machine Learning ในภาษา R

    ภาษา R มี packages จำนวนมาก สำหรับสร้าง machine learning models

    ในบทความนี้ ผมรวบรวม 13 บทความสอนทำ machine learning ซึ่งแบ่งได้เป็น 4 กลุ่ม ดังนี้:

    1. Supervised learning models หรือการ train models แบบมีเฉลย
    2. Tree-based models หรือการสร้าง model ที่ใช้ decision trees
    3. Unsupervised learning models หรือการ train models แบบไม่มีเฉลย
    4. All-in-one packages หรือ packages สำหรับทำ machine learning แบบครบครัน ตั้งแต่การเตรียมข้อมูลไปจนถึงการประเมินประสิทธิภาพ รวมทั้งใช้ model ได้ตามต้องการ

    กลุ่มที่ 1. Supervised learning models (4 บทความ):

    1. KNN
    2. Naïve Bayes
    3. Linear regression
    4. Logistic regression
    5. Generalised linear models

    กลุ่มที่ 2. Tree-based models (3 บทความ):

    1. ภาค 1: Single tree และ random forest 1
    2. ภาค 2: Random forest 2
    3. ภาค 3: Boosted trees

    กลุ่มที่ 3. Unsupervised learning models (3 บทความ):

    1. k-means
    2. Hierarchical clustering analysis (HCA)
    3. Principal component analysis (PCA)

    กลุ่มที่ 4. All-in-one packages (2 บทความ):

    1. caret (เป็น package ที่เก่ากว่า)
    2. tidymodels (เป็น package ที่ใหม่กว่า)