0Pricing
R Academy · บทเรียน

ไดเรกทอรีทำงานและเส้นทางไฟล์

ใช้ getwd(), setwd() และ here() เพื่อสร้างเส้นทางที่เชื่อถือได้ข้ามแพลตฟอร์ม

ไดเรกทอรีทำงานและเส้นทางไฟล์ เป็นบทเรียน R Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน R Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส R Academy มีบทเรียนทั้งหมด 4 บทเรียน

ไดเรกทอรีทำงานคืออะไร

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

# getwd() returns the current working directory
current_dir <- getwd()
cat('Working directory:', current_dir)

# All relative file references start from this location:
# read.csv('data.csv')         <- looks in current_dir/data.csv
# source('R/helpers.R')        <- looks in current_dir/R/helpers.R

setwd() — การเปลี่ยนไดเรกทอรีทำงาน

setwd() เปลี่ยนไดเรกทอรีทำงานสำหรับเซสชัน R ปัจจุบัน โดยจะคืนค่าไดเรกทอรีทำงาน ก่อนหน้า แบบไม่แสดงผล ซึ่งมีประโยชน์สำหรับการคืนสถานะเดิม หมายเหตุ: ไม่แนะนำให้ใช้ setwd() ในสคริปต์สำหรับกระบวนการทำงานที่อิงโครงการ

# Set a new working directory
old_dir <- setwd('/tmp')
cat('Now in:', getwd(), '\n')

# Restore original directory
setwd(old_dir)
cat('Restored to:', getwd(), '\n')

# Common anti-pattern (breaks on other machines):
# setwd('/Users/alice/Desktop/my_project')  <- hardcoded!

# Better: use RStudio Projects which set wd automatically

file.path() — การสร้างเส้นทางที่ย้ายไปใช้ที่อื่นได้

file.path() สร้างเส้นทางไฟล์โดยเชื่อมส่วนต่าง ๆ ด้วยตัวคั่นที่ถูกต้องสำหรับระบบปฏิบัติการนั้น ๆ (/ บน Mac/Linux และ \ บน Windows) ควรใช้ฟังก์ชันนี้แทนการต่อสตริงเสมอเพื่อให้ทำงานข้ามระบบได้

# Build a path from components
data_path <- file.path('data', 'raw', 'sales.csv')
cat('Path:', data_path)
# On Unix:    data/raw/sales.csv
# On Windows: data\raw\sales.csv

# Multiple levels
output_file <- file.path('output', '2024', 'Q1', 'report.pdf')
cat('Output:', output_file)

# Combine with getwd() for a full absolute path
full_path <- file.path(getwd(), 'data', 'sales.csv')
cat('Full path:', full_path)

normalizePath() — การแปลงเป็นเส้นทางแบบสัมบูรณ์

normalizePath() แปลงเส้นทางแบบสัมพัทธ์เป็นรูปแบบสัมบูรณ์ตามรูปแบบมาตรฐาน โดยจัดการส่วนประกอบ . (ไดเรกทอรีปัจจุบัน) และ .. (ไดเรกทอรีแม่) วิธีนี้จำเป็นเมื่อคุณต้องจัดเก็บหรือบันทึกตำแหน่งไฟล์ที่ไม่กำกวม

# Resolve relative paths to absolute
abs_path <- normalizePath('.')
cat('Absolute cwd:', abs_path, '\n')

# Resolve a relative path
data_abs <- normalizePath(file.path('..', 'data', 'sales.csv'),
                          mustWork = FALSE)
cat('Resolved:', data_abs, '\n')

# mustWork = FALSE: do not error if file does not exist yet
# mustWork = TRUE (default): error if path does not exist

# Useful for building reliable log messages or config files
cat('normalizePath demo complete')

dirname() และ basename()

dirname() ดึง ส่วนไดเรกทอรีของเส้นทางออกมา ส่วน basename() ดึง ส่วนชื่อไฟล์ออกมา ฟังก์ชันเหล่านี้เทียบเท่ากับคำสั่งเชลล์ Unix dirname และ basename ใน R

path <- '/Users/alice/projects/analysis/data/sales_2024.csv'

# Extract the directory
folder <- dirname(path)
cat('Directory:', folder, '\n')
# /Users/alice/projects/analysis/data

# Extract the file name
filename <- basename(path)
cat('File name:', filename, '\n')
# sales_2024.csv

# Remove file extension
name_only <- tools::file_path_sans_ext(filename)
cat('Name only:', name_only)

file.exists() — ตรวจสอบก่อนอ่าน

ควรตรวจสอบว่าไฟล์มีอยู่หรือไม่ก่อนพยายามอ่านเสมอ เพื่อหลีกเลี่ยงข้อความข้อผิดพลาดที่เข้าใจยาก file.exists() จะคืนค่า TRUE หรือ FALSE และใช้ได้ทั้งกับไฟล์และไดเรกทอรี

data_file <- file.path('data', 'sales.csv')

# Check existence before reading
if (file.exists(data_file)) {
  cat('File found, loading...\n')
  # df <- read.csv(data_file)
} else {
  cat('File not found:', data_file, '\n')
  stop('Cannot proceed without data file.')
}

# Check multiple files at once
files <- c('data/a.csv', 'data/b.csv', 'data/c.csv')
exists_vec <- file.exists(files)
cat('Files found:', sum(exists_vec), 'of', length(files))

Sys.getenv() — เส้นทางจากตัวแปรสภาพแวดล้อม

ตัวแปรสภาพแวดล้อมใช้จัดเก็บเส้นทางระดับระบบ เช่น ไดเรกทอรีหลัก โฟลเดอร์ชั่วคราว และเส้นทางแอปที่กำหนดเอง Sys.getenv() ใช้อ่านค่าเหล่านี้ ทำให้โค้ดปรับใช้กับระบบต่าง ๆ ได้โดยไม่ต้องเขียนเส้นทางตายตัว

# Get the home directory
home_dir <- Sys.getenv('HOME')
cat('Home:', home_dir, '\n')

# Get the temp directory
tmp_dir <- Sys.getenv('TMPDIR')
cat('Temp:', tmp_dir, '\n')

# Custom environment variable (set in .Renviron)
data_root <- Sys.getenv('DATA_ROOT', unset = '/default/data')
cat('Data root:', data_root, '\n')

# Use env vars to build portable paths
config_file <- file.path(home_dir, '.config', 'myapp', 'settings.json')
cat('Config path:', config_file)

path.expand() — การขยายเครื่องหมายตัวหนอน

เครื่องหมายตัวหนอน ~ เป็นรูปแบบย่อของไดเรกทอรีหลักในระบบที่คล้าย Unix แต่ฟังก์ชันไฟล์ของ R ไม่ได้ขยายเครื่องหมายนี้โดยอัตโนมัติเสมอไป path.expand() จะแทนที่ ~ ด้วยเส้นทางไดเรกทอรีหลักจริง

# Expand tilde to full home path
short_path <- '~/.Rprofile'
full_path  <- path.expand(short_path)
cat('Expanded:', full_path)
# e.g. /Users/alice/.Rprofile

# Useful when passing paths to external tools or logging
config_dir <- path.expand('~/.config/R')
cat('Config dir:', config_dir)

# Can expand multiple paths at once
paths <- c('~/data', '~/output', '~/scripts')
expanded <- path.expand(paths)
cat(expanded, sep = '\n')

การแสดงรายการไฟล์ด้วย list.files()

list.files() (ชื่ออื่นคือ dir()) แสดงรายการไฟล์ในไดเรกทอรี โดยเลือกกรองตามรูปแบบและเลือกให้คืนค่าเป็นเส้นทางแบบเต็มได้ ฟังก์ชันนี้จำเป็นอย่างยิ่งเมื่อต้องประมวลผลไฟล์หลายไฟล์ในโฟลเดอร์

# List all files in current directory
all_files <- list.files('.')
cat('Files found:', length(all_files), '\n')

# Filter by extension
csv_files <- list.files('data', pattern = '\\.csv$', full.names = TRUE)
cat('CSV files:',  length(csv_files), '\n')

# Recursive: include subdirectories
r_files <- list.files('R', pattern = '\\.R$',
                       full.names = TRUE, recursive = TRUE)
cat('R scripts:', length(r_files))

การสร้างและลบเส้นทาง

R มีฟังก์ชันในตัวสำหรับสร้างไดเรกทอรีและจัดการไฟล์ ใช้ dir.create() เพื่อสร้างโฟลเดอร์ใหม่ โดยใช้ recursive = TRUE เพื่อสร้างเส้นทางที่ซ้อนกัน และใช้ file.remove() เพื่อลบไฟล์ชั่วคราวที่ไม่ต้องการ

# Create a directory (will not error if it already exists)
dir.create('output/figures', recursive = TRUE, showWarnings = FALSE)
cat('Directory created\n')

# Create a temporary file
tmp_file <- tempfile(fileext = '.csv')
write.csv(data.frame(x = 1:3), tmp_file, row.names = FALSE)
cat('Temp file:', tmp_file, '\n')

# Remove the file when done
if (file.remove(tmp_file)) {
  cat('Temp file cleaned up')
}

แพ็กเกจ here — เส้นทางที่อิงจากโครงการ

แพ็กเกจ here แก้ปัญหาเรื่องไดเรกทอรีทำงานได้อย่างลงตัว here::here() จะสร้างเส้นทางโดยอ้างอิงจากรากโครงการ ซึ่งเป็นตำแหน่งของไฟล์ .Rproj เสมอ ไม่ว่าคุณจะเรียกใช้ฟังก์ชันจากที่ใดในโครงการ

# install.packages('here')
# library(here)

# Always resolves from project root:
# here('data', 'raw', 'sales.csv')
# here('R', 'helpers.R')
# here('output', 'report.html')

# Without here: setwd() headaches when script is in a subfolder
# With here: same path works from any subfolder

# Demonstrate base-R equivalent approach:
project_root <- normalizePath(file.path(getwd(), '..'), mustWork = FALSE)
data_path    <- file.path(project_root, 'data', 'sales.csv')
cat('Data path:', data_path)

ตรวจสอบด่วน

คุณมีสตริงเส้นทาง 'data/raw/../clean/sales.csv' คุณจะใช้ฟังก์ชันใดเพื่อแปลงสตริงนี้ให้เป็นเส้นทางสัมบูรณ์แบบมาตรฐานที่สะอาด

ประเด็นสำคัญเกี่ยวกับเส้นทางไฟล์

การจัดการเส้นทางไฟล์อย่างรัดกุมเป็นสิ่งสำคัญต่อสคริปต์ R ที่ทำซ้ำผลลัพธ์ได้:

  • getwd() / setwd() — ดูและกำหนดไดเรกทอรีทำงาน
  • file.path('a', 'b', 'c.csv') — สร้างเส้นทางที่ใช้ได้กับทุก OS
  • normalizePath(path, mustWork = FALSE) — แปลงเป็นเส้นทางสัมบูรณ์
  • dirname() / basename() — แยกเส้นทางเป็นโฟลเดอร์และไฟล์
  • file.exists() — ตรวจสอบก่อนอ่าน
  • Sys.getenv('HOME') — เข้าถึงเส้นทางระบบผ่านตัวแปรสภาพแวดล้อม
  • path.expand('~') — ขยายเครื่องหมายทิลด์เป็นไดเรกทอรีบ้าน
  • list.files(pattern = '\.csv$') — ค้นหาไฟล์ตามนามสกุล
  • dir.create(recursive = TRUE) — สร้างไดเรกทอรีซ้อนกันอย่างปลอดภัย
  • ใช้แพ็กเกจ here สำหรับเส้นทางที่อ้างอิงจากโครงการในโครงการ RStudio
# Robust file loading pattern:
data_file <- file.path('data', 'raw', 'sales.csv')

if (!file.exists(data_file)) {
  stop(paste('Missing file:', normalizePath(data_file, mustWork = FALSE)))
}

# df <- read.csv(data_file)
cat('File path:', data_file, '\n')
cat('Full path:', normalizePath(data_file, mustWork = FALSE))

คำถามที่พบบ่อย

บทเรียน “ไดเรกทอรีทำงานและเส้นทางไฟล์” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “ไดเรกทอรีทำงานและเส้นทางไฟล์” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส R Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส R Academy มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “ไดเรกทอรีทำงานและเส้นทางไฟล์”

ใช้ getwd(), setwd() และ here() เพื่อสร้างเส้นทางที่เชื่อถือได้ข้ามแพลตฟอร์ม คุณปฏิบัติ R Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน R Academy หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน R Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน

บทเรียน “ไดเรกทอรีทำงานและเส้นทางไฟล์” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน R Academy นี้ได้ไหม

ได้ บทเรียน R Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. การใช้ source() เพื่อโหลดสคริปต์
  2. ความคิดเห็น รูปแบบ และความอ่านง่าย
  3. ไดเรกทอรีทำงานและเส้นทางไฟล์
  4. โปรเจกต์ R และการจัดการพื้นที่ทำงาน
← กลับไปที่ R Academy