r-style-guide
Rのコーディング規約に沿って、変数名やスペース、レイアウト、関数の設計など、Rコードを書く際のベストプラクティスを適用し、読みやすく保守しやすいコードを作成するSkill。
📜 元の英語説明(参考)
R style guide covering naming conventions, spacing, layout, and function design best practices. Use when writing R code.
🇯🇵 日本人クリエイター向け解説
Rのコーディング規約に沿って、変数名やスペース、レイアウト、関数の設計など、Rコードを書く際のベストプラクティスを適用し、読みやすく保守しやすいコードを作成するSkill。
※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。
下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o r-style-guide.zip https://jpskill.com/download/8789.zip && unzip -o r-style-guide.zip && rm r-style-guide.zip
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/8789.zip -OutFile "$d\r-style-guide.zip"; Expand-Archive "$d\r-style-guide.zip" -DestinationPath $d -Force; ri "$d\r-style-guide.zip"
完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。
💾 手動でダウンロードしたい(コマンドが難しい人向け)
- 1. 下の青いボタンを押して
r-style-guide.zipをダウンロード - 2. ZIPファイルをダブルクリックで解凍 →
r-style-guideフォルダができる - 3. そのフォルダを
C:\Users\あなたの名前\.claude\skills\(Win)または~/.claude/skills/(Mac)へ移動 - 4. Claude Code を再起動
⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。
🎯 このSkillでできること
下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。
📦 インストール方法 (3ステップ)
- 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
- 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
- 3. 展開してできたフォルダを、ホームフォルダの
.claude/skills/に置く- · macOS / Linux:
~/.claude/skills/ - · Windows:
%USERPROFILE%\.claude\skills\
- · macOS / Linux:
Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。
詳しい使い方ガイドを見る →- 最終更新
- 2026-05-18
- 取得日時
- 2026-05-18
- 同梱ファイル
- 1
📖 Skill本文(日本語訳)
※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。
R スタイルガイドと関数作成のベストプラクティス
R コードの一貫性のある命名、スペーシング、構造、および関数設計
関数作成のベストプラクティス
構造とスタイル
# 良い関数構造
rescale01 <- function(x) {
rng <- range(x, na.rm = TRUE, finite = TRUE)
(x - rng[1]) / (rng[2] - rng[1])
}
# 型が安定した出力を使用する
map_dbl() # 数値ベクトルを返す
map_chr() # 文字ベクトルを返す
map_lgl() # 論理ベクトルを返す
命名と引数
# 良い命名: 変数/関数には snake_case を使用する
calculate_mean_score <- function(data, score_col) {
# 関数の本体
}
# 標準でない引数には . をプレフィックスとして付ける
my_function <- function(.data, ...) {
# 引数の衝突を減らす
}
スタイルガイドの要点
オブジェクト名
- すべての名前に snake_case を使用する
- 変数名 = 名詞、関数名 = 動詞
- S3 メソッドを除き、ドットは避ける
# 良い例
day_one
calculate_mean
user_data
# 避けるべき例
DayOne
calculate.mean
userData
スペーシングとレイアウト
# 良いスペーシング
x[, 1]
mean(x, na.rm = TRUE)
if (condition) {
action()
}
# パイプのフォーマット
data |>
filter(year >= 2020) |>
group_by(category) |>
summarise(
mean_value = mean(value),
count = n()
)
代入
# 良い例 - 代入には <- を使用する
x <- 5
# 避けるべき例 - 代入に = を使用する (関数引数にのみ使用する)
x = 5 # 意図が不明確
インデントと行の長さ
- インデントには 2 つのスペースを使用する (タブは絶対に使用しない)
- 可能であれば、行を 80 文字未満に保つ
- 長い関数呼び出しの場合は、各引数を独自の行に配置する
# 良い例 - 長い関数呼び出し
do_something_complicated(
data = my_data,
arg_one = value_one,
arg_two = value_two,
arg_three = value_three
)
# 良い例 - 長いパイプチェーン
result <- data |>
filter(year >= 2020) |>
mutate(
new_var = old_var * 2,
another_var = str_to_lower(text_var)
) |>
summarise(
mean_value = mean(value),
.by = category
)
コメント
# 良い例 - コメントは WHAT ではなく WHY を説明する
# センサーデータのノイズを平滑化するために移動平均を計算する
running_avg <- zoo::rollmean(values, k = 5)
# 避けるべき例 - コードを繰り返すだけのコメント
# x に 1 を加算する
x <- x + 1
ファイル構成
# 1. パッケージを先頭にロードする
library(dplyr)
library(ggplot2)
# 2. ヘルパーファイルを読み込む
source("R/helpers.R")
# 3. 定数を定義する
MAX_ITERATIONS <- 1000
DEFAULT_THRESHOLD <- 0.05
# 4. 関数を定義する
process_data <- function(data) {
# ...
}
# 5. メインスクリプトのロジック (パッケージではない場合)
main <- function() {
data <- read_csv("data/input.csv")
result <- process_data(data)
write_csv(result, "data/output.csv")
}
関数設計のガイドライン
単一責任
# 良い例 - 各関数は 1 つのことを行う
read_and_validate <- function(path) {
data <- read_csv(path)
validate_columns(data)
data
}
validate_columns <- function(data) {
required <- c("id", "value", "date")
missing <- setdiff(required, names(data))
if (length(missing) > 0) {
stop("Missing columns: ", paste(missing, collapse = ", "))
}
}
# 避けるべき例 - 関数が多くのことを行う
do_everything <- function(path, output_path, ...) {
# 読み込み、検証、変換、モデル化、プロット、書き込み...
}
戻り値
# 良い例 - 複雑な関数には明示的な return を使用する
calculate_metrics <- function(data) {
metrics <- list(
mean = mean(data$value),
sd = sd(data$value),
n = nrow(data)
)
return(metrics)
}
# 良い例 - 単純な関数には暗黙的な return を使用する
square <- function(x) {
x^2
}
# 避けるべき例 - 正当な理由なく途中で return する
process <- function(x) {
if (is.null(x)) return(NULL) # OK - 早期終了
# ... より多くのコード
result # 最後に暗黙的な return
}
エラー処理
# 良い例 - 有益なエラーメッセージ
validate_input <- function(x, name = "x") {
if (!is.numeric(x)) {
stop("`", name, "` must be numeric, not ", typeof(x), call. = FALSE)
}
if (length(x) == 0) {
stop("`", name, "` cannot be empty", call. = FALSE)
}
}
# 良い例 - ユーザーフレンドリーなメッセージには cli を使用する
validate_input_cli <- function(x) {
if (!is.numeric(x)) {
cli::cli_abort(
"{.arg x} must be numeric, not {.cls {class(x)}}."
)
}
}
デフォルト引数
# 良い例 - 適切なデフォルト値
summarise_data <- function(data, na.rm = TRUE, digits = 2) {
# ...
}
# 良い例 - オプションの引数には NULL のデフォルト値を使用する
filter_data <- function(data, min_value = NULL, max_value = NULL) {
if (!is.null(min_value)) {
data <- filter(data, value >= min_value)
}
if (!is.null(max_value)) {
data <- filter(data, value <= max_value)
}
data
}
Tidyverse API の規約
データファーストの引数
# 良い例 - パイプ処理のためにデータを最初の引数にする
my_transform <- function(data, var, threshold = 0.5) {
data |>
filter({{ var }} > threshold)
}
# 使用例
data |> my_transform(value, threshold = 0.8)
プレフィックス付きの非標準引数
# 良い例 - 競合を避けるために . をプレフィックスとして付ける
group_summary <- function(.data, ..., .by = NULL) {
.data |>
summarise(..., .by = {{ .by }})
}
一貫した戻り値の型
# 良い例 - 常に tibble を返す
my_function <- function(data) {
result <- data |>
# 処理...
filter(!is.na(value))
tibble::as_tibble(result)
}
よくあるスタイルの間違い
これらのパターンは避ける
# 避けるべき例 - 一貫性のないスペーシング
x<-1+2 # スペースなし
x <- 1 + 2 # 正しい
# 避けるべき例 - 不要な括弧
if ((x > 0)) {} # 余分な括弧
if (x > 0) {} # 正しい
# 避けるべき例 - TRUE/FALSE の代わりに T/F を使用する
if (x == T) {} # T は上書きされる可能性がある
if (x == TRUE) {} # 正しい
# 避けるべき例 - セミコロンでステートメントを区切る
x <- 1; y <- 2 # 読みにくい
x <- 1 # 正しい
y <- 2
# 避けるべき例 - attach() - 曖昧さを生み出す
attach(mtcars)
mean(mpg) # どの mpg?
detach(mtcars)
# 正しい例 - 明示的にする
mean(mtcars$mpg)
# または
with(mtcars, mean(mpg))
# または
mtcars |> pull(mpg) |> mean() 📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開
R Style Guide & Function Writing Best Practices
Consistent naming, spacing, structure, and function design for R code
Function Writing Best Practices
Structure and Style
# Good function structure
rescale01 <- function(x) {
rng <- range(x, na.rm = TRUE, finite = TRUE)
(x - rng[1]) / (rng[2] - rng[1])
}
# Use type-stable outputs
map_dbl() # returns numeric vector
map_chr() # returns character vector
map_lgl() # returns logical vector
Naming and Arguments
# Good naming: snake_case for variables/functions
calculate_mean_score <- function(data, score_col) {
# Function body
}
# Prefix non-standard arguments with .
my_function <- function(.data, ...) {
# Reduces argument conflicts
}
Style Guide Essentials
Object Names
- Use snake_case for all names
- Variable names = nouns, function names = verbs
- Avoid dots except for S3 methods
# Good
day_one
calculate_mean
user_data
# Avoid
DayOne
calculate.mean
userData
Spacing and Layout
# Good spacing
x[, 1]
mean(x, na.rm = TRUE)
if (condition) {
action()
}
# Pipe formatting
data |>
filter(year >= 2020) |>
group_by(category) |>
summarise(
mean_value = mean(value),
count = n()
)
Assignment
# Good - Use <- for assignment
x <- 5
# Avoid - = for assignment (use only for function arguments)
x = 5 # Less clear intent
Indentation and Line Length
- Use 2 spaces for indentation (never tabs)
- Keep lines under 80 characters when possible
- For long function calls, put each argument on its own line
# Good - Long function call
do_something_complicated(
data = my_data,
arg_one = value_one,
arg_two = value_two,
arg_three = value_three
)
# Good - Long pipe chain
result <- data |>
filter(year >= 2020) |>
mutate(
new_var = old_var * 2,
another_var = str_to_lower(text_var)
) |>
summarise(
mean_value = mean(value),
.by = category
)
Comments
# Good - Comments explain WHY, not WHAT
# Calculate running average to smooth noise in sensor data
running_avg <- zoo::rollmean(values, k = 5)
# Avoid - Comments that just repeat the code
# Add 1 to x
x <- x + 1
File Organization
# 1. Load packages at the top
library(dplyr)
library(ggplot2)
# 2. Source any helper files
source("R/helpers.R")
# 3. Define constants
MAX_ITERATIONS <- 1000
DEFAULT_THRESHOLD <- 0.05
# 4. Define functions
process_data <- function(data) {
# ...
}
# 5. Main script logic (if not a package)
main <- function() {
data <- read_csv("data/input.csv")
result <- process_data(data)
write_csv(result, "data/output.csv")
}
Function Design Guidelines
Single Responsibility
# Good - Each function does one thing
read_and_validate <- function(path) {
data <- read_csv(path)
validate_columns(data)
data
}
validate_columns <- function(data) {
required <- c("id", "value", "date")
missing <- setdiff(required, names(data))
if (length(missing) > 0) {
stop("Missing columns: ", paste(missing, collapse = ", "))
}
}
# Avoid - Function does too many things
do_everything <- function(path, output_path, ...) {
# Reads, validates, transforms, models, plots, writes...
}
Return Values
# Good - Explicit return for complex functions
calculate_metrics <- function(data) {
metrics <- list(
mean = mean(data$value),
sd = sd(data$value),
n = nrow(data)
)
return(metrics)
}
# Good - Implicit return for simple functions
square <- function(x) {
x^2
}
# Avoid - Return in the middle without good reason
process <- function(x) {
if (is.null(x)) return(NULL) # OK - early exit
# ... more code
result # Implicit return at end
}
Error Handling
# Good - Informative error messages
validate_input <- function(x, name = "x") {
if (!is.numeric(x)) {
stop("`", name, "` must be numeric, not ", typeof(x), call. = FALSE)
}
if (length(x) == 0) {
stop("`", name, "` cannot be empty", call. = FALSE)
}
}
# Good - Use cli for user-friendly messages
validate_input_cli <- function(x) {
if (!is.numeric(x)) {
cli::cli_abort(
"{.arg x} must be numeric, not {.cls {class(x)}}."
)
}
}
Default Arguments
# Good - Sensible defaults
summarise_data <- function(data, na.rm = TRUE, digits = 2) {
# ...
}
# Good - NULL default for optional arguments
filter_data <- function(data, min_value = NULL, max_value = NULL) {
if (!is.null(min_value)) {
data <- filter(data, value >= min_value)
}
if (!is.null(max_value)) {
data <- filter(data, value <= max_value)
}
data
}
Tidyverse API Conventions
Data-First Argument
# Good - Data as first argument for piping
my_transform <- function(data, var, threshold = 0.5) {
data |>
filter({{ var }} > threshold)
}
# Usage
data |> my_transform(value, threshold = 0.8)
Prefixed Non-Standard Arguments
# Good - Prefix with . to avoid conflicts
group_summary <- function(.data, ..., .by = NULL) {
.data |>
summarise(..., .by = {{ .by }})
}
Consistent Return Types
# Good - Always return tibble
my_function <- function(data) {
result <- data |>
# processing...
filter(!is.na(value))
tibble::as_tibble(result)
}
Common Style Mistakes
Avoid These Patterns
# Avoid - Inconsistent spacing
x<-1+2 # No spaces
x <- 1 + 2 # Correct
# Avoid - Unnecessary parentheses
if ((x > 0)) {} # Extra parens
if (x > 0) {} # Correct
# Avoid - Using T/F instead of TRUE/FALSE
if (x == T) {} # T can be overwritten
if (x == TRUE) {} # Correct
# Avoid - Semicolons to separate statements
x <- 1; y <- 2 # Hard to read
x <- 1 # Correct
y <- 2
# Avoid - attach() - creates ambiguity
attach(mtcars)
mean(mpg) # Which mpg?
detach(mtcars)
# Correct - Be explicit
mean(mtcars$mpg)
# or
with(mtcars, mean(mpg))
# or
mtcars |> pull(mpg) |> mean()