작업 디렉터리와 파일 경로
신뢰할 수 있는 크로스 플랫폼 경로를 위해 getwd(), setwd(), here()를 사용합니다.
작업 디렉터리와 파일 경로은(는) CoddyKit의 무료 R Academy 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 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.Rsetwd() — 작업 디렉터리 변경
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 automaticallyfile.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()는 상대 경로를 표준 절대 경로로 변환하며, .(현재 디렉터리) 및 ..(부모 디렉터리) 구성 요소를 해석합니다. 모호하지 않은 파일 위치를 저장하거나 logging할 때 필수적입니다.
# 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')— 운영 체제에 상관없이 경로를 구성합니다normalizePath(path, mustWork = FALSE)— 절대 경로로 변환합니다dirname()/basename()— 경로를 폴더와 파일로 나눕니다file.exists()— 읽기 전에 존재 여부를 확인합니다Sys.getenv('HOME')— 환경 변수를 통해 시스템 경로에 접근합니다path.expand('~')— 물결표를 홈 디렉터리로 확장합니다list.files(pattern = '\.csv$')— 확장자로 파일을 찾습니다dir.create(recursive = TRUE)— 중첩된 디렉터리를 안전하게 만듭니다- RStudio 프로젝트에서는 프로젝트 기준 경로에 here 패키지를 사용합니다
# 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))자주 묻는 질문
“작업 디렉터리와 파일 경로” 강의는 무료인가요?
네 — “작업 디렉터리와 파일 경로” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 R Academy 강의 전체를 잠금 해제할 수 있습니다. R Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“작업 디렉터리와 파일 경로”에서 뭘 배우나요?
신뢰할 수 있는 크로스 플랫폼 경로를 위해 getwd(), setwd(), here()를 사용합니다. 브라우저에서 직접 실행하는 실습 코드로 R Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
R Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 R Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“작업 디렉터리와 파일 경로” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 R Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 R Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- source()로 스크립트 불러오기
- 주석, 스타일, 가독성
- 작업 디렉터리와 파일 경로
- R 프로젝트와 작업 공간 관리