0Pricing
R Academy · 강의

readxl로 Excel 파일 가져오기

시트 선택과 셀 범위 옵션을 사용하여 .xls 및 .xlsx 시트를 읽습니다.

readxl로 Excel 파일 가져오기은(는) CoddyKit의 무료 R Academy 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 R Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. R Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

Excel 파일에 readxl을 사용하는 이유

Excel 파일(.xlsx 및 .xls)은 업무 환경에서 매우 널리 사용됩니다. readxl 패키지는 Excel을 설치하지 않아도, Java 종속성 없이 파일을 읽습니다. tibble을 반환하며 여러 시트, 명명된 범위, 셀 유형 감지를 지원합니다.

library(readxl)

# readxl can read:
# .xlsx  - modern Excel format (XML-based)
# .xls   - older Excel format (binary)
# .xlsm  - Excel with macros (reads data, ignores macros)

# Core functions:
# read_excel()   - auto-detects .xls vs .xlsx
# read_xlsx()    - always reads as .xlsx
# read_xls()     - always reads as .xls
# excel_sheets() - lists all sheet names

cat('readxl requires no Java, no Excel installation!')

excel_sheets() — 모든 시트 나열하기

excel_sheets('file.xlsx')는 모든 시트 이름을 문자 벡터로 반환합니다. 파일을 읽기 전에 사용해 통합 문서 구조를 확인한 다음, 시트 이름을 read_excel()에 전달합니다.

library(readxl)

# Using readxl's built-in example file
path <- readxl_example('datasets.xlsx')

# List all sheets in the workbook
sheets <- excel_sheets(path)
print(sheets)

cat('\nNumber of sheets:', length(sheets))

read_excel() — 기본 사용법

read_excel(path)은 기본적으로 첫 번째 시트를 읽습니다. 파일이 .xls인지 .xlsx인지 자동으로 감지합니다. 결과는 데이터에서 추정한 열 유형을 포함하는 tibble입니다.

library(readxl)

path <- readxl_example('datasets.xlsx')

# Read the first sheet (default)
df <- read_excel(path)
print(head(df, 4))
cat('\nDimensions:', nrow(df), 'rows x', ncol(df), 'cols')

sheet 인수 — 이름 또는 인덱스로 선택하기

이름으로 선택하려면 sheet='Sheet1'을 사용하고, 위치로 선택하려면 sheet=2를 사용합니다(1부터 시작). 둘 다 유효합니다. 시트 순서가 바뀔 수 있다면 이름을 사용하는 편이 더 안정적이고, 반복 처리에는 인덱스를 사용하는 편이 편리합니다.

library(readxl)

path <- readxl_example('datasets.xlsx')
sheets <- excel_sheets(path)
print(sheets)

# Read by name
df_name <- read_excel(path, sheet = 'iris')
cat('iris sheet rows:', nrow(df_name), '\n')

# Read by index
df_idx <- read_excel(path, sheet = 2)
cat('Sheet 2 rows:', nrow(df_idx))

range — 셀 범위 읽기

range='A1:D10'은 Excel 표기법으로 지정한 셀 범위만 읽습니다. 워크시트에 여러 표가 있거나 서식 테두리가 있거나, 필요한 데이터 영역 바깥에 메타데이터가 있을 때 유용합니다.

library(readxl)

path <- readxl_example('datasets.xlsx')

# Read only the first 5 data rows of columns A-D
df <- read_excel(path, sheet='iris', range='A1:D6')
print(df)
cat('\nShape:', nrow(df), 'rows,', ncol(df), 'cols')

col_names — 사용자 지정 열 이름

col_names=FALSE로 설정하면 머리글 행을 건너뛰고 열 이름을 자동으로 지정합니다. 사용자 지정 이름을 사용하려면 문자 벡터를 col_names에 전달합니다(이 경우 머리글 행도 건너뜁니다). 머리글이 다른 행에 있다면 skip과 함께 사용합니다.

library(readxl)

path <- readxl_example('datasets.xlsx')

# Read with custom column names (skip original header)
df <- read_excel(
  path,
  sheet = 'iris',
  col_names = c('sepal_l','sepal_w','petal_l','petal_w','species'),
  skip = 1  # Skip the original header row
)

print(head(df, 3))
print(names(df))

skip 인수 — 메타데이터 행 건너뛰기

skip=n은 읽기 전에 시트의 처음 n개 행을 건너뜁니다. 워크시트의 실제 데이터 표 위에 보고서 제목, 생성 날짜 또는 기타 메타데이터가 있을 때 유용합니다.

library(readxl)

# Simulating a sheet with metadata rows (using a range instead)
path <- readxl_example('datasets.xlsx')

# Skip first row (pretend it has a title)
# and read only first 5 data rows
df <- read_excel(
  path,
  sheet = 'chickwts',
  skip = 1,       # Skip first data row
  col_names = FALSE  # Row 2 has no header now
)

print(head(df, 4))

col_types — 열 유형 지정하기

col_types를 사용하면 유형 추정을 재정의할 수 있습니다. 유효한 유형은 'text', 'numeric', 'date', 'logical', 'skip'(열 삭제), 'list'(유형이 섞인 열용)입니다.

library(readxl)

path <- readxl_example('datasets.xlsx')

# Read with explicit column types
# iris sheet: 4 numeric + 1 text
df <- read_excel(
  path,
  sheet = 'iris',
  col_types = c('numeric','numeric','numeric','numeric','text')
)

print(sapply(df, class))

map()으로 모든 시트 읽기

excel_sheets()와 purrr::map()을 결합하면 모든 시트를 한 번에 읽어 이름이 지정된 목록으로 만들 수 있습니다. 목록의 각 요소는 해당 시트의 tibble입니다. 모든 시트를 행 방향으로 결합하려면 map_df(.id='sheet')을 사용합니다.

library(readxl)
library(purrr)

path <- readxl_example('datasets.xlsx')
sheets <- excel_sheets(path)

# Read all sheets into a named list
all_data <- map(sheets, ~read_excel(path, sheet=.x))
names(all_data) <- sheets

# Show dimensions of each sheet
map_df(all_data, function(df) {
  data.frame(rows=nrow(df), cols=ncol(df))
}, .id='sheet')

n_max — 읽을 행 수 제한하기

n_max=n은 데이터 행을 최대 n개까지 읽습니다(머리글 제외). 큰 워크시트를 미리 보거나, 테스트용 표본을 불러오거나, 메모리가 제한된 환경에서 데이터를 여러 부분으로 나누어 읽을 때 사용합니다.

library(readxl)

path <- readxl_example('datasets.xlsx')

# Preview just the first 5 rows
preview <- read_excel(path, sheet='iris', n_max=5)
print(preview)
cat('\nPreviewed', nrow(preview), 'of', nrow(read_excel(path, sheet='iris')), 'rows')

na 인수 — 결측값 문자열

readr와 마찬가지로 readxl은 어떤 텍스트 문자열을 NA로 읽을지 지정하는 na 인수를 지원합니다. Excel에서는 결측값을 빈 셀(자동으로 처리됨)이나 'N/A', '#N/A'와 같은 대체 문자열로 저장하는 경우가 많습니다.

library(readxl)

path <- readxl_example('datasets.xlsx')

# Handle Excel error strings and custom NA markers
# In real files these might be '#N/A', '#VALUE!', 'N/A', '-'
df <- read_excel(
  path,
  sheet = 'iris',
  na = c('', 'NA', 'N/A', '#N/A', '-')
)

cat('Missing values per column:\n')
print(colSums(is.na(df)))

빠른 확인

excel_sheets('file.xlsx')는 무엇을 반환합니까?

요약: Excel 파일 가져오기

readxl을 사용한 Excel 가져오기의 핵심 내용:

  • excel_sheets(path) — 모든 시트 이름을 나열합니다
  • read_excel(path) — 첫 번째 시트를 읽고 .xls/.xlsx를 자동으로 감지합니다
  • sheet='Name' 또는 sheet=2 — 이름이나 색인으로 시트를 선택합니다
  • range='A1:D10' — 특정 셀 범위를 읽습니다
  • col_names, skip — 메타데이터 행과 사용자 지정 열 이름을 처리합니다
  • col_types = c('text','numeric','date','skip') — 형식 추론 결과를 재정의합니다
  • n_max=5 — 큰 파일을 미리 봅니다. na=c('N/A','#N/A') — 사용자 지정 NA 문자열을 지정합니다
  • 모든 시트를 처리하려면 map(excel_sheets(path), ~read_excel(path, sheet=.x))와 결합합니다
library(readxl)
library(purrr)

path <- readxl_example('datasets.xlsx')

# Full workflow: discover, select, read
cat('Sheets available:', paste(excel_sheets(path), collapse=', '), '\n\n')

# Read a specific sheet with explicit types
df <- read_excel(
  path,
  sheet = 'iris',
  col_types = c('numeric','numeric','numeric','numeric','text'),
  n_max = 5
)

print(df)

자주 묻는 질문

“readxl로 Excel 파일 가져오기” 강의는 무료인가요?

네 — “readxl로 Excel 파일 가져오기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 R Academy 강의 전체를 잠금 해제할 수 있습니다. R Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“readxl로 Excel 파일 가져오기”에서 뭘 배우나요?

시트 선택과 셀 범위 옵션을 사용하여 .xls 및 .xlsx 시트를 읽습니다. 브라우저에서 직접 실행하는 실습 코드로 R Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

R Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 R Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.

“readxl로 Excel 파일 가져오기” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 R Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 R Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. read_csv()로 CSV 파일 읽기
  2. TSV 및 고정 너비 파일 구문 분석
  3. readxl로 Excel 파일 가져오기
  4. 여러 형식으로 데이터 작성하기
← R Academy(으)로 돌아가기