0Pricing
R Academy · レッスン

readxlによるExcelファイルの読み込み

シートの選択やセル範囲の指定を行い、.xlsと.xlsxのシートを読み込みます。

「readxlによるExcelファイルの読み込み」はCoddyKit上の無料R Academyレッスンです。 これはレッスン3/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応の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時間対応のAIチューター)、R Academyコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 R Academyコースには全4レッスンが含まれています。

「readxlによるExcelファイルの読み込み」で何を学びますか?

シートの選択やセル範囲の指定を行い、.xlsと.xlsxのシートを読み込みます。 ブラウザで直接実行するハンズオンコードでR Academyを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

R Academyを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのR Academyは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン3/4です。

「readxlによるExcelファイルの読み込み」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このR Academyレッスンでコードを書いて実行できますか?

はい。すべてのR Academyレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. read_csv()によるCSVファイルの読み込み
  2. TSVと固定幅ファイルの解析
  3. readxlによるExcelファイルの読み込み
  4. 複数形式へのデータ出力
← R Academyに戻る