Author: Shinin Varongchayakul

  • สรุปความรู้จาก 4 Sessions ในงาน Work Life Festival 2025: การเอาตัวรอดในอนาคต, วิธีหาเงินโดยทำงานน้อยลง, เคล็ดลับการสร้างรายได้, และการลงทุน

    สรุปความรู้จาก 4 Sessions ในงาน Work Life Festival 2025: การเอาตัวรอดในอนาคต, วิธีหาเงินโดยทำงานน้อยลง, เคล็ดลับการสร้างรายได้, และการลงทุน

    Work Life Festival 2025 เป็น event ที่จัดขึ้นเมื่อวันที่ 7–8 พฤศจิกายนที่ผ่านมา โดยในงานมีเวทีนำเสนอในหลากหลายหัวข้อที่ตอบโจทย์วัยทำงาน เช่น:

    • การเงินการลงทุน
    • การทำธุรกิจ
    • การพัฒนาทักษะ
    • การใช้ชีวิต

    ในบทความนี้ ผมจะมาสรุปเนื้อหาจาก 4 sessions ที่น่าสนใจที่ผมมีโอกาสได้ไปร่วมฟัง:

    1. The Future of Work (กษิดิศ สตางค์มงคล): วิธีการเอาตัวรอดในโลกอนาคต
    2. Barista FIRE (วิฑูรย์ สูงกิจบูลย์): วิธีการเกษียณก่อนอายุ ทำยังไงให้ทำงานน้อยลงแต่มีรายได้และเวลาเพิ่มขึ้น?
    3. Income Maximisation Strategy (ศิวกร ปล้องใหม): วิธีเพิ่มรายได้ให้ถึงขีดสุด
    4. Purpose First, Market Later (ศรารัญย์ คาน): วิธีการลงทุนให้ตอบโจทย์ชีวิต

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


    1. 🦾 The Future of Work: Why Now Is the Best Time to Build One-Person Business
      1. 🧘 Mindsets for Survival
      2. 🤔 Future Jobs
      3. 🏦 First-Principles for One-Person Business
      4. 🧑‍💼 One-Person Business Philosophy
    2. 🧧 Barista FIRE: แผนที่สู่อิสระกึ่งเกษียณ ทำงานที่อยากทำ ไม่ใช่เพราะต้องทำ
      1. 📖 Backstory
      2. 🔥 FIRE & Barista FIRE
      3. 🪜 How to Barista FIRE
      4. ☕ Example
      5. 🙋 Start With This Question
    3. 💰 Income Maximisation Strategy: กลยุทธเรียบง่ายเพิ่มรายได้ให้ถึงขีดสุด
      1. 🚲 The Three Wheels of Income
      2. 🚴 How to Move the Wheel
      3. 🔥 Expand Existing Income
      4. ⌨️ Find Extra Income
    4. 📊 Purpose First, Market Later: The Three Pillars of Lifelong Investing
      1. 💸 Investing Not Required, Or Not?
      2. 💖 Put Purpose First
      3. 🪙 Compound Interest
      4. 📘 Free Investment Playbooks
    5. 📃 References

    🦾 The Future of Work: Why Now Is the Best Time to Build One-Person Business

    Speaker: กษิดิศ สตางค์มงคล (Digital Writer & Data Analyst, DataRockie)

    .

    🧘 Mindsets for Survival

    ไม่มีใครรู้ว่า จะเกิดอะไรขึ้นในอนาคต:

    • AI ฉลาดขึ้น
    • สิ่งแวดล้อมแย่ลง
    • วิกฤตเศรษฐกิจ
    • สงครามและความขัดแย้ง

    ถ้าจะอยู่รอด เราจะต้องมี mindset 2 ข้อ:

    1. Accept that everything/reality is just the way it is: ยอมรับในสิ่งที่เป็น ไม่ปฏิเสธหรือต่อต้าน
    2. No one is coming to save you: ไม่ใครจะช่วยเราได้ (นอกจากตัวเราเอง)

    .

    🤔 Future Jobs

    Job ในอนาคตจะเปลี่ยนจาก job แบบที่พ่อแม่เราทำ (หางานและอยู่กับมันไปนาน ๆ) ไปเป็น job ที่เราสร้างเอง นั่นคือ การสร้างธุรกิจเป็นของตัวเอง (one-person business)

    งาน office มีข้อเสียอยู่ 2 ข้อ:

    1. Less secure: แม้จะดูมั่นคง แต่ก็ไม่เสมอไป หลายองค์กร lay off พนักงาน ทั้งตอน COVID-19 และเมื่อ AI เริ่มเข้ามาแทนที่คน ไม่มีอะไรการันตีว่า เราจะอยู่กับงานที่ทำไปจนเกษียณ
    2. Effort ≠ reward: ไม่ว่าเราจะทุ่มเทให้กับงานขนาดไหน แต่ไม่มีอะไรการันตีว่า เงินเดือนของเราจะสูงขึ้นตามไป เช่น เราให้เวลากับงานในปีนี้เป็น 2 เท่า แต่ในปีหน้า เราอาจไม่ได้รับเงินเดือนเพราะเศรษฐกิจไม่ดี และเราจะโชคดีมากที่ไม่ถูก lay off

    ในทางกลับกัน การมีธุรกิจเป็นของตัวเองมีข้อดี 2 ข้อ:

    1. More secure: แม้จะไม่มั่นคง 100% แต่ตราบใดที่เรายังสามารถส่งมอบ value ให้กับโลกได้ เราจะสามารถสร้างรายได้อย่างต่อเนื่องและไม่ต้องกลัวตกงาน
    2. More control: เราควบคุมผลลัพธ์ได้มากกว่า เช่น สร้างรายได้เป็น 2 เท่าจากความพยายามที่เพิ่มขึ้น 2 เท่า

    .

    🏦 First-Principles for One-Person Business

    เรามีหลักคิด 5 ข้อในการสร้างธุรกิจเป็นของตัวเอง:

    1. Worthy goal: มองหาเป้าหมายที่คุ้มค่าที่จะลอง
    2. Work harder on yourself (than on your job): ทุ่มเทไปกับการพัฒนา/ดูแลตัวเอง มากกว่าทุ่มเทให้กับงานที่ทำ (แนวคิดจาก Jim Rohn นักธุรกิจและนักเขียนชาวอเมริกัน)
    3. Always read: จงอ่านอยู่เสมอ เพราะการเรียนคือชีวิต ไม่ใช่การเตรียมตัวเพื่อใช้ชีวิต (อิงจาก quote ของ John Dewey นักปรัชญาและนักจิตวิทยาชาวอเมริกัน)
    4. Focus on what you can control: โฟกัสกับสิ่งที่เราควบคุมได้ เพราะสิ่งเดียวที่ไม่มีใครเอาไปจากเราได้ คือ อิสระในการเลือกของเรา (แนวคิดจาก Viktor Frankl นักจิตวิทยาชาวออสเตรียและผุ้รอดชีวิตจากค่ายกักกันของนาซี)
    5. Relentless pursuit: ทำทุกวัน ทำอย่างสม่ำเสมอ ทำวันละเล็กละน้อยสะสมไป เช่น ถ้าเราอ่านหนังสือเดือนละเล่ม ใน 10 ปีข้างหน้า เราจะมีความรู้เพิ่มขึ้นขนาดไหน

    .

    🧑‍💼 One-Person Business Philosophy

    Key takeaway สำหรับการสร้างธุรกิจเป็นของตัวเอง คือ:

    Use your skills to build something of value and monetise it through the internet.


    🧧 Barista FIRE: แผนที่สู่อิสระกึ่งเกษียณ ทำงานที่อยากทำ ไม่ใช่เพราะต้องทำ

    Speaker: วิฑูรย์ สูงกิจบูลย์ (ผู้ก่อตั้งสำนักพิมพ์ spAcebook, เจ้าของเพจ สรุปให้)

    .

    📖 Backstory

    เมื่อ 10 ปีก่อน คุณวิฑูรย์เคยทำงานเป็นผู้บริหารเงินเดือน 6 หลักและมีชีวิตที่เพียบพร้อม ทั้งเงิน บ้าน รถ และครอบครัว

    แต่สิ่งที่ขาดไป คือ ความสุข

    คุณวิฑูรย์มีทุกอย่าง แต่ไม่มีเวลาให้กับครอบครัว คุณวิฑูรย์และภรรยาต่างก็เป็นผู้บริหารที่ทำงานหนักด้วยกันทั้งคู่ คุณวิฑูรย์ทำงานหนักจนกระทั่งว่า ลูกคนหนึ่งจะต้องไปอยู่กับยาย/ย่า เพราะทั้งคุณวิฑูรย์และภรรยาไม่มีที่เลี้ยงดูลูกได้อย่างเต็มที่

    ทางเลือกของคุณวิฑูรย์มีอยู่ 2 ทาง:

    1. มีทุกอย่าง แต่ไม่มีเวลาให้กับลูก
    2. ทำงานน้อยลง แต่มีเวลาให้กับลูก

    แน่นอนว่า คุณวิฑูรย์เลือกทางเลือกที่ 2

    คุณวิฑูรย์ไม่ได้ออกจากงานในทันที แต่ก็ไม่ได้แผนที่ชัดเจนตอนออกจากงาน

    14 งาน คือ งานที่คุณวิฑูรย์ทดลองทำหลังออกจากงาน ตั้งแต่งานแปลเอกสารไปจนถึงขายของในตลาดนัด

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

    .

    🔥 FIRE & Barista FIRE

    แนวคิดที่ว่า คือ FIRE (financial independence, retire early) ซึ่งเป็นวิธีสร้างอิสระทางการเงินด้วยการเก็บออมเงินในขณะที่ยังทำงานอยู่ เพื่อให้สามารถเกษียณตอนอายุยังน้อยและยังมีเงินใช้จ่ายโดยไม่ต้องทำงานอีก

    Barista FIRE เป็น FIRE ที่ลดความเข้มข้นในการเก็บออมลงมา โดยแทนที่เราจะออมให้ได้มากพอที่จะสำหรับค่าใช้จ่ายหลังเกษียณ เราจะเก็บเงินแค่ให้มากสำหรับใช้จ่ายบางส่วน และหารายได้เสริมเพื่อดูแลค่าใช้จ่ายที่เหลือ

    .

    🪜 How to Barista FIRE

    การออมแบบ barista FIRE มีอยู่ 3 ขั้นตอน ดังนี้:

    1. ออม: เก็บเงินในระหว่างที่ยังทำงานประจำอยู่
    2. ลงทุน: เอาเงินออมไปลงทุนให้ได้ port ขนาด 25 เท่าของค่าใช้จ่ายต่อปี เพื่อให้มี passive income 4% ของค่าใช้จ่ายหลังเกษียณ
    3. เกษียณ: ออกจากงาน ใช้งานด้วย passive income + ทำงานเสริม

    .

    ☕ Example

    ตัวอย่างการออมเงินให้พอสำหรับเกษียณ:

    ถ้าเรามีค่าใช้จ่าย 120,000 บาทต่อปี เราจะต้องสร้าง port ให้ได้ขนาด:

    12,000 * 25 = 3,000,000 บาท

    และเราต้องการทำ port ให้ได้ภายใน 5 ปี (60 เดือน) เราจะต้องเก็บเงินเดือนละ:

    3,000,000 / 60 = 50,000 บาท

    .

    🙋 Start With This Question

    Barista FIRE เป็นแนวทางที่จะช่วยให้เรามีอิสระในการใช้ชีวิตมากขึ้น ซึ่งเราสามารถเริ่มได้ด้วยการถามตัวเองว่า:

    เงินขั้นต่ำที่ทำให้เราอยู่ได้โดยไม่เดือดร้อน คือ เท่าไร?


    💰 Income Maximisation Strategy: กลยุทธเรียบง่ายเพิ่มรายได้ให้ถึงขีดสุด

    Speaker: ศิวกร ปล้องใหม (Founder of Nack Siwakorn)

    .

    🚲 The Three Wheels of Income

    รายได้มาจาก 3 ทาง:

    1. หาเงิน
    2. ออมเงิน
    3. ลงทุน

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

    .

    🚴 How to Move the Wheel

    ใน 3 ทางนี้ ทางที่สำคัญที่สุด คือ หาเงิน

    ถ้าเรามีเงินทุนเยอะ เราจะสามารถออมและลงทุนได้มากขึ้น นั่นคือ วงล้อการเงินของเราจะหมุนได้ง่ายขึ้น

    เราสามารถเพิ่มรายได้ด้วย 2 วิธี:

    1. เพิ่มรายได้ที่มีอยู่
    2. หารายได้เสริม

    .

    🔥 Expand Existing Income

    การหาเงินไม่มีอยู่จริง เราไม่สามารถมองหาเงินและเจอเงินล้านตกอยู่บนพื้นได้

    ถ้าเราต้องการหาเงิน สิ่งที่เราต้องมองหาไม่เงิน แต่คือปัญหา

    ถ้าเราสามารถแก้ปัญหาให้กับกลุ่มคนที่ต้องการทางออกได้ เราก็จะได้เงินที่เรามองหา

    การทำงานทุกอย่างคือการแก้ปัญหา เช่น การติว IELTS คือการแก้ปัญหาการสอบเข้ามหาวิทยาลัยให้กับนักเรียนม.ปลาย

    เราสามารถเพิ่มรายได้ที่มีอยู่ได้ 2 ทาง:

    1. แก้ปัญหาที่ใหญ่ขึ้น: เช่น สอน IELTS ให้พนักงานที่ต้องการทำงานในองค์กรต่างชาติ ซึ่งมีกำลังจ่ายมากกว่านักเรียนม.ปลาย
    2. แก้ปัญหาให้คนมากขึ้น: เช่น เปลี่ยนการสอนแบบตัวต่อตัว เป็นสอนแบบกลุ่ม

    .

    ⌨️ Find Extra Income

    อีกวิธีในการเพิ่มรายได้ คือ ทำงานเสริม

    งานเสริมที่เราสามารถทำได้ เช่น:

    • Video editor
    • Graphic designer
    • Content creator
    • Fitness coach
    • Financial advisor
    • Tutor
    • Consultant
    • Seller
    • อื่น ๆ

    หลายคนอาจมีคำถามเกี่ยวการเริ่มทำงานเสริม เช่น:

    1. ไม่รู้จะทำอะไร
    2. ทำไม่เป็น
    3. ไม่มีทุน
    4. ไม่มี passion

    แต่ทุกคำถามมีคำตอบ:

    1. ไม่รู้จะทำอะไร → ออกไปหา ไปทดลองเพื่อให้รู้ว่าอยากทำอะไร
    2. ทำไม่เป็น → เราแค่ต้องฝึกฝนเพิ่ม
    3. ไม่มีทุน → เราสามารถเก็บเงินเพื่อสร้างทุน หรือเริ่มทำในสิ่งที่ไม่ต้องใช้เงินก่อนได้
    4. ไม่มี passion → เราไม่มี passion เพราะเราทำได้ไม่ดี และเราทำได้ไม่ดีเพราะยังไม่ได้ลองทำ ดังนั้น ทางออกคือเริ่มลงมือทำ

    เราไม่จำเป็นต้องพร้อม 100% ก่อนจะเริ่ม เราสามารถเริ่มได้โดย focus ที่ 4 อย่างนี้:

    1. Now: ทำในสิ่งที่เราสามารถทำได้ทันที
    2. Doable: ทำสิ่งที่ฝึกฝนได้/มีคนทำอยู่จริง
    3. Not too demanding: ไม่ใช่สิ่งที่หนักเกินไป/เราแบ่งเวลาให้ได้
    4. All in later: ค่อย ๆ เริ่มทีละเล็กละน้อย และเมื่อเริ่มไปได้ดี ค่อยทุ่มเต็มที่ 100%

    เราจะเริ่มงานเสริมได้ แค่ต้องมี 3 สิ่งนี้:

    1. เครื่องมือ (เช่น แล็ปท็อป)
    2. ทักษะ
    3. แนวทาง (ถ้าเป็นสิ่งที่มีคนเคยทำแล้ว ให้เราเรียนรู้จากคนเหล่านี้)

    Pro tip: สิ่งที่สำคัญสำหรับคนที่เริ่มต้นใหม่ ๆ คือการบริหารเวลา ในช่วงแรกที่เรายังทำได้ไม่ดี/ไม่คล่อง เวลาส่วนตัวของเราอาจจะถูกรบกวนบ่อยครั้ง เราจะต้องจัดการเวลาให้ดี จนกว่าทุกอย่างจะเข้าที่เข้าทาง เพื่อให้เรายังมีคุณภาพชีวิตที่ดี


    📊 Purpose First, Market Later: The Three Pillars of Lifelong Investing

    Speaker: ศรารัญย์ คาน (Investor & Content Creator, Earthh Evans)

    .

    💸 Investing Not Required, Or Not?

    กรลงทุนเป็นแค่เครื่องมือ และเราไม่จำเป็นต้องลงทุนก็ได้ถ้า:

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

    จะเห็นว่า หลาย ๆ ข้อเราอาจจะยอมรับ/จัดการไม่ได้ ซึ่งหมายความว่า การลงทุนเป็นสิ่งจำเป็นที่จะช่วยให้เราอยู่รอดได้

    .

    💖 Put Purpose First

    การตัดสินใจว่าจะลงทุนกับอะไร กับตลาดไหน และเท่าไร ขึ้นอยู่กับปัจจัย 3 อย่าง:

    1. Goal: ไม่ว่าจะเลือกว่าจะลงทุนในสินทรัพย์อะไร ไม่ว่าจะเป็นตลาดไทยหรือต่างประเทศ ทุกอย่างขึ้นกับเป้าหมายของแต่ละคนว่าต้องการมีเงินไปเพื่ออะไร
    2. Comfort: ความสบายใจต่อปัจจัยต่าง ๆ ที่เกี่ยวข้อง เช่น:
      1. ภาษีที่มากับการลงทุน
      2. ค่าธรรมเนียม
      3. ความผันผวนของค่าเงิน (เช่น อัตราแลกเปลี่ยน)
      4. ความต่างของเวลาตลาด
      5. ข่าวสารต่าง ๆ
    3. Understanding: ความเข้าใจในการลงทุน เช่น:
      1. ความเข้าใจในธุรกิจ
      2. ตัวขับเคลื่อนมูลค่า
      3. โครงสร้างอุตสาหกรรม
      4. ความเสี่ยงเฉพาะธุรกิจ

    .

    🪙 Compound Interest

    ในการลงทุน เราจะใช้ concept ที่เรียกว่า compound interest หรือดอกเบี้ยทบต้น เพื่อทำเงินให้เรา

    เพื่อจะทำให้เราได้ผลตอบแทนที่ดีที่สุดจาก compound interest เราจะต้องพิจารณา 3 อย่าง:

    1. Capital: เงินต้นที่มากพอ
    2. Time: เวลาที่มากพอ
    3. Interest: ผลตอบแทนที่มากพอ

    .

    📘 Free Investment Playbooks

    สำหรับคนที่สนใจเริ่ทต้นลงทุน สามารถโหลด playbooks ความรู้ในการลงทุนได้ฟรีบนโพสต์ของ Earthh Evans


    📃 References

  • วิเคราะห์ resumes ใน 3 ขั้นตอน ด้วย Gemini ผ่าน OpenAI library ใน Python — ตัวอย่างการทำงานใน Google Colab

    วิเคราะห์ resumes ใน 3 ขั้นตอน ด้วย Gemini ผ่าน OpenAI library ใน Python — ตัวอย่างการทำงานใน Google Colab

    บทความนี้เหมาะสำหรับบริษัทหรือ HR ที่ต้องการใช้ AI ช่วยลดเวลาในการคัดกรองผู้สมัคร เพราะเราจะมาดูวิธีวิเคราะห์ resumes ด้วย Gemini ผ่าน OpenAI library ใน Python กัน

    บทความนี้แบ่งเป็น 3 ส่วนตามขั้นตอนการวิเคราะห์ ได้แก่:

    1. Install and load libraries
    2. Set input
    3. Analyse resumes

    โดยเราจะไปดูตัวอย่างโดยใช้ Google Colab กัน (ดู code ทั้งหมดได้ที่นี่)

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


    1. ⬇️ 1. Install & Load Libraries
    2. 🔧 2. Set the Input
      1. 🧑‍💻 (1) Client
      2. 💼 (2) JD
      3. 📄 (3) Resumes
    3. ⚡ 3. Analyse the Resumes
      1. 🤖 (1) Function เรียกใช้งาน Gemini
      2. ➕ (2) Function ใส่ Input ใน Prompt
      3. 🤔 (3) วิเคราะห์ Resumes
      4. 👀 (4) Print ผลลัพธ์
    4. 😺 Code & Input Examples
    5. 📃 References

    ⬇️ 1. Install & Load Libraries

    ในขั้นแรก เราจะเรียกติดตั้งและโหลด libraries ที่จำเป็นดังนี้:

    • openai: สำหรับเรียกใช้ AI ผ่าน API
    • drive จาก google.colab: สำหรับเชื่อมต่อกับไฟล์ใน Google Drive
    • PyPDF2: สำหรับดึง text ออกจากไฟล์ PDF
    • textwrap: สำหรับลบย่อหน้าออกจาก string
    • Console จาก rich.console และ Markdown จาก rich.markdown: สำหรับ render การแสดงผล string ให้อ่านง่ายขึ้น

    ติดตั้ง:

    # Install libraries
    !pip install PyPDF2
    

    Note: Google Colab มี libraries อื่น ๆ อยู่แล้ว ทำให้เราแค่ต้องติดตั้ง PyPDF2 อย่างเดียว

    โหลด:

    # Load libraries
    
    # Connect to Gemini
    from openai import OpenAI
    
    # Connect to Google Drive
    from google.colab import drive
    
    # Extract text from PDF
    import PyPDF2
    
    # Dedent text
    import textwrap
    
    # Render markdown text
    from rich.console import Console
    from rich.markdown import Markdown
    

    🔧 2. Set the Input

    สำหรับการวิเคราะห์ resumes เราต้องการ input 3 อย่าง ได้แก่:

    1. Client: สำหรับเรียกใช้ Gemini API
    2. Job description (JD): รายละเอียดตำแหน่งงานที่กำลังต้องการพนักงาน
    3. Resumes: ข้อมูล resume ที่เราต้องการวิเคราะห์

    เราไปดูวิธีกำหนด input แต่ละตัวกัน

    .

    🧑‍💻 (1) Client

    เราสามารถกำหนด client ได้ด้วย OpenAI() ซึ่งต้องการ 2 arguments:

    1. api_key: API key สำหรับเชื่อมต่อ API
    2. base_url: base URL สำหรับเรียกใช้ AI service ซึ่งสำหรับ Gemini เราต้องกำหนดเป็น "<https://generativelanguage.googleapis.com/v1beta/openai/>"

    ในตัวอย่าง เราจะเรียกใช้ OpenAI() แบบนี้:

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

    Note: ในกรณีใช้งานจริง ให้แทนที่ "YOUR_API_KEY" ด้วย API key จริง (ดูวิธีสร้าง API key ฟรีได้ที่ Using Gemini API keys)

    .

    💼 (2) JD

    Input ที่ 2 สำหรับการวิเคราะห์ คือ JD ซึ่งเราสามารถกำหนดเป็น string ได้แบบนี้:

    # Set the job description (JD)
    web_dev_jd = """
    Senior Web Developer
    
    We're looking for a Senior Web Developer with a strong background in front-end development and a passion for creating dynamic, intuitive web experiences. The ideal candidate will have extensive experience with the entire development lifecycle, from project conception to final deployment and quality assurance. This role requires a blend of technical skill, creative collaboration, and a commitment to solving complex programming challenges.
    
    Responsibilities
    * Cooperate with designers to create clean, responsive interfaces and intuitive user experiences.
    * Develop and maintain project concepts, ensuring an optimal workflow throughout the development cycle.
    * Work with a team to manage large, complex design projects for corporate clients.
    * Complete detailed programming tasks for both front-end and back-end server code.
    * Conduct quality assurance tests to discover errors and optimize usability for all projects.
    
    Qualifications
    * Bachelor's degree in Computer Information Systems or a related field.
    * Proven experience in all stages of the development cycle for dynamic web projects.
    * Expertise in programming languages including PHP OOP, HTML5, JavaScript, CSS, and MySQL.
    * Familiarity with various PHP frameworks such as Zend, Codeigniter, and Symfony.
    * A strong background in project management and customer relations.
    """
    

    Note: ในกรณีที่ JD เป็นไฟล์ PDF เราสามารถใช้วิธีดึงข้อมูลแบบเดียวกันกับ resumes ได้

    .

    📄 (3) Resumes

    Input สุดท้าย คือ resumes ที่เราต้องการวิเคราะห์

    ในตัวอย่าง เราจะดึงข้อมูล resumes จากไฟล์ PDF ใน Google Drive ใน 3 ขั้นตอน ได้แก่:

    ขั้นที่ 1. เชื่อมต่อ Google Drive ด้วย drive.mount():

    # Connect to Google Drive
    drive.mount("/content/drive")
    

    Note: Google จะถามยืนยันการให้สิทธิ์เข้าถึงไฟล์ใน Drive ให้เรากดยืนยันเพื่อไปต่อ

    ขั้นที่ 2. กำหนด file path ของไฟล์ PDF ใน Google Drive:

    # Set resume file paths
    rs_file_paths = {
        "George Evans": "/content/drive/My Drive/Resumes/cv_george_evans.pdf",
        "Robert Richardson": "/content/drive/My Drive/Resumes/cv_robert_richardson.pdf",
        "Christine Smith": "/content/drive/My Drive/Resumes/cv_christine_smith.pdf"
    }
    

    Note: ในตัวอย่าง จะเห็นว่า เรามี resumes 3 ใบ (ดาวน์โหลด resumes ฟรีได้ที่ www.coolfreecv.com)

    ขั้นที่ 3. ดึง text ออกจาก resumes ด้วย for loop และ PyPDF2:

    # Extract resume texts
    
    # Instantiate a collector
    rs_texts = {}
    
    # Loop through resume files to get text
    for key in rs_file_paths:
    
        # Instantiate an empty string to store the extracted text
        rs_text = ""
    
        # Open the PDF file
        reader = PyPDF2.PdfReader(rs_file_paths[key])
    
        # Loop through the pages
        for i in range(len(reader.pages)):
    
            # Extract the text from the page
            text = reader.pages[i].extract_text()
    
            # Append the text to the string
            rs_text += text
    
        # Collect the extracted text
        rs_texts[key] = rs_text
    

    ตัวอย่าง PDF และข้อมูลที่ดึงจาก PDF:

    Source: www.coolfreecv.com
    Contact  
    +1 (970) 343  888 999 
    george.evans@gmail.com  
    <https://www.coolfreecv.com>  
    32 ELM STREET MADISON, SD 
    57042  
     George  Evans  
    PHP / OOP   
    Zend Framework  Summary  
    Senior Web Developer specializing in front end development . 
    Experienced with all stages of the development cycle for dynamic 
    web projects. Well -versed in numerous programming languages 
    including HTML5, PHP OOP, JavaScript, CSS, MySQL. Strong 
    background in project management and customer relations. 
    Perceived as versatile, unconventional and committed, I am 
    looking for new and interesting programming challenges.  
    Experience  
    Web Developer - 09/201 8 to 05/20 22 
    Luna Web Design, New York  
    • Cooperate with designers to create clean interfaces and 
    simple, intuitive interactions and experiences.  
    • Develop project concepts and maintain optimal workflow.  
    • Work with senior developer to manage large, complex 
    design projects for corporate clients.  
    • Complete detailed programming and development tasks 
    for front end public and internal websites as well as 
    challenging back -end server code.  
    • Carry out quality assurance tests to discover errors and 
    optimize usability.  
    Education  
    Bachelor of Science: Computer Information Systems  - 2018  
    Columbia University, NY  
     
    Certifications  
    PHP Framework (certificate): Zend, Codeigniter, Symfony. 
    Programming Languages: JavaScript, HTML5, PHP OOP, CSS, SQL, 
    MySQL.  
    Reference  
    Adam Smith - Luna Web Design  
    adam.smith@luna.com  +1(970 )555 555  Skills   
    JavaScript   Symfony Framework
    

    ⚡ 3. Analyse the Resumes

    ในขั้นสุดท้าย เราจะเปรียบเทียบความเหมาะสมของ resumes กับตำแหน่งงาน (JD) ใน 4 ขั้นตอน ดังนี้:

    1. สร้าง function เพื่อเรียกใช้ Gemini
    2. สร้าง function เพื่อใส่ input ใน prompt
    3. วิเคราะห์ resumes โดยใช้ for loop และ functions จากข้อ 1, 2
    4. Print ผลการวิเคราะห์

    .

    🤖 (1) Function เรียกใช้งาน Gemini

    ในขั้นแรก เราจะสร้าง function สำหรับเรียกใช้ Gemini เพื่อให้ง่ายในการใช้งาน AI

    ในตัวอย่าง เราจะกำหนด 3 arguments สำหรับ function:

    1. prompts: list เก็บ system prompt และ user prompt
    2. model: model ของ Gemini ที่เราจะเรียกใช้ (เช่น Gemini 2.5 Flash)
    3. temp: ระดับความคิดสร้างสรรค์ของ model โดยมีค่าระหว่าง 0 และ 2 โดย 0 จะทำให้ model ให้คำตอบเหมือนกันทุกครั้ง และ 2 คำตอบจะแตกต่างกันทุกครั้ง
    # Create a function to get a Gemini response
    def get_gemini_response(prompts, model, temp):
    
        # Generate a response
        response = client.chat.completions.create(
    
            # Set the prompts
            messages=prompts,
    
            # Set the model
            model=model,
    
            # Set the temperature
            temperature=temp
        )
    
        # Return the response
        return response.choices[0].message.content
    

    .

    ➕ (2) Function ใส่ Input ใน Prompt

    ในขั้นที่ 2 เราจะสร้าง function เพื่อประกอบ input เข้ากับ prompt เพื่อพร้อมที่จะนำไปใช้ใน function ในขั้นที่ 1

    ในตัวอย่างเราจะสร้าง function แบบนี้:

    # Create a function to concatenate prompt + JD + resume
    def concat_input(jd_text, rs_text):
    
        # Set the system prompt
        system_prompt = """
        # 1. Your Role
        You are an expert technical recruiter and resume analyst.
        """
    
        # Set the user prompt
        user_prompt = f"""
        # 2. Your Task
        Your task is to meticulously evaluate a candidate's resume against a specific job description (JD) and provide a detailed pre-screening report.
    
        Your analysis must be structured with the following sections and include specific, data-driven insights.
    
        ## 1. Strengths
        - Identify and elaborate on top three key strengths.
        - For each strength, briefly provide specific evidence from the resume (e.g., "The candidate's experience with Python and Django, as shown in their role at Acme Corp, directly addresses the JD's requirement for...") and explain how it directly fulfills a requirement in the JD.
    
        ## 2. Weaknesses
        - Identify top three areas where the candidate's experience or skills may not fully align with the JD's requirements.
        - For each point, briefly explain the potential concern and why it might be a risk for the role (e.g., "The JD requires experience with AWS, but the resume only mentions exposure to Azure. This could indicate a gap in cloud infrastructure expertise.").
    
        ## 3. Candidate Summary
        - Draft a concise summary of the candidate's professional background.
        - Emphasise their JD-relevant core responsibilities, key achievements, and career progression as evidenced in the resume.
    
        ## 4. Overall Fit Score
        - Provide a numerical score from 1 to 100, representing the overall alignment of the candidate's profile with the JD.
        - A higher score indicates a stronger match: 80-100 = best match; 60-80 = strong match; 0-40 = weak match.
    
        ## 5. Hiring Recommendation
        - Conclude with a clear, binary hiring recommendation: "🟢 Proceed to interview", "🟡 Add to waitlist", or "🔴 Do not proceed".
        - Justify this recommendation with a brief, objective explanation based on the analysis above.
    
        ---
    
        # 3. Your Output
        - Use a professional and objective tone.
        - Base your analysis solely on the provided resume and JD. Do not make assumptions.
        - Be concise and to the point; no more than 30 words per sentence; the hiring manager needs to quickly grasp the key findings.
        - Format your final report using markdown headings and bullet points for readability.
    
        Output template:
        '''
        # [candidate's name (Title Case)] ([fit score]/100)
    
        [recommendation]: [justification]
    
        ## Profile Summary:
        [summary]
    
        ## Strengths:
        - [strength 1]
        - [strength 2]
        - [strength 3]
    
        ## Weaknesses:
        - [weakness 1]
        - [weakness 2]
        - [weakness 3]
        '''
    
        ---
    
        # 4. Your Input
        **1. JD:**
        {jd_text}
    
        **2. Resume:**
        {rs_text}
    
        ---
    
        Generate the report.
        """
    
        # Collect prompts
        prompts = [
            {
                "role": "system",
                "content": textwrap.dedent(system_prompt)
            },
            {
                "role": "user",
                "content": textwrap.dedent(user_prompt)
            }
        ]
    
        # Return the prompts
        return prompts
    

    Note: เราใช้ textwrap.dedent() เพื่อลบย่อหน้าที่เกิดจาก indent ใน function ออกจาก prompt เพื่อป้องกันความผิดพลาดในการประมวลผลของ AI และประหยัด input token

    .

    🤔 (3) วิเคราะห์ Resumes

    ในขั้นที่ 3 ซึ่งเป็นขั้นที่สำคัญที่สุด เราจะวิเคราะห์ resumes โดย:

    • ใช้ functions จากขั้นที่ 1 และ 2 เพื่อสร้าง prompt และส่ง prompt ให้กับ Gemini
    • ใช้ for loop เพื่อส่ง resumes ให้กับ Gemini จนครบทุกใบ
    # Instantiate a response collector
    results = {}
    
    # Loop through the resumes
    for rs_name, rs_text in rs_texts.items():
    
        # Create the prompts
        prompts = concat_input(web_dev_jd, rs_text)
    
        # Get the Gemini response
        response = get_gemini_response(prompts=prompts, model="gemini-2.5-flash", temp=0.5)
    
        # Collect the response
        results[rs_name] = response
    

    เมื่อรัน code นี้แล้ว เราจะได้ผลลัพธ์เก็บไว้ใน results

    .

    👀 (4) Print ผลลัพธ์

    สุดท้าย เราจะ print ผลการวิเคราะห์ออกมา โดย:

    • ใช้ for loop ช่วย print ผลจนครบ
    • ใช้ Console กับ Markdown เพื่อทำให้ข้อความอ่านง่ายขึ้น:
    # Instantiate a console
    console = Console()
    
    # Instantiate a counter
    i = 1
    
    # Print the results
    for rs_name, analysis_result in results.items():
    
        # Print the resume name
        print(f"👇 {i}. {rs_name}:")
    
        # Print the response
        console.print(Markdown(analysis_result))
    
        # Add spacers and divider
        print("\\n")
        print("-----------------------------------------------------------")
        print("\\n")
    
        # Add a counter
        i += 1
    

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

    ในตัวอย่าง จะเห็นได้ว่า George Evans เหมาะที่จะเป็น Senior Web Developer


    😺 Code & Input Examples

    • ดูตัวอย่าง code ได้ที่ Google Colab
    • ดูตัวอย่าง JD และ resumes ได้ที่ JD & Resumes

    📃 References

  • 4 ขั้นตอนในการใช้ google-genai library เพื่อทำงานกับ Gemini API — ตัวอย่างการสร้างสูตรอาหารที่ไม่เหมือนใคร

    4 ขั้นตอนในการใช้ google-genai library เพื่อทำงานกับ Gemini API — ตัวอย่างการสร้างสูตรอาหารที่ไม่เหมือนใคร

    ในบทความนี้ เราจะมาดู 4 ขั้นตอนในการใช้งาน google-genai ซึ่งเป็น official library สำหรับทำงานกับ Gemini API ผ่านตัวอย่างการสร้างสูตรอาหารใน Google Colab กัน:

    1. Import packages
    2. Create client
    3. Create function
    4. Generate response

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


    1. 📦 Import Packages
    2. 🧑‍💼 Create Client
    3. 📲 Create Function
    4. 📬 Generate Response
      1. 🤖 Set Model
      2. 🧑‍💻 Set User Prompt
      3. 🛠️ Set Configuration
      4. 📖 Generate Response
      5. 🖨️ Print Response
    5. 😺 Google Colab
    6. 📃 References

    📦 Import Packages

    เริ่มแรก เราจะ import 4 packages ที่จำเป็น ได้แก่:

    FromFunction/ClassFor
    googlegenaiทำงานกับ Gemini API
    google.genai.typesGenerateContentConfigตั้งค่า Gemini
    google.colabuserdataเรียก API key จากเมนู Secrets ใน Google Colab
    pydanticBaseModelกำหนดโครงสร้างของ response จาก Gemini
    # Import packages
    
    # google-genai library
    from google import genai
    from google.genai.types import GenerateContentConfig
    
    # Secret key
    from google.colab import userdata
    
    # pydantic
    from pydantic import BaseModel
    

    🧑‍💼 Create Client

    ในขั้นที่ 2 เราจะสร้าง client สำหรับทำงานกับ Gemini API

    เพื่อความปลอดภัย เราจะเก็บ API key ไว้ในเมนู Secrets ของ Google Colab

    เราสามารถเพิ่ม API key ด้วยการ import ผ่านปุ่ม “Gemini API keys” หรือผ่านการเพิ่ม API key เองด้วยปุ่ม “Add new secret”:

    หลังสร้าง API key ใน Secrets แล้ว เราสามารถเรียกใช้ API key ได้ด้วย userdata.get() ซึ่งต้องการ 1 argument คือ ชื่อ secret:

    # Get API key
    my_api = userdata.get("GOOGLE_API_KEY")
    

    จากนั้น เราจะสร้าง client ด้วย genai.Client() ซึ่งต้องการ 1 argument คือ API key:

    # Create client
    client = genai.Client(api_key=my_api)
    

    Note:

    • ในกรณีที่เราไม่ห่วงความปลอดภัยของ API key เราสามารถใส่ API key ใน genai.Client() ได้โดยตรง เช่น genai.Client(api_key="g04821...")
    • เราสามารถสร้าง API key ได้ฟรี โดยไปที่ Google AI Studio และกด “Create API key”

    📲 Create Function

    ในขั้นที่ 3 เราจะสร้าง function สำหรับเรียกใช้ Gemini ซึ่งต้องการ 3 arguments:

    1. model: Gemini model ที่เราจะเรียกใช้
    2. user_prompt: กำหนด user prompt
    3. config: กำหนดการตั้งค่าต่าง ๆ ของ model

    โดยทั้ง 3 arguments จะอยู่ใน client.models.generate_content():

    # Create a function to get Gemini response
    def get_response(model, user_prompt, config):
    
        # Get response
        response = client.models.generate_content(
    
            # Set model
            model=model,
    
            # Set user prompt
            contents=user_prompt,
    
            # Set config
            config=config
        )
    
        # Return response
        return response.text
    

    📬 Generate Response

    ในขั้นที่ 4 เราจะ get response จาก Gemini โดยใช้ function ที่เราสร้างในขั้นที่ 3

    เนื่องจาก function ต้องการ 3 arguments เราจะต้องกำหนด 3 สิ่งนี้ก่อนที่จะสร้าง response ได้:

    1. Model
    2. User prompt
    3. Configuration

    .

    🤖 Set Model

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

    # Set model
    gemini_model = "gemini-2.5-flash"
    

    Note: ดูชื่อ model อื่น ๆ ได้ที่ Gemini Models

    .

    🧑‍💻 Set User Prompt

    สำหรับ user prompt เราสามารถกำหนดเป็น string ได้แบบนี้:

    # Set user prompt
    gemini_user_prompt = """
    Create a healthy Thai-inspired burger for one person.
    
    Protein: chicken or tofu
    Bun: whole-wheat if possible (or lettuce wrap)
    
    Deliver (match field names exactly):
    - `menu` (string)
    - `ingredient` (list of items with name, description, amount, unit)
    - `steps` (30-word strings)
    - `calorie_kcal` (float, total for the dish)
    """
    

    .

    🛠️ Set Configuration

    สำหรับ configuration เราสามารถตั้งค่า model ได้หลายค่า

    ในตัวอย่างนี้ เราจะเลือกกำหนด 3 ค่า ได้แก่:

    1. System prompt
    2. Temperature
    3. Output type and structure

    ค่าที่ 1. System prompt คือ prompt ที่กำหนดพฤติกรรมของ Gemini ในการตอบสนองต่อ user prompt ของเรา

    เราสามารถกำหนด system prompt เป็น string ได้แบบนี้:

    # Set system prompt
    system_prompt = """
    You are a highly experienced home cook specialising in healthy Thai-style food.
    
    Constraints:
    - Single-serving
    - Favour grilling/pan-searing over deep-frying
    - Keep ingredients common in Thai kitchens
    - Keep steps <=7
    - Include an approximate total calories for the whole dish
    - Keep language simple
    - Return JSON only that matches the given schema exactly (no extra fields)
    """
    

    ค่าที่ 2. Temperature มีค่าระหว่าง 0 และ 2 โดย:

    • 0 จะทำให้ response ตายตัว (deterministic) มากขึ้น
    • 2 จะทำให้ response สร้างสรรค์ (creative) มากขึ้น

    Note: ค่า default ของ temperature อยู่ที่ 1 (Generate content with the Gemini API in Vertex AI)

    ในตัวอย่าง เราจะกำหนด temperature เป็น 2 เพื่อให้ response มีความสร้างสรรค์สูงสุด:

    # Set temperature
    temp = 2
    

    ค่าที่ 3. สำหรับ output type และ structure เราจะกำหนดดังนี้:

    กำหนด type เป็น "application/json" เพื่อให้ response อยู่ในรูป JSON object:

    # Set output type
    output_type = "application/json"
    

    Note: ดู type อื่น ๆ ได้ที่ Structured output

    กำหนดโครงสร้างของ JSON object ด้วย class และ BaseModel:

    # Set output structure
    class Ingredient(BaseModel):
        name: str
        description: str
        amount: float
        unit: str
    
    class OutputStructure(BaseModel):
        menu: str
        ingredient: list[Ingredient]
        steps: list[str]
        calorie_kcal: float
    

    Note: ดูวิธีใช้ BaseModel ได้ที่ JSON Schema

    หลังกำหนด system prompt, temperature, และ output type กับ structure แล้ว ให้เรารวมค่าทั้งหมดไว้ใน GenerateContentConfig() แบบนี้:

    # Set configuration
    gemini_config = GenerateContentConfig(
    
        # Set system prompt
        system_instruction=system_prompt,
    
        # Set temperature
        temperature=temp,
    
        # Set response type
        response_mime_type=output_type,
    
        # Set response structure
        response_schema=OutputStructure
    )
    

    Note: ดูค่าอื่น ๆ ที่เรากำหนดใน GenerateContentConfig() ได้ที่ Content generation parameters

    .

    📖 Generate Response

    หลังจากกำหนด arguments แล้ว เราจะเรียกใช้ function เพื่อ get response แบบนี้:

    # Generate a recipe
    recipe = get_response(
    
        # Set model
        model=gemini_model,
    
        # Set user prompt
        user_prompt=gemini_user_prompt,
    
        # Set configuration
        config=gemini_config
    )
    

    .

    สุดท้าย เราจะดู response ด้วย print():

    # Print response
    print(recipe)
    

    ผลลัพธ์:

    {
      "menu": "Thai Chicken Burger",
      "ingredient": [
        {
          "name": "Ground Chicken",
          "description": "Lean ground chicken",
          "amount": 150.0,
          "unit": "g"
        },
        {
          "name": "Whole-wheat Burger Bun",
          "description": "Standard size",
          "amount": 1.0,
          "unit": "unit"
        },
        {
          "name": "Lime Juice",
          "description": "Freshly squeezed",
          "amount": 1.0,
          "unit": "tablespoon"
        },
        {
          "name": "Fish Sauce",
          "description": "Thai fish sauce",
          "amount": 1.0,
          "unit": "tablespoon"
        },
        {
          "name": "Fresh Ginger",
          "description": "Grated",
          "amount": 1.0,
          "unit": "teaspoon"
        },
        {
          "name": "Garlic",
          "description": "Minced",
          "amount": 1.0,
          "unit": "clove"
        },
        {
          "name": "Cilantro",
          "description": "Fresh, chopped",
          "amount": 2.0,
          "unit": "tablespoons"
        },
        {
          "name": "Green Onion",
          "description": "Chopped",
          "amount": 1.0,
          "unit": "tablespoon"
        },
        {
          "name": "Red Chilli",
          "description": "Finely minced (optional)",
          "amount": 0.5,
          "unit": "teaspoon"
        },
        {
          "name": "Lettuce Leaf",
          "description": "Fresh, crisp",
          "amount": 1.0,
          "unit": "large"
        },
        {
          "name": "Cucumber",
          "description": "Sliced thinly",
          "amount": 3.0,
          "unit": "slices"
        },
        {
          "name": "Cooking Oil",
          "description": "Any neutral oil",
          "amount": 1.0,
          "unit": "teaspoon"
        }
      ],
      "steps": [
        "Combine ground chicken with fish sauce, lime juice, grated ginger, minced garlic, chopped cilantro, and green onion in a bowl. Mix thoroughly.",
        "Form the seasoned chicken mixture into a single, uniform burger patty. If using chilli, incorporate it now.",
        "Heat cooking oil in a non-stick pan over medium heat. Cook the chicken patty for 5-7 minutes per side, or until it is thoroughly cooked through.",
        "While the patty cooks, lightly toast the whole-wheat burger bun in a dry pan or toaster until golden brown.",
        "Assemble your burger: Place the cooked chicken patty on the bottom half of the toasted bun. Top with fresh lettuce and cucumber slices.",
        "Complete the burger with the top bun. Serve immediately and enjoy your healthy Thai-inspired meal."
      ],
      "calorie_kcal": 450.0
    }
    

    เท่านี้ก็จบ flow การทำงานกับ Gemini API ด้วย google-genai library แล้ว


    😺 Google Colab

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


    📃 References

  • วิธีใช้ 9 arguments ใน read_csv() จาก pandas library เพื่อโหลดข้อมูลใน Python — ตัวอย่างการโหลดข้อมูลการแข่งขันฟุตบอล

    วิธีใช้ 9 arguments ใน read_csv() จาก pandas library เพื่อโหลดข้อมูลใน Python — ตัวอย่างการโหลดข้อมูลการแข่งขันฟุตบอล

    pandas เป็น Python library สำหรับทำงานกับข้อมูลในรูปแบบตาราง (tabular data) และมี functions หลากหลายสำหรับโหลดข้อมูลเข้ามาใน Python

    โดยหนึ่งใน functions ที่นิยมใช้กันมากที่สุด ได้แก่ read_csv() ซึ่งใช้โหลดข้อมูล CSV (Comma-Separated Values) และมี arguments หลัก 9 อย่าง ได้แก่:

    1. filepath_or_buffer: file path, ชื่อไฟล์, หรือ URL ของไฟล์ที่ต้องการโหลด
    2. sep: กำหนด delimiter
    3. header: กำหนด row ที่เป็นหัวตาราง
    4. skiprows: กำหนด rows ที่ไม่ต้องการโหลด
    5. nrows: เลือกจำนวน rows ที่ต้องการโหลด
    6. usecols: กำหนด columns ที่ต้องการโหลด
    7. index_col: กำหนด column ที่จะเป็น index
    8. names: กำหนดชื่อของ columns
    9. dtype: กำหนดประเภทข้อมูล (data types) ของ columns

    ในบทความนี้ เราจะมาดูวิธีใช้ทั้ง 9 arguments ของ read_csv() เพื่อโหลดตัวอย่างข้อมูลการแข่งขันฟุตบอลในอังกฤษกัน

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


    1. 🏁 Getting Started
    2. 🗃️ Argument #1. filepath_or_buffer
    3. 🤺 Argument #2. sep
    4. 😶‍🌫️ Argument #3. header
    5. 🛑 Argument #4. skiprows
    6. 📋 Argument #5. nrows
    7. ☑️ Argument #6. usecols
    8. 🔢 Argument #7. index_col
    9. 🔠 Argument #8. names
    10. ⏹️ Argument #9. dtype
    11. ⚡ Summary
    12. 😺 GitHub
    13. 📃 References

    🏁 Getting Started

    ก่อนเริ่มใช้งาน read_csv() เราต้องติดตั้งและโหลด pandas ก่อน:

    # Install pandas
    !pip install pandas
    
    # Import pandas
    import pandas as pd
    

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


    🗃️ Argument #1. filepath_or_buffer

    filepath_or_buffer เป็น argument หลักที่เราจะต้องกำหนดทุกครั้งที่เรียกใช้ read_csv()

    ยกตัวอย่างเช่น เรามีข้อมูลการแข่งขันฟุตบอล (matches_clean.csv):

    MatchID,HomeTeam,AwayTeam,HomeGoals,AwayGoals,MatchDate
    M001,Manchester United,Chelsea,2,1,2024-08-14
    M002,Liverpool,Arsenal,1,1,2024-08-20
    M003,Tottenham,Everton,3,0,2024-09-02
    M004,Man City,Aston Villa,4,2,2024-09-15
    M005,Newcastle,West Ham,0,0,2024-09-22
    M006,Brighton,Leeds,2,3,2024-09-29
    

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

    # Load the dataset
    df1 = pd.read_csv("matches_clean.csv")
    
    # View the result
    print(df1)
    

    ผลลัพธ์:

      MatchID           HomeTeam     AwayTeam  HomeGoals  AwayGoals   MatchDate
    0    M001  Manchester United      Chelsea          2          1  2024-08-14
    1    M002          Liverpool      Arsenal          1          1  2024-08-20
    2    M003          Tottenham      Everton          3          0  2024-09-02
    3    M004           Man City  Aston Villa          4          2  2024-09-15
    4    M005          Newcastle     West Ham          0          0  2024-09-22
    5    M006           Brighton        Leeds          2          3  2024-09-29
    

    🤺 Argument #2. sep

    sep ใช้กำหนด delimiter หรือเครื่องหมายในการแบ่ง columns โดย default ของ sep คือ "," ทำให้ปกติ เราไม่ต้องกำหนด sep เมื่อไฟล์เป็น CSV

    เราจะใช้ sep เมื่อข้อมูลมี delimiter อื่น เช่น ";" (matches_semicolon.txt):

    MatchID;HomeTeam;AwayTeam;HomeGoals;AwayGoals;MatchDate
    M001;Manchester United;Chelsea;2;1;2024-08-14
    M002;Liverpool;Arsenal;1;1;2024-08-20
    M003;Tottenham;Everton;3;0;2024-09-02
    M004;Man City;Aston Villa;4;2;2024-09-15
    M005;Newcastle;West Ham;0;0;2024-09-22
    M006;Brighton;Leeds;2;3;2024-09-29
    

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

    # Load the dataset with ";" as delim
    df2 = pd.read_csv("matches_semicolon.csv", sep=";")
    
    # View the result
    print(df2)
    

    ผลลัพธ์:

      MatchID           HomeTeam     AwayTeam  HomeGoals  AwayGoals   MatchDate
    0    M001  Manchester United      Chelsea          2          1  2024-08-14
    1    M002          Liverpool      Arsenal          1          1  2024-08-20
    2    M003          Tottenham      Everton          3          0  2024-09-02
    3    M004           Man City  Aston Villa          4          2  2024-09-15
    4    M005          Newcastle     West Ham          0          0  2024-09-22
    5    M006           Brighton        Leeds          2          3  2024-09-29
    

    😶‍🌫️ Argument #3. header

    header ใช้กำหนด row ที่จะเป็นหัวตาราง

    เราจะใช้ header เมื่อ rows แรกของข้อมูลมีข้อมูลอื่น เช่น metadata (matches_with_metadata.txt):

    # UK Football Matches Data
    # Created for practice with pd.read_csv()
    MatchID,HomeTeam,AwayTeam,HomeGoals,AwayGoals,MatchDate
    M001,Manchester United,Chelsea,2,1,2024-08-14
    M002,Liverpool,Arsenal,1,1,2024-08-20
    M003,Tottenham,Everton,3,0,2024-09-02
    M004,Man City,Aston Villa,4,2,2024-09-15
    M005,Newcastle,West Ham,0,0,2024-09-22
    M006,Brighton,Leeds,2,3,2024-09-29
    

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

    # Load the dataset where the header is the 3rd row
    df3 = pd.read_csv("matches_with_metadata.txt", header=2)
    
    # View the result
    print(df3)
    

    ผลลัพธ์:

      MatchID           HomeTeam     AwayTeam  HomeGoals  AwayGoals   MatchDate
    0    M001  Manchester United      Chelsea          2          1  2024-08-14
    1    M002          Liverpool      Arsenal          1          1  2024-08-20
    2    M003          Tottenham      Everton          3          0  2024-09-02
    3    M004           Man City  Aston Villa          4          2  2024-09-15
    4    M005          Newcastle     West Ham          0          0  2024-09-22
    5    M006           Brighton        Leeds          2          3  2024-09-29
    

    จะสังเกตว่า metadata จะไม่ถูกโหลดเข้ามาด้วย

    Note: เราสามารถกำหนด header=None ในกรณีที่ข้อมูลไม่มีหัวตาราง เช่น matches_no_header.csv:

    M001,Manchester United,Chelsea,2,1,2024-08-14
    M002,Liverpool,Arsenal,1,1,2024-08-20
    M003,Tottenham,Everton,3,0,2024-09-02
    M004,Man City,Aston Villa,4,2,2024-09-15
    M005,Newcastle,West Ham,0,0,2024-09-22
    M006,Brighton,Leeds,2,3,2024-09-29
    

    🛑 Argument #4. skiprows

    skiprows ใช้เลือก rows ที่เราไม่ต้องการโหลดเข้ามาใน Python ซึ่งเราสามารถกำหนดได้ 2 แบบ:

    1. กำหนดเป็น int (เช่น 2) ในกรณีที่ต้องการข้าม row เดียว
    2. กำหนดเป็น list (เช่น [0, 1, 2]) ในกรณีที่ต้องการข้ามมากกว่า 1 rows

    ยกตัวอย่างเช่น เราต้องการข้าม 2 บรรทัดแรกซึ่งเป็น metadata:

    # UK Football Matches Data
    # Created for practice with pd.read_csv()
    MatchID,HomeTeam,AwayTeam,HomeGoals,AwayGoals,MatchDate
    M001,Manchester United,Chelsea,2,1,2024-08-14
    M002,Liverpool,Arsenal,1,1,2024-08-20
    M003,Tottenham,Everton,3,0,2024-09-02
    M004,Man City,Aston Villa,4,2,2024-09-15
    M005,Newcastle,West Ham,0,0,2024-09-22
    M006,Brighton,Leeds,2,3,2024-09-29
    

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

    # Load the dataset, skipping the metadata
    df4 = pd.read_csv("matches_with_metadata.txt", skiprows=[0, 1])
    
    # View the result
    print(df4)
    

    ผลลัพธ์:

      MatchID           HomeTeam     AwayTeam  HomeGoals  AwayGoals   MatchDate
    0    M001  Manchester United      Chelsea          2          1  2024-08-14
    1    M002          Liverpool      Arsenal          1          1  2024-08-20
    2    M003          Tottenham      Everton          3          0  2024-09-02
    3    M004           Man City  Aston Villa          4          2  2024-09-15
    4    M005          Newcastle     West Ham          0          0  2024-09-22
    5    M006           Brighton        Leeds          2          3  2024-09-29
    

    📋 Argument #5. nrows

    nrows ใช้เลือก rows ที่เราต้องการโหลดเข้ามาใน Python

    เช่น แทนที่จะโหลดข้อมูลทั้งหมด:

    MatchID,HomeTeam,AwayTeam,HomeGoals,AwayGoals,MatchDate
    M001,Manchester United,Chelsea,2,1,2024-08-14
    M002,Liverpool,Arsenal,1,1,2024-08-20
    M003,Tottenham,Everton,3,0,2024-09-02
    M004,Man City,Aston Villa,4,2,2024-09-15
    M005,Newcastle,West Ham,0,0,2024-09-22
    M006,Brighton,Leeds,2,3,2024-09-29
    

    เราจะโหลดข้อมูล 3 rows แรกด้วย nrows แบบนี้:

    # Load the first 3 rows
    df5 = pd.read_csv("matches_clean.csv", nrows=3)
    
    # View the result
    print(df5)
    

    ผลลัพธ์:

      MatchID           HomeTeam AwayTeam  HomeGoals  AwayGoals   MatchDate
    0    M001  Manchester United  Chelsea          2          1  2024-08-14
    1    M002          Liverpool  Arsenal          1          1  2024-08-20
    2    M003          Tottenham  Everton          3          0  2024-09-02
    

    ☑️ Argument #6. usecols

    usecols ใช้กำหนด columns ที่เราต้องการโหลดเข้ามาใน Python

    ยกตัวอย่างเช่น เลือกเฉพาะ HomeTeam และ HomeGoals จาก:

    MatchID,HomeTeam,AwayTeam,HomeGoals,AwayGoals,MatchDate
    M001,Manchester United,Chelsea,2,1,2024-08-14
    M002,Liverpool,Arsenal,1,1,2024-08-20
    M003,Tottenham,Everton,3,0,2024-09-02
    M004,Man City,Aston Villa,4,2,2024-09-15
    M005,Newcastle,West Ham,0,0,2024-09-22
    M006,Brighton,Leeds,2,3,2024-09-29
    

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

    # Load only HomeTeam and HomeGoals
    df6 = pd.read_csv("matches_clean.csv", usecols=["HomeTeam", "HomeGoals"])
    
    # View the result
    print(df6)
    

    ผลลัพธ์:

                HomeTeam  HomeGoals
    0  Manchester United          2
    1          Liverpool          1
    2          Tottenham          3
    3           Man City          4
    4          Newcastle          0
    5           Brighton          2
    

    🔢 Argument #7. index_col

    index_col ใช้กำหนด column ที่เป็น index ของข้อมูล เช่น MatchID:

    MatchID,HomeTeam,AwayTeam,HomeGoals,AwayGoals,MatchDate
    M001,Manchester United,Chelsea,2,1,2024-08-14
    M002,Liverpool,Arsenal,1,1,2024-08-20
    M003,Tottenham,Everton,3,0,2024-09-02
    M004,Man City,Aston Villa,4,2,2024-09-15
    M005,Newcastle,West Ham,0,0,2024-09-22
    M006,Brighton,Leeds,2,3,2024-09-29
    

    เราจะใช้ index_col แบบนี้:

    # Load the dataset with MatchID as index col
    df7 = pd.read_csv("matches_clean.csv", index_col="MatchID")
    
    # View the result
    print(df7)
    

    ผลลัพธ์:

                      HomeTeam     AwayTeam  HomeGoals  AwayGoals   MatchDate
    MatchID
    M001     Manchester United      Chelsea          2          1  2024-08-14
    M002             Liverpool      Arsenal          1          1  2024-08-20
    M003             Tottenham      Everton          3          0  2024-09-02
    M004              Man City  Aston Villa          4          2  2024-09-15
    M005             Newcastle     West Ham          0          0  2024-09-22
    M006              Brighton        Leeds          2          3  2024-09-29
    

    🔠 Argument #8. names

    names ใช้กำหนดชื่อ columns ซึ่งเราจะใช้เมื่อ:

    • ข้อมูลไม่มีหัวตาราง
    • ต้องการเปลี่ยนชื่อ columns

    ยกตัวอย่างเช่น ใส่ชื่อ columns ให้กับ matches_no_header.csv:

    M001,Manchester United,Chelsea,2,1,2024-08-14
    M002,Liverpool,Arsenal,1,1,2024-08-20
    M003,Tottenham,Everton,3,0,2024-09-02
    M004,Man City,Aston Villa,4,2,2024-09-15
    M005,Newcastle,West Ham,0,0,2024-09-22
    M006,Brighton,Leeds,2,3,2024-09-29
    

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

    # Set col names
    col_names = [
        "id",
        "home",
        "away",
        "home_goals",
        "away_goals",
        "date"
    ]
    
    # Load the dataset with custom col names
    df8 = pd.read_csv("matches_no_header.csv", names=col_names)
    
    # View the result
    print(df8)
    

    ผลลัพธ์:

         id               home         away  home_goals  away_goals        date
    0  M001  Manchester United      Chelsea           2           1  2024-08-14
    1  M002          Liverpool      Arsenal           1           1  2024-08-20
    2  M003          Tottenham      Everton           3           0  2024-09-02
    3  M004           Man City  Aston Villa           4           2  2024-09-15
    4  M005          Newcastle     West Ham           0           0  2024-09-22
    5  M006           Brighton        Leeds           2           3  2024-09-29
    

    ⏹️ Argument #9. dtype

    dtype ใช้กำหนดประเภทข้อมูลของ columns

    ยกตัวอย่างเช่น กำหนด ประเภทข้อมูลของ MatchID, HomeGoals, และ AwayGoals จาก matches_clean.csv:

    MatchID,HomeTeam,AwayTeam,HomeGoals,AwayGoals,MatchDate
    M001,Manchester United,Chelsea,2,1,2024-08-14
    M002,Liverpool,Arsenal,1,1,2024-08-20
    M003,Tottenham,Everton,3,0,2024-09-02
    M004,Man City,Aston Villa,4,2,2024-09-15
    M005,Newcastle,West Ham,0,0,2024-09-22
    M006,Brighton,Leeds,2,3,2024-09-29
    

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

    # Set col data types
    col_dtypes = {
        "MatchID": str,
        "HomeGoals": "int32",
        "AwayGoals": "int32"
    }
    
    # Load the dataset, specifying data types for MatchID, HomeGoals, and AwayGoals
    df9 = pd.read_csv("matches_clean.csv", dtype=col_dtypes)
    
    # View the result
    df9.info()
    

    ผลลัพธ์:

    <class 'pandas.core.frame.DataFrame'>
    RangeIndex: 6 entries, 0 to 5
    Data columns (total 6 columns):
     #   Column     Non-Null Count  Dtype
    ---  ------     --------------  -----
     0   MatchID    6 non-null      object
     1   HomeTeam   6 non-null      object
     2   AwayTeam   6 non-null      object
     3   HomeGoals  6 non-null      int32
     4   AwayGoals  6 non-null      int32
     5   MatchDate  6 non-null      object
    dtypes: int32(2), object(4)
    memory usage: 372.0+ bytes
    

    ⚡ Summary

    ในบทความนี้ เราได้ไปดูวิธีการใช้ 9 arguments ของ read_csv() จาก pandas เพื่อโหลดข้อมูลใน Python กัน:

    1. filepath_or_buffer: ไฟล์ที่ต้องการโหลด
    2. sep: delimiter ในไฟล์
    3. header: row ที่เป็นหัวตาราง
    4. skiprows: rows ที่ไม่ต้องการโหลด
    5. nrows: จำนวน rows ที่ต้องการโหลด
    6. usecols: columns ที่ต้องการโหลด
    7. index_col: column ที่จะเป็น index
    8. names: ชื่อของ columns
    9. dtype: ประเภทข้อมูล (data types) ของ columns

    😺 GitHub

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


    📃 References

  • แนะนำ 4 functions ในการทำงานกับ JSON ใน Python: json.dumps(), json.loads(), json.dump(), และ json.load() — ตัวอย่างการทำงานกับข้อมูลคำสั่งซื้อคุกกี้

    แนะนำ 4 functions ในการทำงานกับ JSON ใน Python: json.dumps(), json.loads(), json.dump(), และ json.load() — ตัวอย่างการทำงานกับข้อมูลคำสั่งซื้อคุกกี้

    ในบทความนี้ เราจะไปดูวิธีใช้ 4 functions จาก json package ใน Python สำหรับทำงานกับ JSON (JavaScript Object Notation) ซึ่งเป็น data structure ที่พบได้บ่อยในแอปพลิเคชันและระบบต่าง ๆ กัน:

    1. json.loads()
    2. json.dumps()
    3. json.load()
    4. json.dump()

    ตัวอย่าง JSON คำสั่งซื้อออนไลน์:

    {
      "order_id": 1024,
      "customer": {
        "name": "Ari Lee",
        "phone": "+66 89 123 4567"
      },
      "items": [
        {
          "product": "Cappuccino",
          "size": "Medium",
          "price": 75,
          "quantity": 1
        },
        {
          "product": "Ham Sandwich",
          "price": 95,
          "quantity": 2
        }
      ],
      "payment": {
        "method": "QR Code",
        "total": 170,
        "currency": "THB"
      },
      "status": "Preparing",
      "timestamp": "2025-10-11T09:30:00"
    }
    

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


    1. 🏁 Introduction to json
    2. 🗨️ Group 1. JSON Strings
      1. ⬇️ json.loads(): JSON String to Python Object
      2. ⬆️ json.dumps(): Python Object to JSON String
    3. 📂 Group 2. JSON Files
      1. ⬇️ json.load(): JSON File to Python Object
      2. ⬆️ json.dump(): Python Object to JSON File
    4. 💪 Summary
    5. 😺 GitHub
    6. 📃 References

    🏁 Introduction to json

    json เป็น built-in package ใน Python และถูกออกแบบมาสำหรับทำงานกับ JSON โดยเฉพาะ

    เราสามารถเริ่มใช้งาน json ด้วยการโหลด package ด้วย import:

    # Import json
    import json
    

    json มี 4 functions สำหรับทำงานกับ JSON ซึ่งแบ่งได้เป็น 2 กลุ่ม:

    1. ทำงานกับ JSON string หรือ JSON ที่อยู่ในรูป Python string:
      1. json.loads()
      2. json.dumps()
    2. ทำงานกับ JSON file หรือ file ที่เห็นข้อมูล JSON เอาไว้:
      1. json.load()
      2. json.dump()

    Note: เทคนิคการจำ คือ function ที่ลงท้ายด้วย s (เช่น json.loads()) แสดงว่าใช้งานกับ JSON string

    ทั้ง 4 functions มีรายละเอียดการใช้งาน ดังนี้:

    FunctionFromTo
    json.loads()JSON string 🗨️Python object 🐍
    json.dumps()Python object 🐍JSON string 🗨️
    json.load()JSON file 📂Python object 🐍
    json.dump()Python object 🐍JSON file 📂

    เราไปดูวิธีใช้งานทั้ง 4 functions กับตัวอย่างข้อมูลสั่งซื้อคุกกี้กัน


    🗨️ Group 1. JSON Strings

    2 functions สำหรับทำงานกับ JSON string หรือ JSON ที่อยู่ในรูปของ Python string ได้แก่:

    FunctionFromTo
    json.loads()JSON string 🗨️Python object 🐍
    json.dumps()Python object 🐍JSON string 🗨️

    .

    ⬇️ json.loads(): JSON String to Python Object

    json.loads() ใช้โหลด JSON string ให้เป็น Python object เช่น:

    • String: ""
    • List: []
    • Dictionary: {}

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

    # Create a Python dict
    cookie_json_string = """
    {
        "customer": "May",
        "cookies": [
            "Chocolate Chip",
            "Oatmeal",
            "Sugar"
        ],
        "is_member": true,
        "total_price": 120
    }
    """
    
    # Convert to Python object
    cookie_python_dict = json.loads(cookie_json_string)
    

    เราสามารถดูผลลัพธ์ได้ด้วย pprint() ซึ่งเป็น function สำหรับ print Python dictionary ให้อ่านง่าย:

    # Import pprint
    from pprint import pprint
    
    # View the result
    pprint(cookie_python_dict)
    

    ผลลัพธ์:

    {'cookies': ['Chocolate Chip', 'Oatmeal', 'Sugar'],
     'customer': 'May',
     'is_member': True,
     'total_price': 120}
    

    .

    ⬆️ json.dumps(): Python Object to JSON String

    ในกรณีที่เรามี Python object เราสามารถแปลงเป็น JSON string ได้ด้วย json.dumps():

    # Create a Python dict
    cookie_py_dict = {
        "customer": "May",
        "cookies": [
            "Chocolate Chip",
            "Oatmeal",
            "Sugar"
        ],
        "is_member": True,
        "total_price": 120
    }
    
    # Convert to JSON string
    cookie_json_str = json.dumps(cookie_py_dict)
    
    # View the result
    print(cookie_json_str)
    

    ผลลัพธ์:

    {"customer": "May", "cookies": ["Chocolate Chip", "Oatmeal", "Sugar"], "is_member": true, "total_price": 120}
    

    ทั้งนี้ เราสามารถใช้ indent เพื่อทำให้ JSON string อ่านง่ายขึ้นได้ เช่น:

    # Convert to JSON string with indent argument
    cookie_json_str_indent = json.dumps(cookie_py_dict, indent=4)
    
    # View the result
    print(cookie_json_str_indent)
    

    ผลลัพธ์:

    {
        "customer": "May",
        "cookies": [
            "Chocolate Chip",
            "Oatmeal",
            "Sugar"
        ],
        "is_member": true,
        "total_price": 120
    }
    

    📂 Group 2. JSON Files

    เรามี 2 functions สำหรับทำงานกับ JSON files ได้แก่:

    FunctionFromTo
    json.load()JSON file 📂Python object 🐍
    json.dump()Python object 🐍JSON file 📂

    .

    ⬇️ json.load(): JSON File to Python Object

    json.load() ใช้สำหรับโหลดข้อมูลจาก JSON file เข้ามาใน Python

    เช่น เรามี JSON file ดังนี้:

    {
        "order_id": 2048,
        "customer": {
            "name": "MJ",
            "phone": "+66 92 888 4321"
        },
        "items": [
            {
                "product": "Double Chocolate Cookie",
                "size": "Large",
                "price": 55,
                "quantity": 2
            },
            {
                "product": "Almond Biscotti",
                "price": 45,
                "quantity": 3
            }
        ],
        "payment": {
            "method": "Credit Card",
            "total": 285,
            "currency": "THB"
        },
        "status": "Baking",
        "timestamp": "2025-10-11T10:15:00"
    }
    

    เราสามารถโหลดขัอมูลได้แบบนี้:

    # Load JSON data
    with open("cookie_order.json", "r") as file:
        cookie_order = json.load(file)
    
    # View the result
    pprint(cookie_order)
    

    ผลลัพธ์:

    {'customer': {'name': 'MJ', 'phone': '+66 92 888 4321'},
     'items': [{'price': 55,
                'product': 'Double Chocolate Cookie',
                'quantity': 2,
                'size': 'Large'},
               {'price': 45, 'product': 'Almond Biscotti', 'quantity': 3}],
     'order_id': 2048,
     'payment': {'currency': 'THB', 'method': 'Credit Card', 'total': 285},
     'status': 'Baking',
     'timestamp': '2025-10-11T10:15:00'}
    

    .

    ⬆️ json.dump(): Python Object to JSON File

    json.dump() ใช้สร้าง JSON file จาก Python objects

    เช่น update ข้อมูลผู้ซื้อใน cookie_order จาก "MJ" เป็น "Peter Parker" และสร้างเป็น JSON file:

    # Update name
    cookie_order["customer"]["name"] = "Peter Parker"
    
    # Write to JSON file
    with open("cookie_order_updated.json", "w") as file:
        json.dump(cookie_order, file, indent=2)
    

    Note: สังเกตว่า เราสามารถกำหนด indent เพื่อทำให้ JSON อ่านง่ายขึ้นได้เหมือนกับ json.dumps()

    ผลลัพธ์ใน JSON file:

    {
      "order_id": 2048,
      "customer": {
        "name": "Peter Parker",
        "phone": "+66 92 888 4321"
      },
      "items": [
        {
          "product": "Double Chocolate Cookie",
          "size": "Large",
          "price": 55,
          "quantity": 2
        },
        {
          "product": "Almond Biscotti",
          "price": 45,
          "quantity": 3
        }
      ],
      "payment": {
        "method": "Credit Card",
        "total": 285,
        "currency": "THB"
      },
      "status": "Baking",
      "timestamp": "2025-10-11T10:15:00"
    }
    

    💪 Summary

    ในบทความนี้ เราได้ไปดูวิธีการใช้ 4 functions จาก json package เพื่อทำงานกับ JSON ใน Python:

    FunctionFromTo
    json.loads()JSON string 🗨️Python object 🐍
    json.dumps()Python object 🐍JSON string 🗨️
    json.load()JSON file 📂Python object 🐍
    json.dump()Python object 🐍JSON file 📂

    Note: json.dumps() และ json.dump() มี indent argument ที่ทำให้ JSON ออกอ่านง่ายได้


    😺 GitHub

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


    📃 References

  • วิธีใช้ open() เพื่อทำงานกับไฟล์ใน Python: วิธีใช้งาน, วิธีเขียนโดยใช้ with และไม่ใช้ with, และ 4 modes ในการทำงานกับไฟล์ (+ bonus การลบไฟล์) พร้อมตัวอย่าง

    วิธีใช้ open() เพื่อทำงานกับไฟล์ใน Python: วิธีใช้งาน, วิธีเขียนโดยใช้ with และไม่ใช้ with, และ 4 modes ในการทำงานกับไฟล์ (+ bonus การลบไฟล์) พร้อมตัวอย่าง

    ในบทความนี้ เราจะมาดูวิธีใช้ open() เพื่อทำงานกับไฟล์ใน Python กัน:

    1. Intro to open(): วิธีการเขียนและการใช้งาน
    2. 4 modes: 4 วิธีการทำงานกับไฟล์
    3. Bonus: วิธีลบไฟล์

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


    1. 💻 Intro to open()
      1. 🔢 Syntax
      2. 🗄️ Using open()
    2. 🗂️ Mode
      1. 📄 Create
      2. 📖 Read
      3. ➕ Append
      4. ✏️ Write
    3. 🍩 Bonus: Delete
    4. ⚡ Summary
    5. 😺 GitHub
    6. 📃 References

    💻 Intro to open()

    .

    🔢 Syntax

    open() เป็น base function สำหรับทำงานกับไฟล์ และต้องการ 2 arguments:

    open(filename, mode)
    
    • filename = ชื่อไฟล์ (เป็น string เช่น "my_file.txt")
    • mode = mode ในการทำงานกับไฟล์ (เช่น "r" สำหรับอ่านไฟล์)

    .

    🗄️ Using open()

    เราสามารถใช้ open() ได้ 2 วิธี ได้แก่:

    วิธีที่ 1. เปิดไฟล์โดยไม่ใช้ with ซึ่งจะต้องมี .close() เพื่อปิดไฟล์เมื่อทำงานเสร็จ:

    # Open file
    file = open(filename, mode)
    
    # Act on file
    file.method()
    
    # Close file
    file.close()
    

    วิธีที่ 2. เปิดไฟล์โดยใช้ with:

    # Open file
    with open(filename, mode) as file:
        
        # Act on file
        file.method()
    

    วิธีที่ 2 เป็นวิธีที่นิยมใช้มากกว่า เพราะเราไม่จำเป็นต้องปิดไฟล์ด้วย .close() หลังทำงานเสร็จ


    🗂️ Mode

    open() มี 4 modes ในการทำงานกับไฟล์ ได้แก่:

    ModeActionNote
    "x"สร้างไฟล์แสดง error ถ้ามีไฟล์ชื่อเดียวกันอยู่แล้ว
    "r"อ่านไฟล์แสดง error ถ้ามีไม่มีไฟล์ที่ต้องการ
    "a"เพิ่มข้อมูลในไฟล์สร้างไฟล์ใหม่ถ้าไม่มีไฟล์ชื่อเดียวกันอยู่แล้ว
    "w"เขียนทับข้อมูลที่มีในไฟล์สร้างไฟล์ใหม่ถ้าไม่มีไฟล์ชื่อเดียวกันอยู่แล้ว

    ไปดูตัวอย่างการใช้ทั้ง 4 modes กัน

    .

    📄 Create

    ตัวอย่างการสร้างไฟล์ด้วย "x":

    # Create a file
    with open("example.txt", "x") as file:
        file.write("This is the first line.")
        file.write("This is the second line.")
        file.write("This is the third line.")
    

    ผลลัพธ์: เราจะได้ไฟล์ชื่อ example.txt ในเครื่องของเรา

    .

    📖 Read

    เราสามารถอ่านไฟล์ด้วย "r" ได้ 3 วิธี:

    วิธีที่ 1. ใช้ .read() เพื่ออ่านเนื้อหาทั้งหมด:

    # Read the file - all
    with open("example.txt", "r") as file:
        file.read()
    

    ผลลัพธ์ใน console:

    This is the first line.
    This is the second line.
    This is the third line.
    

    วิธีที่ 2. ใช้ .readline() ในกรณีที่ต้องการอ่านรายบรรทัด:

    # Read the file - one line at a time
    with open("example.txt", "r") as file:
        file.readline()
        file.readline()
    

    ผลลัพธ์ใน console:

    This is the first line.
    This is the second line.
    

    วิธีที่ 3. ใช้ for loop เพื่ออ่านเนื้อหาทั้งหมดทีละบรรทัด:

    # Read the file - line by line
    with open("example.txt", "r") as file:
        
        # Loop through each line
        for line in file:
            print(line)
    

    ผลลัพธ์ใน console:

    This is the first line.
    This is the second line.
    This is the third line.
    

    .

    ➕ Append

    ตัวอย่างการเพิ่มข้อมูลด้วย "a":

    # Add content to the file
    with open("example.txt", "a") as file:
        file.write("This is the fourth line.")
    

    เนื้อหาในไฟล์:

    This is the first line.
    This is the second line.
    This is the third line.
    This is the fourth line.
    

    .

    ✏️ Write

    ตัวอย่างการเขียนไฟล์ด้วย "w":

    # Overwrite the file
    with open("example.txt", "w") as file:
        file.write("This is all there is now.")
    

    เนื้อหาในไฟล์:

    This is all there is now.
    

    🍩 Bonus: Delete

    ในกรณีที่เราต้องการลบไฟล์ เราจะต้องเรียกใช้ remove() function จาก os module:

    # Import os module
    import os
    
    # Delete the file
    os.remove("example.txt")
    

    ผลลัพธ์: ไฟล์จะถูกลบออกจากเครื่อง


    ⚡ Summary

    • open() เป็น base Python function สำหรับทำงานกับไฟล์
    • open() ต้องการ 2 arguments คือ:
      • filename: ชื่อไฟล์
      • mode: mode ในการทำงานกับไฟล์
    • วิธีใช้งาน:
      • open() มักใช้คู่กับ with
      • ถ้าไม่ใช้ with เราจะต้องปิดไฟล์ด้วย .close() เมื่อมช้งานเสร็จ
    • open() มี 4 modes ได้แก่:
      • "x": สร้างไฟล์
      • "r": อ่านไฟล์
      • "a": เพิ่มเนื้อหา
      • "w": เขียนทับข้อมูลเดิม
    • ลบไฟล์ด้วย os.remove()

    😺 GitHub

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


    📃 References

  • วิธีสร้าง functions ใน Python: def, docstring, arguments, และ lambda พร้อมตัวอย่าง

    วิธีสร้าง functions ใน Python: def, docstring, arguments, และ lambda พร้อมตัวอย่าง

    ในบทความนี้ เราจะมาดูวิธีสร้าง function ใน Python กัน โดยบทความนี้แบ่งเป็น 4 ส่วน:

    1. def syntax: การใช้ def เพื่อสร้าง function
    2. Docstring: การเขียนวิธีใช้งาน function
    3. Arguments: การกำหนด arguments ใน function
    4. lambda: การสร้าง function แบบไม่ระบุชื่อ

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


    1. 💻 def Syntax
    2. 📃 Docstring
      1. 🤔 Why Docstring?
      2. 🥸 What Is Docstring?
      3. 😎 Reading Docstring
    3. 💬 Arguments
      1. 🫡 Default Arguments
      2. 😶‍🌫️ Arbitrary Arguments
    4. 🛋️ lambda
    5. 😺 GitHub
    6. 📃 References

    💻 def Syntax

    ใน Python เราสามารถสร้าง function ได้ด้วย def ซึ่งประกอบด้วย 4 ส่วน:

    # Name and arguments
    def name(arguments):
    # Body
    Do something
    # Return
    return result
    1. name = ชื่อ function
    2. arguments = input สำหรับ function
    3. Body = การทำงานของ function
    4. Return = ส่งผลลัพธ์กลับออกมาจาก function *

    (Note: * เราสามารถใช้ print() แทน return ได้ ในกรณีที่เราต้องการแสดงผลลัพธ์ใน console)

    ยกตัวอย่างเช่น สร้าง function สำหรับคำนวณ BMI (body mass index) ซึ่งต้องการ 2 arguments คือ น้ำหนัก (weight) และส่วนสูง (height):

    # Create a function that calculates BMI
    def calculate_bmi(weight, height):
    
        # Calculate BMI
        bmi = weight / (height ** 2)
    
        # Round to 2 decimals
        bmi_rounded = round(bmi, 2)
    
        # Return BMI
        return bmi_rounded
    

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

    # Use the BMI calculator function
    my_bmi = calculate_bmi(weight=80, height=1.8)
    
    # Print the result
    print(my_bmi)
    

    ผลลัพธ์:

    24.69
    

    📃 Docstring

    .

    🤔 Why Docstring?

    ในตัวอย่าง bmi_cal() เราจะเห็นว่า weight และ height มีได้หลายค่า ขึ้นอยู่กับหน่วยวัดที่ใช้ เช่น:

    • height: metre = 1.8; feet = 5.9
    • weight: kg = 80; pound = 176

    ถ้าเราใส่ค่าไม่ถูกต้องลงใน function เราจะได้ผลลัพธ์ที่ผิดกลับมา เช่น ใส่ height เป็น cm:

    # Using incorrect input
    wrong_bmi = calculate_bmi(weight=80, height=180)
    
    # Print the result
    print(wrong_bmi)
    

    ผลลัพธ์:

    0.0
    

    .

    🥸 What Is Docstring?

    เราสามารถแก้ปัญหานี้ได้ 2 วิธี:

    1. ตั้งชื่อ arguments ให้เรารู้ว่า ต้องใส่อะไรใน function (เช่น height_in_m, weight_in_kg)
    2. ใส่ docstring หรือ string ที่เก็บวิธีใช้ function ไว้

    เราสามารถเพิ่ม docstring ใน function ได้แบบนี้:

    # Adding docstring to the function
    def calculate_bmi(height, weight):
    
        # Docstring
        """
        Calculate BMI using weight and height:
        - Weight: kg
        - Height: m
    
        Return BMI rounded to 2 decimals.
        """
    
        # Calculate BMI
        bmi = weight / (height ** 2)
    
        # Round to 2 decimals
        bmi_rounded = round(bmi, 2)
    
        # Return BMI
        return bmi_rounded
    

    Pro tip: เราควรใส่ docstring ไว้ใน function โดยเฉพาะใน code ที่ใช้งานร่วมกับคนอื่น เพื่อให้คนอื่นเข้าใจการทำงาน function ของเรา

    .

    😎 Reading Docstring

    เราสามารถอ่าน docstring ได้ 2 วิธี:

    วิธีที่ 1. ใช้ help():

    # Read docstring with help()
    help(calculate_bmi)
    

    ผลลัพธ์:

    Help on function calculate_bmi in module __main__:
    
    calculate_bmi(height, weight)
        Calculate BMI using weight and height:
        - Weight: kg
        - Height: m
    
        Return BMI rounded to 2 decimals.
    

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

    # Read docstring with .__doc__:
    print(calculate_bmi.__doc__)
    

    ผลลัพธ์:

    Calculate BMI using weight and height:
        - Weight: kg
        - Height: m
    
        Return BMI rounded to 2 decimals.
    

    💬 Arguments

    เรามาดูการกำหนด 2 ประเภท arguments ใน functions กัน:

    1. Default arguments
    2. Arbitrary arguments

    .

    🫡 Default Arguments

    Default arguments เป็นค่าที่ function จะเรียกใช้ถ้าเราไม่กำหนด arguments เอง

    ยกตัวอย่างเช่น สร้าง function สำหรับคิดเลขยกกำลัง ซึ่งจะยกกำลัง 2 โดย default:

    # Create a function with default arguments
    def calculate_power(number, power=2):
    
        # Calculate number to the power of power
        result = number ** power
    
        # Return result
        return result
    
    # Call the function without power
    print(calculate_power(10))
    

    ผลลัพธ์:

    100
    

    แต่ถ้าเรากำหนด power เอง:

    # Call the function with power
    print(calculate_power(10, 3))
    

    ผลลัพธ์จะเปลี่ยนไป:

    1000
    

    .

    😶‍🌫️ Arbitrary Arguments

    Arbitrary arguments เป็นประเภท argument ที่เรากำหนดในกรณีที่เราไม่รู้ว่า จะมีกี่ arguments

    เราสามารถสร้าง function ที่รับ arguments แบบไม่ระบุจำนวนได้ 2 วิธี:

    1. *args: มี positional arguments (arguments ที่ใส่ตามลำดับ) แบบไม่ระบุจำนวน
    2. **kargs: มี keyword arguments (arguments ที่ใส่ตาม keywords) แบบไม่ระบุจำนวน

    ยกตัวอย่าง *args เช่น สร้าง function สำหรับคำนวณราคาสินค้าในตระกร้า ซึ่งเราไม่รู้ว่า จะมีสินค้ากี่ชิ้น:

    # Create a function calculate total price
    def calculate_total_price(*prices):
    
        # Calculate sum
        total = sum(prices)
    
        # Return total
        return total
    
    # Examples
    total_basket_01 = calculate_total_price(500, 1000)
    total_basket_02 = calculate_total_price(100, 200, 300)
    
    print(f"Basket 1: {total_basket_01}")
    print(f"Basket 2: {total_basket_02}")
    

    ผลลัพธ์:

    Basket 1: 1500
    Basket 2: 600
    

    ยกตัวอย่าง **kargs เช่น สร้าง function เก็บข้อมูล user ซึ่งแต่ละ user มีข้อมูลไม่เท่ากัน:

    # Create a function to return user's data
    def user_profile(**user_data):
        return user_data
    
    # Examples
    print(f"User 1: {user_profile(name='John')}")
    print(f"User 2: {user_profile(name='Jane', gender='F', age=20)}")
    

    ผลลัพธ์:

    User 1: {'name': 'John'}
    User 2: {'name': 'Jane', 'gender': 'F', 'age': 20}
    

    Note:

    • Arguments ใน *args จะถูกเก็บรวมในรูปของ tuple
    • Arguments ใน **kargs จะถูกเก็บรวมในรูปของ dictionary

    🛋️ lambda

    lambda เป็นการสร้าง function แบบไม่ระบุชื่อ โดยเราเขียนได้ดังนี้:

    lambda arguments: expression

    lambda มักใช้สร้าง function ขนาดเล็ก เช่น function หาผลรวม:

    # Create a function using lambda
    addition = lambda a, b: a + b
    
    # Call addition
    print(addition(1, 1))
    

    ผลลัพธ์:

    2
    

    จะเห็นได้ว่า lambda ในตัวอย่างมีค่าเท่ากับการใช้ def แบบนี้:

    # Same as lambda
    def addition(a, b):
        return a + b
    

    เมื่อเทียบกับ def จะเห็นว่า lambda มีการเขียนที่สั้นและง่ายกว่า

    เรามักใช้ lambda ในกรณีที่ต้องการสร้าง function อย่างง่ายและรวดเร็ว

    และเรามักใช้ def ในกรณีที่:

    • สร้าง function ที่มีความซับซ้อน (มีการทำงานหลายขั้นตอน)
    • สร้าง function สำหรับใช้งานร่วมกับคนอื่น เพราะ def จะทำให้คนอื่นอ่าน code ได้ง่ายกว่า

    😺 GitHub

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


    📃 References

  • dbplyr: แนะนำ package และ 6 ขั้นตอนในการทำงานกับ database ด้วย dplyr syntax ในภาษา R — ตัวอย่างการทำงานกับ Chinook database

    dbplyr: แนะนำ package และ 6 ขั้นตอนในการทำงานกับ database ด้วย dplyr syntax ในภาษา R — ตัวอย่างการทำงานกับ Chinook database

    ในบทความนี้ เราจะไปดูวิธีใช้ dbplyr ซึ่งเป็น package สำหรับทำงานกับ database ในภาษา R และเหมาะกับคนที่ต้องการทำงานโดยใช้ภาษา R เป็นหลักกัน

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


    1. 🤔 What Is dbplyr?
    2. 🏁 Getting Started
    3. 🏃‍♂️‍➡️ Using dbplyr
      1. 1️⃣ Connect to the Database
      2. 2️⃣ Create a Lazy Tibble
      3. 3️⃣ Create a Query
      4. 4️⃣ Show the Query
      5. 5️⃣ Collect the Result
      6. 6️⃣ Disconnect the Database
    4. 💪 Summary
    5. 😺 GitHub
    6. 📃 References
    7. ✅ R Book for Psychologists: หนังสือภาษา R สำหรับนักจิตวิทยา

    🤔 What Is dbplyr?

    dbplyr เป็น package ในภาษา R สำหรับทำงานกับ database โดยใช้ dplyr syntax แทน SQL เช่น แทนที่เราเขียน:

    SELECT * FROM table
    

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

    select(table, everything())
    

    (Note: อ่านวิธีใช้ dplyr ได้ที่นี่)


    🏁 Getting Started

    เราสามารถเริ่มใช้งาน dbplyr ได้โดยติดตั้งและโหลด 4 packages ดังนี้:

    1. DBI: สำหรับเชื่อมต่อกับ database (อ่านวิธีใช้เพิ่มเติมได้ที่นี่)
    2. RSQLite: สำหรับเชื่อมต่อกับ SQLite database (เราจะเปลี่ยน package นี้ตาม database ที่เราใช้ เช่น RPostgres สำหรับ Postgres database)
    3. dplyr: สำหรับ dplyr syntax เช่น select(), filter(), arrange()
    4. dbplyr: สำหรับทำงานกับ database ด้วย dplyr syntax
    # Install packages
    install.packages("DBI")
    install.packages("RSQLite")
    install.packages("dplyr")
    install.packages("dbplyr")
    
    # Load packages
    library(DBI)
    library(RSQLite)
    library(dplyr)
    library(dbplyr)
    

    🏃‍♂️‍➡️ Using dbplyr

    เราสามารถใช้ dbplyr เพื่อทำงานกับ database ได้ใน 6 ขั้นตอน:

    1. Connect to the database
    2. Create a lazy tibble
    3. Create a query
    4. Show the query
    5. Get the result

    .

    1️⃣ Connect to the Database

    ในขั้นแรก เราจะเชื่อมต่อกับ local database ด้วย DBI::dbConnect และ RSQLite::SQLite():

    # Connect to database
    con <- dbConnect(RSQLite::SQLite(),
                     "chinook.sqlite")
    

    Note: โหลด “chinook.sqlite” ได้จาก GitHub

    .

    2️⃣ Create a Lazy Tibble

    ในขั้นที่ 2 เราจะสร้าง lazy tibble หรือ object ที่ใช้แทน database table ซึ่งทำได้ใน 2 steps:

    Step 1. ดูรายชื่อ table ทั้งหมด ใน database ด้วย DBI::dbListTables():

    # View all tables
    dbListTables(con)
    

    ผลลัพธ์:

     [1] "Album"         "Artist"        "Customer"      "Employee"     
     [5] "Genre"         "Invoice"       "InvoiceLine"   "MediaType"    
     [9] "Playlist"      "PlaylistTrack" "Track" 
    

    Step 2. สร้าง lazy tibble จากชื่อ table ที่ต้องการ ด้วย dplyr::tbl():

    # Create lazy tibble
    tracks <- tbl(con,
                  "Track")
    
    # View tibble
    tracks
    

    ผลลัพธ์:

    # Source:   table<`Track`> [?? x 9]
    # Database: sqlite 3.50.1 [C:\\My Code\\RStudio\\chinook.sqlite]
       TrackId Name           AlbumId MediaTypeId GenreId Composer Milliseconds  Bytes UnitPrice
         <int> <chr>            <int>       <int>   <int> <chr>           <int>  <int>     <dbl>
     1       1 For Those Abo…       1           1       1 Angus Y…       343719 1.12e7      0.99
     2       2 Balls to the …       2           2       1 NA             342562 5.51e6      0.99
     3       3 Fast As a Sha…       3           2       1 F. Balt…       230619 3.99e6      0.99
     4       4 Restless and …       3           2       1 F. Balt…       252051 4.33e6      0.99
     5       5 Princess of t…       3           2       1 Deaffy …       375418 6.29e6      0.99
     6       6 Put The Finge…       1           1       1 Angus Y…       205662 6.71e6      0.99
     7       7 Let's Get It …       1           1       1 Angus Y…       233926 7.64e6      0.99
     8       8 Inject The Ve…       1           1       1 Angus Y…       210834 6.85e6      0.99
     9       9 Snowballed           1           1       1 Angus Y…       203102 6.60e6      0.99
    10      10 Evil Walks           1           1       1 Angus Y…       263497 8.61e6      0.99
    # ℹ more rows
    # ℹ Use `print(n = ...)` to see more rows
    

    .

    3️⃣ Create a Query

    ในขั้นที่ 3 เราจะเขียน dplyr syntax เพื่อ query table ที่ต้องการ

    เช่น สรุปข้อมูลจำนวนเพลง ค่าเฉลี่ยความยาวเพลง (Milliseconds) และขนาดเพลง (Bytes) ของแต่ละ album:

    # Create query
    album_info <- tracks |>
      
      # Group by album
      group_by(AlbumId) |>
      
      # Summarise
      summarise(
        
        # Number of tracks
        tracks = n(),
        
        # Average duration
        mean_millisec = mean(Milliseconds,
                             na.rm = TRUE),
        
        # Total size
        total_bytes = sum(Bytes)
      ) |>
      
      # Sort by duration
      arrange(desc(mean_millisec))
    

    ตอนนี้ code ของเราจะยังไม่ถูกส่งไปยัง database เพราะ lazy tibble จะเก็บคำสั่งไว้จนกว่าเราจะมีคำสั่งให้ส่ง

    เราไปดูคำสั่งที่เราสามารถใช้กับ code ที่ยังไม่ถูกส่งไปกัน

    .

    4️⃣ Show the Query

    เราสามารถใช้ dbplyr::show_query() เพื่อดู SQL ที่จะถูกส่งไปยัง database (ซึ่งแปลงมาจาก dplyr syntax ของเรา) ได้:

    # Show query
    show_query(album_info)
    

    ผลลัพธ์:

    <SQL>
    SELECT
      `AlbumId`,
      COUNT(*) AS `tracks`,
      AVG(`Milliseconds`) AS `mean_millisec`,
      SUM(`Bytes`) AS `total_bytes`
    FROM `Track`
    GROUP BY `AlbumId`
    ORDER BY `mean_millisec` DESC
    

    .

    5️⃣ Collect the Result

    เราสามารถส่ง code เพื่อไป query database ได้ด้วย dbplyr::collect():

    # Get result
    album_info_tb <- collect(album_info)
    
    # View the result
    album_info_tb
    

    ผลลัพธ์:

    # A tibble: 347 × 4
       AlbumId tracks mean_millisec total_bytes
         <int>  <int>         <dbl>     <int64>
     1     253     24      2925574. 12872621850
     2     227     19      2778265. 10059916535
     3     229     26      2717907  13917603291
     4     231     24      2637068. 12344960921
     5     226      1      2622250    490750393
     6     228     23      2599142. 11781321607
     7     230     25      2594197.  5280909854
     8     254      1      2484567    492670102
     9     261     17      2321673.  7708725642
    10     251     25      1532684.  7652731262
    # ℹ 337 more rows
    # ℹ Use `print(n = ...)` to see more rows
    

    .

    6️⃣ Disconnect the Database

    สุดท้าย เมื่อเราทำงานเสร็จแล้ว เราจะปิดการเชื่อมต่อกับ database ด้วย DBI::dbDisconnect():

    # Disconnect from database
    dbDisconnect(con)
    

    เป็นการจบ loop การทำงานกับ database ด้วย dbplyr


    💪 Summary

    ในบทความนี้ เราได้ไปทำความรู้จัก 6 ขั้นตอนในการใช้ dbplyr เพื่อทำงานกับ database ในภาษา R กัน:

    1. Connect to the database: DBI::dbConnect() และ RSQLite::SQLite()
    2. Create a lazy tibble: dplyr::tbl()
    3. Create a query: ใช้ dplyr syntax คู่กับ lazy tibble
    4. Show the query: dbplyr::show_query()
    5. Collect the result: dbplyr::collect()
    6. Disconnect the database: DBI::dbDisconnect()

    😺 GitHub

    ดูตัวอย่าง code และ database ในบทความนี้ได้ที่ 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:

  • DBI: แนะนำ 4 ขั้นตอนในการเชื่อมต่อและ query ข้อมูลจาก database โดยใช้ภาษา R — ตัวอย่างการทำงานกับ Chinook database

    DBI: แนะนำ 4 ขั้นตอนในการเชื่อมต่อและ query ข้อมูลจาก database โดยใช้ภาษา R — ตัวอย่างการทำงานกับ Chinook database

    ในบทความนี้ เราจะมาดู 4 ขั้นตอนในการเชื่อมต่อและทำงานกับ database ในภาษา R ด้วย DBI package กัน:

    1. Get started
    2. Explore the database
    3. Query the database
    4. Close the connection

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


    1. 💻 Step 1. Get Started
      1. 📦 DBI Package
      2. ⬇️ Install & Connect
    2. 👀 Step 2. Explore the Database
      1. 1️⃣ dbListTable()
      2. 2️⃣ dbGetQuery()
    3. 🔍 Step 3. Query the Database
      1. 1️⃣ dbReadTable()
      2. 2️⃣ dbGetQuery()
      3. 3️⃣ dbSendQuery()
    4. 🤚 Step 4. Close the Connection
    5. 💪 Summary
    6. 😺 GitHub
    7. 📃 References
    8. ✅ R Book for Psychologists: หนังสือภาษา R สำหรับนักจิตวิทยา

    💻 Step 1. Get Started

    📦 DBI Package

    DBI (Database Interface) เป็น package สำหรับเชื่อมต่อกับ database ซึ่งทำให้เราทำงานกับ database ในภาษา R ได้โดยตรง

    ในบทความนี้ เรามาลองดูการใช้งาน DBI ผ่านการทำงานกับ Chinook SQLite database กัน (เราสามารถโหลด Chinook เพื่อลองทำตามได้จาก GitHub)

    .

    ⬇️ Install & Connect

    ในขั้นแรกของการใช้งาน เราจะติดตั้งและโหลด DBI พร้อมกับ package สำหรับ database ที่เราจะทำงานด้วย

    อย่างในกรณีนี้ เราจะติดตั้งและโหลด RSQLite package เพราะเราจะทำงานกับ SQLite database

    Note: ถ้าเราทำงานกับ database อื่น เราจะต้องติดตั้งและโหลด package อื่น เช่น:

    • MySQL → RMySQL
    • PostgresSQL → RPostgresSQL
    • Oracle → ROracle

    ติดตั้ง packages:

    # Install
    install.packages("DBI")
    install.packages("RSQLite")
    

    โหลด packages:

    # Load
    library(DBI)
    library(RSQLite)
    

    หลังติดตั้งและโหลด packages แล้ว เราจะเชื่อมต่อกับ database ด้วย dbConnect() แบบนี้:

    # Connect to database
    con <- dbConnect(RSQLite::SQLite(),
                     "chinook.sqlite")
    

    Note: ในกรณีที่ database ไม่ได้อยู่ใน working directory เราจะต้องใช้ absolute file path แทนชื่อไฟล์ เช่น:

    # Connect to database
    con <- dbConnect(RSQLite::SQLite(),
                     "C:/Users/YourUser/Documents/R_Projects/my_data/chinook.sqlite")
    

    เท่านี้ เราก็พร้อมที่จะทำงานกับ database กันแล้ว


    👀 Step 2. Explore the Database

    เริ่มแรก เราจะสำรวจ database เพื่อทำความเข้าใจโครงสร้างข้อมูลกันก่อน

    เรามี 2 functions ที่ช่วยเราได้ ได้แก่:

    1. dbListTables(): ดูรายชื่อ tables ทั้งหมดใน database
    2. dbGetQuety(): ดู columns ใน table ที่ต้องการ

    .

    1️⃣ dbListTable()

    ตัวอย่าง:

    # List tables in the database
    dbListTables(con)
    

    ผลลัพธ์:

     [1] "Album"         "Artist"        "Customer"      "Employee"     
     [5] "Genre"         "Invoice"       "InvoiceLine"   "MediaType"    
     [9] "Playlist"      "PlaylistTrack" "Track"  
    

    .

    2️⃣ dbGetQuery()

    ตัวอย่าง:

    # List columns in a table
    dbGetQuery(con,
               "PRAGMA table_info(Artist)")
    

    ผลลัพธ์:

      cid     name          type notnull dflt_value pk
    1   0 ArtistId       INTEGER       1         NA  1
    2   1     Name NVARCHAR(120)       0         NA  0
    

    ในกรณีที่เราต้องการดู columns ในทุก table เราสามารถใช้ for loop ช่วยได้แบบนี้:

    # Get the table list
    tables <- dbListTables(con)
    
    # Get all columns
    for (table_name in tables) {
      
      # Print the table name
      message(paste0("\\n👉 Table: ", table_name))
      
      # Get the columns
      column_info <- dbGetQuery(con,
                                paste0("PRAGMA table_info(",
                                       table_name, 
                                       ")"))
      
      # Print the columns
      print(column_info)
    }
    

    ผลลัพธ์:

    👉 Table: Album
      cid     name          type notnull dflt_value pk
    1   0  AlbumId       INTEGER       1         NA  1
    2   1    Title NVARCHAR(160)       1         NA  0
    3   2 ArtistId       INTEGER       1         NA  0
    👉 Table: Artist
      cid     name          type notnull dflt_value pk
    1   0 ArtistId       INTEGER       1         NA  1
    2   1     Name NVARCHAR(120)       0         NA  0
    👉 Table: Customer
       cid         name         type notnull dflt_value pk
    1    0   CustomerId      INTEGER       1         NA  1
    2    1    FirstName NVARCHAR(40)       1         NA  0
    3    2     LastName NVARCHAR(20)       1         NA  0
    4    3      Company NVARCHAR(80)       0         NA  0
    5    4      Address NVARCHAR(70)       0         NA  0
    6    5         City NVARCHAR(40)       0         NA  0
    7    6        State NVARCHAR(40)       0         NA  0
    8    7      Country NVARCHAR(40)       0         NA  0
    9    8   PostalCode NVARCHAR(10)       0         NA  0
    10   9        Phone NVARCHAR(24)       0         NA  0
    11  10          Fax NVARCHAR(24)       0         NA  0
    12  11        Email NVARCHAR(60)       1         NA  0
    13  12 SupportRepId      INTEGER       0         NA  0
    👉 Table: Employee
       cid       name         type notnull dflt_value pk
    1    0 EmployeeId      INTEGER       1         NA  1
    2    1   LastName NVARCHAR(20)       1         NA  0
    3    2  FirstName NVARCHAR(20)       1         NA  0
    4    3      Title NVARCHAR(30)       0         NA  0
    5    4  ReportsTo      INTEGER       0         NA  0
    6    5  BirthDate     DATETIME       0         NA  0
    7    6   HireDate     DATETIME       0         NA  0
    8    7    Address NVARCHAR(70)       0         NA  0
    9    8       City NVARCHAR(40)       0         NA  0
    10   9      State NVARCHAR(40)       0         NA  0
    11  10    Country NVARCHAR(40)       0         NA  0
    12  11 PostalCode NVARCHAR(10)       0         NA  0
    13  12      Phone NVARCHAR(24)       0         NA  0
    14  13        Fax NVARCHAR(24)       0         NA  0
    15  14      Email NVARCHAR(60)       0         NA  0
    👉 Table: Genre
      cid    name          type notnull dflt_value pk
    1   0 GenreId       INTEGER       1         NA  1
    2   1    Name NVARCHAR(120)       0         NA  0
    👉 Table: Invoice
      cid              name          type notnull dflt_value pk
    1   0         InvoiceId       INTEGER       1         NA  1
    2   1        CustomerId       INTEGER       1         NA  0
    3   2       InvoiceDate      DATETIME       1         NA  0
    4   3    BillingAddress  NVARCHAR(70)       0         NA  0
    5   4       BillingCity  NVARCHAR(40)       0         NA  0
    6   5      BillingState  NVARCHAR(40)       0         NA  0
    7   6    BillingCountry  NVARCHAR(40)       0         NA  0
    8   7 BillingPostalCode  NVARCHAR(10)       0         NA  0
    9   8             Total NUMERIC(10,2)       1         NA  0
    👉 Table: InvoiceLine
      cid          name          type notnull dflt_value pk
    1   0 InvoiceLineId       INTEGER       1         NA  1
    2   1     InvoiceId       INTEGER       1         NA  0
    3   2       TrackId       INTEGER       1         NA  0
    4   3     UnitPrice NUMERIC(10,2)       1         NA  0
    5   4      Quantity       INTEGER       1         NA  0
    👉 Table: MediaType
      cid        name          type notnull dflt_value pk
    1   0 MediaTypeId       INTEGER       1         NA  1
    2   1        Name NVARCHAR(120)       0         NA  0
    👉 Table: Playlist
      cid       name          type notnull dflt_value pk
    1   0 PlaylistId       INTEGER       1         NA  1
    2   1       Name NVARCHAR(120)       0         NA  0
    👉 Table: PlaylistTrack
      cid       name    type notnull dflt_value pk
    1   0 PlaylistId INTEGER       1         NA  1
    2   1    TrackId INTEGER       1         NA  2
    👉 Table: Track
      cid         name          type notnull dflt_value pk
    1   0      TrackId       INTEGER       1         NA  1
    2   1         Name NVARCHAR(200)       1         NA  0
    3   2      AlbumId       INTEGER       0         NA  0
    4   3  MediaTypeId       INTEGER       1         NA  0
    5   4      GenreId       INTEGER       0         NA  0
    6   5     Composer NVARCHAR(220)       0         NA  0
    7   6 Milliseconds       INTEGER       1         NA  0
    8   7        Bytes       INTEGER       0         NA  0
    9   8    UnitPrice NUMERIC(10,2)       1         NA  0
    

    🔍 Step 3. Query the Database

    หลังสำรวจ database แล้ว เราสามารถ query ข้อมูลได้ด้วย 3 functions ได้แก่:

    1. dbReadTable()
    2. dbGetQuery()
    3. dbSendQuery()

    .

    1️⃣ dbReadTable()

    เราจะใช้ dbReadTable() เมื่อต้องการดึงข้อมูลทั้งหมดมาจาก table ที่ต้องการ

    ตัวอย่างเช่น ดูข้อมูลทั้งหมดใน Genre:

    # Query with dbReadTable()
    dbReadTable(con,
                "Genre")
    

    ผลลัพธ์:

       GenreId               Name
    1        1               Rock
    2        2               Jazz
    3        3              Metal
    4        4 Alternative & Punk
    5        5      Rock And Roll
    6        6              Blues
    7        7              Latin
    8        8             Reggae
    9        9                Pop
    10      10         Soundtrack
    11      11         Bossa Nova
    12      12     Easy Listening
    13      13        Heavy Metal
    14      14           R&B/Soul
    15      15  Electronica/Dance
    16      16              World
    17      17        Hip Hop/Rap
    18      18    Science Fiction
    19      19           TV Shows
    20      20   Sci Fi & Fantasy
    21      21              Drama
    22      22             Comedy
    23      23        Alternative
    24      24          Classical
    25      25              Opera
    

    .

    2️⃣ dbGetQuery()

    ในกรณีที่เราต้องการดูข้อมูลแบบเจาะจง เราจะใช้ dbGetQuery() ซึ่งต้องการ 2 arguments:

    1. Connection ที่เชื่อมต่อกับ database
    2. SQL query ที่กำหนดข้อมูลที่ต้องการจาก database

    ตัวอย่างการใช้งาน #1 – ดึงข้อมูลลูกค้าที่มาจากบราซิล:

    # Query with dbGetQuery() - example 1
    dbGetQuery(con,
               "SELECT
                  CustomerId,
                  FirstName,
                  LastName, Email
                FROM
                  Customer
                WHERE
                  country = 'Brazil';")
    

    ผลลัพธ์:

      CustomerId FirstName  LastName                         Email
    1          1      Luís Gonçalves          luisg@embraer.com.br
    2         10   Eduardo   Martins      eduardo@woodstock.com.br
    3         11 Alexandre     Rocha              alero@uol.com.br
    4         12   Roberto   Almeida roberto.almeida@riotur.gov.br
    5         13  Fernanda     Ramos      fernadaramos4@uol.com.br
    

    ตัวอย่าง #2 – คำนวณยอดขายรวมของแต่ละประเทศ โดยเรียงจากมากไปน้อย:

    # Query with dbGetQuery() - example 2
    dbGetQuery(con,
               "SELECT
                  BillingCountry,
                  SUM(Total) AS TotalSales
                FROM
                  Invoice
                GROUP BY
                  BillingCountry
                ORDER BY
                  TotalSales DESC;")
    

    ผลลัพธ์:

       BillingCountry TotalSales
    1             USA     523.06
    2          Canada     303.96
    3          France     195.10
    4          Brazil     190.10
    5         Germany     156.48
    6  United Kingdom     112.86
    7  Czech Republic      90.24
    8        Portugal      77.24
    9           India      75.26
    10          Chile      46.62
    11        Ireland      45.62
    12        Hungary      45.62
    13        Austria      42.62
    14        Finland      41.62
    15    Netherlands      40.62
    16         Norway      39.62
    17         Sweden      38.62
    18          Spain      37.62
    19         Poland      37.62
    20          Italy      37.62
    21        Denmark      37.62
    22        Belgium      37.62
    23      Australia      37.62
    24      Argentina      37.62
    

    ตัวอย่าง #3 – ดึงชื่อเพลงและชื่ออัลบัม 10 อันดับแรก:

    # Query with dbGetQuery() - example 3
    dbGetQuery(con,
               "SELECT
                  T.Name AS TrackName,
                  A.Title AS AlbumTitle
                FROM
                  Track AS T
                JOIN
                  Album AS A ON T.AlbumID = A.AlbumID
                LIMIT 10;")
    

    ผลลัพธ์:

                                     TrackName                            AlbumTitle
    1  For Those About To Rock (We Salute You) For Those About To Rock We Salute You
    2                        Balls to the Wall                     Balls to the Wall
    3                          Fast As a Shark                     Restless and Wild
    4                        Restless and Wild                     Restless and Wild
    5                     Princess of the Dawn                     Restless and Wild
    6                    Put The Finger On You For Those About To Rock We Salute You
    7                          Let's Get It Up For Those About To Rock We Salute You
    8                         Inject The Venom For Those About To Rock We Salute You
    9                               Snowballed For Those About To Rock We Salute You
    10                              Evil Walks For Those About To Rock We Salute You
    

    .

    3️⃣ dbSendQuery()

    dbSendQuery() ทำงานเหมือนกับ dbGetQuery() แต่ต่างกันที่ dbGetQuery() จะยังส่งข้อมูลใด ๆ กลับมาจนกว่าเราจะเรียกดูด้วย dbFetch()

    ยกตัวอย่างเช่น ดูข้อมูลลูกค้า 10 รายชื่อแรกเมื่อเรียงตามนามสกุล:

    # Send query
    res <- dbSendQuery(con,
                       "SELECT
                          CustomerId,
                          LastName,
                          FirstName,
                          Email
                        FROM
                          Customer
                        ORDER BY
                          LastName
                        LIMIT 10;")
    
    # Fetch results
    dbFetch(res)
    

    ผลลัพธ์:

       CustomerId   LastName FirstName                         Email
    1          12    Almeida   Roberto roberto.almeida@riotur.gov.br
    2          28    Barnett     Julia           jubarnett@gmail.com
    3          39    Bernard   Camille      camille.bernard@yahoo.fr
    4          18     Brooks  Michelle             michelleb@aol.com
    5          29      Brown    Robert              robbrown@shaw.ca
    6          21      Chase     Kathy           kachase@hotmail.com
    7          26 Cunningham   Richard      ricunningham@hotmail.com
    8          41     Dubois      Marc       marc.dubois@hotmail.com
    9          34  Fernandes      João           jfernandes@yahoo.pt
    10         30    Francis    Edward           edfrancis@yachoo.ca
    

    เมื่อเราเรียกดูข้อมูลทั้งหมดแล้ว เราจะไม่สามารถเรียกดูซ้ำได้:

    # Fetch results
    dbFetch(res)
    

    ผลลัพธ์:

    > dbFetch(res)
    [1] CustomerId LastName   FirstName  Email     
    <0 rows> (or 0-length row.names)
    

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

    # Send query
    res <- dbSendQuery(con,
                       "SELECT
                          CustomerId,
                          LastName,
                          FirstName,
                          Email
                        FROM
                          Customer
                        ORDER BY
                          LastName
                        LIMIT 10;")
    
    # Fetch five, twice
    dbFetch(res, n = 5)
    dbFetch(res, n = 5)
    dbFetch(res, n = 5)
    

    ผลลัพธ์:

    > dbFetch(res, n = 5)
      CustomerId LastName FirstName                         Email
    1         12  Almeida   Roberto roberto.almeida@riotur.gov.br
    2         28  Barnett     Julia           jubarnett@gmail.com
    3         39  Bernard   Camille      camille.bernard@yahoo.fr
    4         18   Brooks  Michelle             michelleb@aol.com
    5         29    Brown    Robert              robbrown@shaw.ca
    > dbFetch(res, n = 5)
      CustomerId   LastName FirstName                    Email
    1         21      Chase     Kathy      kachase@hotmail.com
    2         26 Cunningham   Richard ricunningham@hotmail.com
    3         41     Dubois      Marc  marc.dubois@hotmail.com
    4         34  Fernandes      João      jfernandes@yahoo.pt
    5         30    Francis    Edward      edfrancis@yachoo.ca
    > dbFetch(res, n = 5)
    [1] CustomerId LastName   FirstName  Email     
    <0 rows> (or 0-length row.names)
    

    เราสามารถใช้ dbSendQuery() และ dbFetch() เพื่อดูข้อมูลเป็นชุด ๆ แทนที่จะดูข้อมูลทั้งหมดในครั้งเดียวแบบ dbGetQuery()

    Note: ในกรณีที่เราต้องการลบ query ที่เราส่งไป database ด้วย dbSendQuery() ให้เราใช้ dbClearResult():

    # Clear results
    dbClearResult(res)
    

    🤚 Step 4. Close the Connection

    สุดท้าย เมื่อเราทำงานกับ database เสร็จแล้ว เราต้องสิ้นสุดการเชื่อมต่อกับ database ด้วย dbDisconnect():

    # Close the connection
    dbDisconnect(con)
    

    เป็นอันจบการทำงานกับ database ด้วย DBI


    💪 Summary

    ในบทความนี้ เราได้ไปดูวิธีการใช้งาน DBI เพื่อทำงานกับ database กัน:

    เชื่อมต่อ database:

    • dbConnect()

    สำรวจ database:

    • dbListTables()
    • dbGetQuery()

    Query ข้อมูล:

    • dbReadTable()
    • dbGetQuery()
    • dbSendQuery(), dbFetch(), และ dbClearResult()

    ปิดการเชื่อมต่อ:

    • dbDisconnect()

    😺 GitHub

    ดู code และ database ในบทความนี้ได้ที่ 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:

  • sqldf(): แนะนำ function ในการทำงานกับ data frame ด้วย SQL ในภาษา R — ตัวอย่างจาก Cars93

    sqldf(): แนะนำ function ในการทำงานกับ data frame ด้วย SQL ในภาษา R — ตัวอย่างจาก Cars93

    ในบทความนี้ เราจะมาดูวิธีใช้ sqldf() ซึ่งเป็น function ที่ช่วยให้เราทำงานกับ data frame ในภาษา R ได้ด้วย SQL syntax และเหมาะกับคนที่คุ้นเคยกับการใช้ SQL ในการทำงานกัน

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


    1. 🏁 Getting Started: Install & Load sqldf
    2. 🏃‍♂️‍➡️ Using sqldf
      1. 1️⃣ Example 1. SELECT
      2. 2️⃣ Example 2. WHERE
      3. 3️⃣ Example 3. Aggregate
    3. 😺 GitHub
    4. 📃 References
    5. ✅ R Book for Psychologists: หนังสือภาษา R สำหรับนักจิตวิทยา

    🏁 Getting Started: Install & Load sqldf

    ก่อนเริ่มใช้ sqldf() เราจะต้องติดตั้งและโหลด sqldf ซึ่งเป็น package ต้นทางของ sdldf() ด้วย install.packages() และ library() ตามลำดับ:

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

    Note:

    • เราใช้ install.packages() เพื่อติดตั้งแค่ครั้งเดียว
    • เราใช้ library() เพื่อโหลด sqldf ทุกครั้งที่เริ่ม session ใหม่

    🏃‍♂️‍➡️ Using sqldf

    sqldf() ต้องการ 1 argument คือ character ที่มี SQL query เช่น:

    sqldf("SELECT * FROM df")
    

    เราลองมาดูตัวอย่างการใช้ sqldf() กับ Cars93 dataset (จาก MASS package) ซึ่งมีข้อมูลรถ 93 คันที่ขายในปี ค.ศ. 1993:

    # Install MASS
    install.packages("MASS")
    
    # Load MASS
    library(MASS)
    
    # Load the dataset
    data(Cars93)
    
    # View the dataset structure
    str(Cars93)
    

    ผลลัพธ์:

    'data.frame':	93 obs. of  27 variables:
     $ Manufacturer      : Factor w/ 32 levels "Acura","Audi",..: 1 1 2 2 3 4 4 4 4 5 ...
     $ Model             : Factor w/ 93 levels "100","190E","240",..: 49 56 9 1 6 24 54 74 73 35 ...
     $ Type              : Factor w/ 6 levels "Compact","Large",..: 4 3 1 3 3 3 2 2 3 2 ...
     $ Min.Price         : num  12.9 29.2 25.9 30.8 23.7 14.2 19.9 22.6 26.3 33 ...
     $ Price             : num  15.9 33.9 29.1 37.7 30 15.7 20.8 23.7 26.3 34.7 ...
     $ Max.Price         : num  18.8 38.7 32.3 44.6 36.2 17.3 21.7 24.9 26.3 36.3 ...
     $ MPG.city          : int  25 18 20 19 22 22 19 16 19 16 ...
     $ MPG.highway       : int  31 25 26 26 30 31 28 25 27 25 ...
     $ AirBags           : Factor w/ 3 levels "Driver & Passenger",..: 3 1 2 1 2 2 2 2 2 2 ...
     $ DriveTrain        : Factor w/ 3 levels "4WD","Front",..: 2 2 2 2 3 2 2 3 2 2 ...
     $ Cylinders         : Factor w/ 6 levels "3","4","5","6",..: 2 4 4 4 2 2 4 4 4 5 ...
     $ EngineSize        : num  1.8 3.2 2.8 2.8 3.5 2.2 3.8 5.7 3.8 4.9 ...
     $ Horsepower        : int  140 200 172 172 208 110 170 180 170 200 ...
     $ RPM               : int  6300 5500 5500 5500 5700 5200 4800 4000 4800 4100 ...
     $ Rev.per.mile      : int  2890 2335 2280 2535 2545 2565 1570 1320 1690 1510 ...
     $ Man.trans.avail   : Factor w/ 2 levels "No","Yes": 2 2 2 2 2 1 1 1 1 1 ...
     $ Fuel.tank.capacity: num  13.2 18 16.9 21.1 21.1 16.4 18 23 18.8 18 ...
     $ Passengers        : int  5 5 5 6 4 6 6 6 5 6 ...
     $ Length            : int  177 195 180 193 186 189 200 216 198 206 ...
     $ Wheelbase         : int  102 115 102 106 109 105 111 116 108 114 ...
     $ Width             : int  68 71 67 70 69 69 74 78 73 73 ...
     $ Turn.circle       : int  37 38 37 37 39 41 42 45 41 43 ...
     $ Rear.seat.room    : num  26.5 30 28 31 27 28 30.5 30.5 26.5 35 ...
     $ Luggage.room      : int  11 15 14 17 13 16 17 21 14 18 ...
     $ Weight            : int  2705 3560 3375 3405 3640 2880 3470 4105 3495 3620 ...
     $ Origin            : Factor w/ 2 levels "USA","non-USA": 2 2 2 2 2 1 1 1 1 1 ...
     $ Make              : Factor w/ 93 levels "Acura Integra",..: 1 2 4 3 5 6 7 9 8 10 ...
    

    .

    1️⃣ Example 1. SELECT

    เลือกข้อมูลจาก columns Manufacturer, Model, Min.Price, และ Max.Price:

    # Set query
    select_query <- "
    SELECT
      Manufacturer,
      Model,
      `Min.Price`,
      `Max.Price`
    FROM
      Cars93
    "
    
    # Select from df
    select_result <- sqldf(select_query)
    
    # View the result
    select_result
    

    Note: เราใช้ backticks (`) สำหรับชื่อ columns ที่ไม่ valid ใน SQL (เช่น column ที่มี . อย่าง Min.Price และ Max.Price)

    ผลลัพธ์:

        Manufacturer          Model Min.Price Max.Price
    1          Acura        Integra      12.9      18.8
    2          Acura         Legend      29.2      38.7
    3           Audi             90      25.9      32.3
    4           Audi            100      30.8      44.6
    5            BMW           535i      23.7      36.2
    6          Buick        Century      14.2      17.3
    7          Buick        LeSabre      19.9      21.7
    8          Buick     Roadmaster      22.6      24.9
    9          Buick        Riviera      26.3      26.3
    10      Cadillac        DeVille      33.0      36.3
    11      Cadillac        Seville      37.5      42.7
    12     Chevrolet       Cavalier       8.5      18.3
    13     Chevrolet        Corsica      11.4      11.4
    14     Chevrolet         Camaro      13.4      16.8
    15     Chevrolet         Lumina      13.4      18.4
    16     Chevrolet     Lumina_APV      14.7      18.0
    17     Chevrolet          Astro      14.7      18.6
    18     Chevrolet        Caprice      18.0      19.6
    19     Chevrolet       Corvette      34.6      41.5
    20      Chrylser       Concorde      18.4      18.4
    21      Chrysler        LeBaron      14.5      17.1
    22      Chrysler       Imperial      29.5      29.5
    23         Dodge           Colt       7.9      10.6
    24         Dodge         Shadow       8.4      14.2
    25         Dodge         Spirit      11.9      14.7
    26         Dodge        Caravan      13.6      24.4
    27         Dodge        Dynasty      14.8      16.4
    28         Dodge        Stealth      18.5      33.1
    29         Eagle         Summit       7.9      16.5
    30         Eagle         Vision      17.5      21.2
    31          Ford        Festiva       6.9       7.9
    32          Ford         Escort       8.4      11.9
    33          Ford          Tempo      10.4      12.2
    34          Ford        Mustang      10.8      21.0
    35          Ford          Probe      12.8      15.2
    36          Ford       Aerostar      14.5      25.3
    37          Ford         Taurus      15.6      24.8
    38          Ford Crown_Victoria      20.1      21.7
    39           Geo          Metro       6.7      10.0
    40           Geo          Storm      11.5      13.5
    41         Honda        Prelude      17.0      22.7
    42         Honda          Civic       8.4      15.8
    43         Honda         Accord      13.8      21.2
    44       Hyundai          Excel       6.8       9.2
    45       Hyundai        Elantra       9.0      11.0
    46       Hyundai         Scoupe       9.1      11.0
    47       Hyundai         Sonata      12.4      15.3
    48      Infiniti            Q45      45.4      50.4
    49         Lexus          ES300      27.5      28.4
    50         Lexus          SC300      34.7      35.6
    51       Lincoln    Continental      33.3      35.3
    52       Lincoln       Town_Car      34.4      37.8
    53         Mazda            323       7.4       9.1
    54         Mazda        Protege      10.9      12.3
    55         Mazda            626      14.3      18.7
    56         Mazda            MPV      16.6      21.7
    57         Mazda           RX-7      32.5      32.5
    58 Mercedes-Benz           190E      29.0      34.9
    59 Mercedes-Benz           300E      43.8      80.0
    60       Mercury          Capri      13.3      15.0
    61       Mercury         Cougar      14.9      14.9
    62    Mitsubishi         Mirage       7.7      12.9
    63    Mitsubishi       Diamante      22.4      29.9
    64        Nissan         Sentra       8.7      14.9
    65        Nissan         Altima      13.0      18.3
    66        Nissan          Quest      16.7      21.5
    67        Nissan         Maxima      21.0      22.0
    68    Oldsmobile        Achieva      13.0      14.0
    69    Oldsmobile  Cutlass_Ciera      14.2      18.4
    70    Oldsmobile     Silhouette      19.5      19.5
    71    Oldsmobile   Eighty-Eight      19.5      21.9
    72      Plymouth          Laser      11.4      17.4
    73       Pontiac         LeMans       8.2       9.9
    74       Pontiac        Sunbird       9.4      12.8
    75       Pontiac       Firebird      14.0      21.4
    76       Pontiac     Grand_Prix      15.4      21.6
    77       Pontiac     Bonneville      19.4      29.4
    78          Saab            900      20.3      37.1
    79        Saturn             SL       9.2      12.9
    80        Subaru          Justy       7.3       9.5
    81        Subaru         Loyale      10.5      11.3
    82        Subaru         Legacy      16.3      22.7
    83        Suzuki          Swift       7.3      10.0
    84        Toyota         Tercel       7.8      11.8
    85        Toyota         Celica      14.2      22.6
    86        Toyota          Camry      15.2      21.2
    87        Toyota         Previa      18.9      26.6
    88    Volkswagen            Fox       8.7       9.5
    89    Volkswagen        Eurovan      16.6      22.7
    90    Volkswagen         Passat      17.6      22.4
    91    Volkswagen        Corrado      22.9      23.7
    92         Volvo            240      21.8      23.5
    93         Volvo            850      24.8      28.5
    

    .

    2️⃣ Example 2. WHERE

    คัดกรองข้อมูลรถที่ชื่อผู้ผลิตขึ้นต้นด้วย “M”:

    # Set query
    where_result <- "
    SELECT
      Manufacturer,
      Model,
      `Min.Price`,
      `Max.Price`
    FROM
      Cars93
    WHERE
      Manufacturer LIKE 'M%'
    "
    
    # Filter df
    where_result <- sqldf(where_result)
    
    # View the result
    where_result
    

    ผลลัพธ์:

        Manufacturer    Model Min.Price Max.Price
    1          Mazda      323       7.4       9.1
    2          Mazda  Protege      10.9      12.3
    3          Mazda      626      14.3      18.7
    4          Mazda      MPV      16.6      21.7
    5          Mazda     RX-7      32.5      32.5
    6  Mercedes-Benz     190E      29.0      34.9
    7  Mercedes-Benz     300E      43.8      80.0
    8        Mercury    Capri      13.3      15.0
    9        Mercury   Cougar      14.9      14.9
    10    Mitsubishi   Mirage       7.7      12.9
    11    Mitsubishi Diamante      22.4      29.9
    

    .

    3️⃣ Example 3. Aggregate

    หารถ 10 อันดับแรกที่มีราคาสูงสุด:

    # Set query
    aggregate_query <- "
    SELECT
      Manufacturer,
      AVG(Price) AS Avg_Price
    FROM
      Cars93
    GROUP BY
      Manufacturer
    ORDER BY
      Avg_Price DESC
    LIMIT
      10;
    "
    
    # Aggregate df
    aggregate_result <- sqldf(aggregate_query)
    
    # View the result
    aggregate_result
    

    ผลลัพธ์:

        Manufacturer Avg_Price
    1       Infiniti      47.9
    2  Mercedes-Benz      46.9
    3       Cadillac      37.4
    4        Lincoln      35.2
    5           Audi      33.4
    6          Lexus      31.6
    7            BMW      30.0
    8           Saab      28.7
    9          Acura      24.9
    10         Volvo      24.7
    

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

  • readxl และ XLConnect: วิธีใช้ 2 packages สำหรับทำงานกับ Excel ในภาษา R — ตัวอย่างการทำงานกับ Daily Household Transactions

    readxl และ XLConnect: วิธีใช้ 2 packages สำหรับทำงานกับ Excel ในภาษา R — ตัวอย่างการทำงานกับ Daily Household Transactions

    Excel เป็นเครื่องมือทำงานยอดนิยมในการทำงาน ซึ่งทำให้ในหลาย ๆ ครั้ง ข้อมูลที่เราต้องการถูกเก็บอยู่ในไฟล์ Excel (เช่น .xls และ .xlsx)

    ในบทความนี้ เราจะมาทำความรู้จักกับ readxl และ XLConnect ซึ่งเป็น packages สำหรับทำงานกับ Excel ในภาษา R กัน

    เราจะดูการใช้งานผ่านตัวอย่างการทำงานกับ Daily Transactions Dataset จาก Kaggle ที่ถูกเก็บในไฟล์ XLSX (”Daily Household Transactions.xlsx”):

    ข้อมูลใน ”Daily Household Transactions.xlsx”

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


    1. 1️⃣ Package 1. readxl
    2. 2️⃣ Package 2. XLConnect
      1. 📔 กรณีที่ 1. โหลดและสำรวจ Workbook
      2. ⬇️ กรณีที่ 2. โหลดข้อมูลจาก sheet
      3. 🖐️ กรณีที่ 3. จัดการ Sheet
      4. ➕ กรณีที่ 4. เพิ่มข้อมูลใน Sheet
      5. 💾 กรณีที่ 5. บันทึก Workbook
    3. 💪 Summary
    4. 😺 GitHub
    5. 📃 References
    6. ✅ R Book for Psychologists: หนังสือภาษา R สำหรับนักจิตวิทยา

    1️⃣ Package 1. readxl

    readxl เป็น package สำหรับโหลดข้อมูลจาก Excel และมี function ที่เราจะเรียกใช้งานได้ คือ read_excel() ซึ่งต้องการ 2 arguments:

    1. path: ชื่อไฟล์ หรือ file path
    2. sheet: ชื่อหรือลำดับของ sheet ที่เก็บข้อมูลที่เราต้องการ

    ในการเริ่มต้นใช้งาน readxl เราจะติดตั้งและโหลด package:

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

    จากนั้น เรียกใช้ read_excel() เพื่อโหลดข้อมูล:

    # Import Excel data with read_excel()
    all_transactions <- read_excel("Daily Household Transactions.xlsx",
                                   sheet = 1)
    
    # View the first few rows
    head(all_transactions)
    

    ผลลัพธ์:

    # A tibble: 6 × 8
      Date                Mode              Category Subcategory Note  Amount `Income/Expense` Currency
      <dttm>              <chr>             <chr>    <chr>       <chr>  <dbl> <chr>            <chr>   
    1 2018-09-20 12:04:08 Cash              Transpo… Train       2 Pl…     30 Expense          INR     
    2 2018-09-20 12:03:15 Cash              Food     snacks      Idli…     60 Expense          INR     
    3 2018-09-19 00:00:00 Saving Bank acco… subscri… Netflix     1 mo…    199 Expense          INR     
    4 2018-09-17 23:41:17 Saving Bank acco… subscri… Mobile Ser… Data…     19 Expense          INR     
    5 2018-09-16 17:15:08 Cash              Festiva… Ganesh Puj… Gane…    251 Expense          INR     
    6 2018-09-15 06:34:17 Credit Card       subscri… Tata Sky    Perm…    200 Expense          INR     
    

    Note: read_excel() มี parametres อื่น ๆ ที่เราสามารถตั้งค่าได้ เช่น:

    • range: ช่วงข้อมูลที่เราต้องการโหลด
    • col_names: ชื่อ columns
    • col_types: ประเภทข้อมูลในแต่ละ column
    • skip: จำนวน rows ที่เราจะข้ามในการโหลดข้อมูล เช่น เรากำหนด skip = 5, read_excel() จะโหลดข้อมูลตั้งแต่ row ที่ 6 เป็นต้นไป

    ดูคู่มือการใช้งาน read_excel() ทั้งหมดได้ที่ read_excel: Read xls and xlsx files.


    2️⃣ Package 2. XLConnect

    XLConnect เป็น package ที่ช่วยให้เราทำงานกับไฟล์ Excel จาก R ได้โดยตรง

    การใช้งาน XLConnect แบ่งได้เป็น 5 กรณี ดังนี้:

    1. โหลดและสำรวจ workbook
    2. โหลดข้อมูลจาก sheet
    3. จัดการ sheet
    4. เพิ่มข้อมูลใน sheet
    5. บันทึก workbook

    เราไปดูการใช้งานในแต่ละกรณีกัน

    .

    📔 กรณีที่ 1. โหลดและสำรวจ Workbook

    ในการเริ่มใช้งาน XLConnect เราจะต้องติดตั้งและโหลด package ก่อน:

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

    จากนั้น เราสามารถโหลด Excel เราเข้ามาใน R ได้ด้วย loadWorkbook():

    # Load the workbook
    workbook <- loadWorkbook("Daily Household Transactions.xlsx")
    

    และดู sheet ทั้งหมดใน workbook ด้วย getSheets():

    # List sheets
    getSheets(workbook)
    

    ผลลัพธ์:

    [1] "All Transactions"
    

    ในตัวอย่าง จะเห็นว่า Excel ของเรามี 1 sheet ได้แก่ “All Transactions”

    .

    ⬇️ กรณีที่ 2. โหลดข้อมูลจาก sheet

    เมื่อเห็นโครงสร้างของไฟล์ Excel แล้ว เราสามารถโหลดข้อมูลจาก sheet ที่ต้องการได้ด้วย readWorksheet():

    # Get sheet data
    sheet1_data <- readWorksheet(workbook,
                                 sheet = "All Transactions")
    
    # Print data
    head(sheet1_data)
    

    ผลลัพธ์:

                     Date                  Mode       Category             Subcategory                                     Note Amount Income.Expense Currency
    1 2018-09-20 12:04:08                  Cash Transportation                   Train                     2 Place 5 to Place 0     30        Expense      INR
    2 2018-09-20 12:03:15                  Cash           Food                  snacks              Idli medu Vada mix 2 plates     60        Expense      INR
    3 2018-09-19 00:00:00 Saving Bank account 1   subscription                 Netflix                     1 month subscription    199        Expense      INR
    4 2018-09-17 23:41:17 Saving Bank account 1   subscription Mobile Service Provider                        Data booster pack     19        Expense      INR
    5 2018-09-16 17:15:08                  Cash      Festivals            Ganesh Pujan                              Ganesh idol    251        Expense      INR
    6 2018-09-15 06:34:17           Credit Card   subscription                Tata Sky Permanent Residence - Tata Play recharge    200        Expense      INR
    

    .

    🖐️ กรณีที่ 3. จัดการ Sheet

    ในการจัดการ sheet เราสามารถทำได้ 3 อย่าง:

    1. สร้าง sheet ใหม่: createSheet()
    2. เปลี่ยนชื่อ sheet: renameSheet()
    3. ลบ sheet: removeSheet()

    ยกตัวอย่างการสร้าง sheet ใหม่:

    # Create new sheets
    createSheet(workbook,
                name = "New")
    
    # List sheets
    getSheets(workbook)
    

    ผลลัพธ์:

    [1] "All Transactions" "New" 
    

    เปลี่ยนชื่อ sheet:

    # Rename the new sheet
    renameSheet(workbook,
                sheet = "New",
                newName = "Some Transactions")
    
    # List sheets
    getSheets(workbook)
    

    ผลลัพธ์:

    [1] "All Transactions"  "Some Transactions"
    

    และลบ sheet ทิ้ง:

    # Delete the new sheet
    removeSheet(workbook,
                sheet = "Some Transactions")
    
    # List sheets
    getSheets(workbook)
    

    ผลลัพธ์:

    [1] "All Transactions" 
    

    .

    ➕ กรณีที่ 4. เพิ่มข้อมูลใน Sheet

    เราสามารถใส่ข้อมูลลงใน sheet ได้ด้วย writeWorksheet()

    ยกตัวอย่างเช่น เราต้องการเพิ่มข้อมูลสรุปค่าใช้จ่ายตามประเภทการใช้จ่าย

    เราจะเริ่มจากสรุปค่าใช้จ่ายตามประเภทโดยใช้ dplyr package:

    # Load dplyr
    library(dplyr)
    
    # Calculate expense by category
    expense_by_cat <- sheet1_data |>
      
      # Filter for expense
      filter(Income.Expense == "Expense") |>
      
      # Group by category
      group_by(Category) |>
      
      # Calculate sum amount
      summarise(Sum = sum(Amount)) |>
        
      # Ungroup
      ungroup() |>
      
      # Sort by category
      arrange(desc(Sum))
    
    # View the results
    expense_by_cat
    

    (Note: อ่านเกี่ยวกับการใช้ dplyr ได้ที่นี่)

    ผลลัพธ์:

    # A tibble: 27 × 2
       Category                  Sum
       <chr>                   <dbl>
     1 Money transfer        606529.
     2 Investment            271858 
     3 Transportation        169054.
     4 Household             161646.
     5 subscription          114588.
     6 Food                   96403.
     7 Public Provident Fund  90000 
     8 Other                  87025.
     9 Family                 78582.
    10 Health                 66253.
    # ℹ 17 more rows
    # ℹ Use `print(n = ...)` to see more rows
    

    จากนั้น สร้าง sheet ใหม่เพื่อเก็บข้อมูลที่เราได้มา:

    # Create a new sheet
    createSheet(workbook,
                name = "Expense by Category")
    
    # Add data to "Expense by Catogory" sheet
    writeWorksheet(workbook,
                   data = expense_by_cat,
                   sheet = "Expense by Category")
    

    เมื่อเราเรียกดูข้อมูลจาก “Expense by Catogory” เราจะเห็นข้อมูลแบบนี้:

    # Read the sheet
    readWorksheet(workbook,
                  sheet = "Expense by Category")
    

    ผลลัพธ์:

                    Category       Sum
    1         Money transfer 606528.90
    2             Investment 271858.00
    3         Transportation 169053.78
    4              Household 161645.58
    5           subscription 114587.91
    6                   Food  96403.10
    7  Public Provident Fund  90000.00
    8                  Other  87025.28
    9                 Family  78582.20
    10                Health  66252.75
    11               Tourism  63608.85
    12                  Gift  40168.00
    13               Apparel  25373.82
    14     Recurring Deposit  22000.00
    15                  maid  21839.00
    16                  Cook  12443.00
    17                  Rent  10709.00
    18             Festivals   6911.00
    19               Culture   4304.36
    20                Beauty   4189.00
    21      Self-development   2357.00
    22             Education    537.00
    23              Grooming    400.00
    24           Social Life    298.00
    25   water (jar /tanker)    148.00
    26             Documents    100.00
    27      garbage disposal     67.00
    

    .

    💾 กรณีที่ 5. บันทึก Workbook

    จนถึงจุดนี้ สิ่งที่เราแก้ไขไปจะยังไม่ถูกบันทึกลงในไฟล์ Excel ของเรา

    เราต้องใช้ saveWorkbook() เพื่อบันทึกการเปลี่ยนแปลงทั้งหมดได้

    อย่างในตัวอย่าง เราจะบันทึกการเปลี่ยนแปลงทั้งหมดไปที่ workbook ใหม่ชื่อ “Daily Household Transactions (Updated).xlsx”:

    # Save the file
    saveWorkbook(workbook,
                 file = "Daily Household Transactions (Updated).xlsx")
    

    เมื่อเราเปิด working directory ดู เราจะเห็น Excel 2 ไฟล์:

    1. ไฟล์ต้นฉบับ
    2. ไฟล์ที่เราสร้างใหม่
    Workbook ต้นฉบับ (ซ้าย) และ workbook ที่เราสร้างใหม่ (ขวา)

    💪 Summary

    ในบทความนี้ เราได้เรียนรู้วิธีการทำงานกับ Excel ในภาษา R ผ่าน 2 packages ได้แก่:

    Package 1. readxl:

    FunctionFor
    read_excel()โหลดข้อมูลจาก Excel

    Package 2. XLConnect:

    FunctionFor
    loadWorkbook()โหลด workbook
    getSheets()ดู sheets ใน workbook
    readWorksheet()โหลดข้อมูลจาก sheet
    createSheet()สร้าง sheet
    renameSheet()เปลี่ยนชื่อ sheet
    removeSheet()ลบ sheet
    writeWorksheet()เพิ่มข้อมูลใน sheet
    saveWorkbook()บันทึก workbook

    😺 GitHub

    ดู code และ Excel ตัวอย่างได้ที่ 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:

  • if, for, while ใน Python: วิธีใช้ conditional statements, control flow, และ loop control ใน Python พร้อมตัวอย่าง

    if, for, while ใน Python: วิธีใช้ conditional statements, control flow, และ loop control ใน Python พร้อมตัวอย่าง

    ในบทความนี้ เราจะมาดูวิธีใช้ code 3 ประเภท ที่จะช่วยให้ Python code สามารถตัดสินใจแทนเราได้:

    1. Conditional statements: if, elif, else
    2. Control flow statements: for, while
    3. Loop control statements: continue, break, pass

    ก่อนไปดูวิธีใช้ทั้ง 3 ประเภท เราจะไปทำความรู้จักกับ comparison และ logical statement ซึ่งเราจะใช้ร่วมกับ code 3 ประเภทนี้กัน

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


    1. 🧮 1. Comparison & Logical Operators
      1. #️⃣ (1) Comparison Operators
      2. ♟️ (2) Logical Operators
    2. 🚦 2. Conditional Statements
    3. 🌊 3. Control Flow Statements
      1. 📦 (1) for Loop
      2. 🔁 (2) while Loop
    4. 🚄 4. Loop Control Statements
    5. 💪 5. Summary
    6. 😺 GitHub
    7. 📃 References

    🧮 1. Comparison & Logical Operators

    #️⃣ (1) Comparison Operators

    Comparison operators เป็นเครื่องหมายใช้เปรียบเทียบข้อมูล:

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

    โดย comparison operators จะให้ผลลัพธ์เป็น Boolean (True, False) กลับมา เช่น:

    # True statement
    10 > 5
    

    ผลลัพธ์:

    True
    

    และ:

    # False statement
    10 < 5
    

    ผลลัพธ์:

    False
    

    ♟️ (2) Logical Operators

    Logical operators เป็น keywords เชื่อมเงื่อนไข ช่วยให้เราประเมินหลายเงื่อนไขพร้อมกันได้:

    OperatorDescription
    andLogical AND
    orLogical OR
    notLogical NOT

    โดยผลลัพธ์เป็นไปตาม truth table:

    Condition 1OperatorCondition 2Result
    TrueandTrueTrue
    TrueandFalseFalse
    FalseandFalseFalse
    TrueorTrueTrue
    TrueorFalseTrue
    FalseorFalseFalse
    notTrueFalse
    notFalseTrue

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

    # True and True
    1 == 1 and 2 < 4
    

    ผลลัพธ์:

    True
    

    🚦 2. Conditional Statements

    Conditional statements ใช้กำหนดเงื่อนไขว่า code จะรันได้เมื่อไร และมีอยู่ 3 แบบ ได้แก่:

    • if: กำหนดเงื่อนไขแรก
    • elif: กำหนดเงื่อนไขเพิ่มเติม
    • else: รันเมื่อตรงกับเงื่อนไขอื่น ๆ ที่ไม่ใช่ if และ elif

    ยกตัวอย่างเช่น เราต้องการ print ข้อความแจ้งเตือนตามสภาพอากาศ:

    # Weather today
    weather = "snowy"
    

    เราสามารถทำได้แบบนี้:

    # Print when sunny
    if weather == "sunny":
        print("It's a sunny day. Don't forget your sunscreen!")
    
    # Print when rainy
    elif weather == "rainy":
        print("It's raining. Remember to bring an umbrella!")
    
    # Print when other conditions
    else:
        print("Likely chilly. Wear a jacket!")
    

    ผลลัพธ์:

    Likely chilly. Wear a jacket!
    

    อธิบาย code:

    • if block: ประเมินว่า weather เป็น "sunny" ไหม ถ้าใช่ จะ print "It's a sunny day. Don't forget your sunscreen!"
    • elif block: weather เป็น "rainy" ไหม ถ้าใช่ จะ print "It's raining. Remember to bring an umbrella!"
    • else block: ถ้า weather เป็นค่าอื่น ๆ (เช่น "snowy") จะ print "Likely chilly. Wear a jacket!"

    เพราะ weather มีค่าตรงกับ else block เราจึงได้ผลลัพธ์เป็น "Likely chilly. Wear a jacket!"


    🌊 3. Control Flow Statements

    Control flow statements ใช้ควบคุมลำดับการทำงานของ code และมีอยู่ 2 แบบ ได้แก่:

    1. for: รัน code ตามจำนวนข้อมูลที่มี
    2. while: รัน code จนกว่าเงื่อนไขจะไม่เป็นจริง

    📦 (1) for Loop

    ตัวอย่าง for loop เช่น print ชื่อแขกในงาน:

    # Guest list
    guests = ["James Bond", "John Wick", "Jack Reacher", "Jason Bourne", "Jack Ryan"]
    
    # Print guest names
    for name in guests:
        
        # Print name
        print(name)
    

    ผลลัพธ์:

    James Bond
    John Wick
    Jack Reacher
    Jason Bourne
    Jack Ryan
    

    อธิบาย code:

    • guest = ...: สร้าง list เก็บรายชื่อแขก
    • for ...: นำชื่อแขกใน list มา print จนกว่าจะครบทุกคน

    🔁 (2) while Loop

    ตัวอย่าง while loop เช่น นับเลข 1 ถึง 10:

    # Starting number
    number = 1
    
    # Count to 10
    while number <= 10:
        
        # Print number
        print(number)
        
        # Add 1 to number
        number += 1
    

    ผลลัพธ์:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    

    อธิบาย code:

    • number = 1: กำหนดเลขเริ่มต้น
    • while ...: print number และปรับ number ให้สูงขึ้น 1 ค่า ทำอย่างนี้วนไปจนกว่า number จะมากกว่า 10 (number <= 10 ไม่เป็นจริง)

    🚄 4. Loop Control Statements

    Loop control statements ใช้ควบคุมการทำงานของ control flow และมีอยู่ 3 แบบ ได้แก่:

    1. continue: skip ไป item ถัดไป
    2. break: หยุดการทำงานของ control flow
    3. pass: placeholder สำหรับใส่ code ในอนาคต

    ยกตัวอย่างเช่น เรามีรายการของที่ต้องซื้อ และแต่ละอย่างมี action ไม่เหมือนกัน:

    # A shopping list program
    shopping_list = ["milk", "bread", "chips", "apple", "toothpaste", "chocolate"]
    
    # Loop through the list
    for item in shopping_list:
    
        # Skip item if chip
        if item == "chips":
            print("Chips are unhealthy. Skipping ...")
            continue
        
        # Stop the loop if toothpaste
        if item == "toothpaste":
            print("Found toothpaste, done shopping early!")
            break
        
        # Do nothing if milk
        if item == "milk" or item == "bread":
            pass
        
        # Print item
        print("Putting", item, "into the cart.")
    

    ผลลัพธ์:

    Putting milk into the cart.
    Putting bread into the cart.
    Chips are unhealthy. Skipping ...
    Putting apple into the cart.
    Found toothpaste, done shopping early!
    

    อธิบาย code:

    • shopping_list = ...: สร้าง list เก็บรายการซื้อของ
    • if item == "chips" block: ประเมินว่า item ใช่ "chip" ไหม ถ้าใช่ ให้ print "Chips are unhealthy. Skipping ..." และข้ามไป item ถัดไป (continue)
    • if item == "toothpaste" block: ประเมินว่า item ใช่ "toothpaste" ไหม ถ้าใช่ ให้ print "Found toothpaste, done shopping early!" และจบ loop ทันที (break)
    • if item == "milk" … block: ประเมินว่า item ใช่ "milk" หรือ "bread" ไหม ถ้าใช่ ไม่ต้องทำอะไร (pass)
    • print ...: print ว่า กำลังเอา item ใส่ตระกร้า

    สังเกตว่า:

    • มีแค่ milk, bread, apple ที่ “กำลังใส่ตระกร้า” เพราะ milk และ bread อยู่ใน pass block และ apple ไม่ได้อยู่ใน block ไหนเลย
    • Chip ถูกข้ามไป เพราะอยู่ใน continue block
    • Toothpaste อยู่ใน break block และมาก่อน chocolate ทำให้เราไม่เห็น chocolate เพราะ toothpaste

    💪 5. Summary

    ในบทความนี้ เราได้ไปดูวิธีการเขียน code ใน Python เพื่อให้ code ตัดสินใจได้:

    Comparison operators:

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

    Logical operators:

    OperatorDescription
    andLogical AND
    orLogical OR
    notLogical NOT

    Conditional statements:

    StatementDescription
    ifกำหนดเงื่อนไขแรก
    elifกำหนดเงื่อนไขเพิ่มเติม
    elseทำ action เมื่อเข้าเงื่อนไขอื่น ๆ

    Control flow statements:

    StatementDescription
    forวนจนครบทุก item
    whileวนจนกว่าเงื่อนไขจะเป็น False

    Loop control statements:

    StatementDescription
    continueSkip
    breakStop
    passDo nothing

    😺 GitHub

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


    📃 References