値の繰り返しのためのrep()
rep()とtimes、each引数を使って値やベクトルを繰り返します。
「値の繰り返しのためのrep()」はCoddyKit上の無料R Academyレッスンです。 これはレッスン3/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはR Academy学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 R Academyコースには全4レッスンが含まれています。
rep() の概要
rep() は replicate の略です。値やベクトルを指定した回数だけ繰り返します。構造化されたテストデータやバランスの取れたデータセットを作成したり、ベクトルをデフォルト値で埋めたりする際に、非常に便利なツールです。
# Repeat a single value
zeros <- rep(0, times = 5)
cat('Five zeros:', zeros, '
')
# Repeat a string
status <- rep('active', times = 4)
cat('Status:', status, '
')rep(x, times) — ベクトル全体を繰り返す
x がベクトルで、times が単一の整数の場合、rep() はベクトル全体をその回数だけ繰り返します。出力の長さは length(x) * times です。
# Repeat a vector 3 times
weekend <- c('Saturday', 'Sunday')
four_weekends <- rep(weekend, times = 4)
cat('4 weekends:', four_weekends, '
')
# Repeat numeric vector
pattern <- c(1, 2, 3)
cat('Pattern x3:', rep(pattern, times = 3), '
')rep(x, each) — 各要素を繰り返す
each 引数は、次の要素に進む前に個々の要素をそれぞれ繰り返します。これは times との重要な違いです。each は各要素をその位置で繰り返します。
groups <- c('A', 'B', 'C')
# times: repeats whole vector
cat('times=3:', rep(groups, times = 3), '
')
# A B C A B C A B C
# each: repeats each element before next
cat('each=3 :', rep(groups, each = 3), '
')
# A A A B B B C C Crep(x, times = c(...)) — 要素ごとに異なる回数で繰り返す
times が x と同じ長さのベクトルの場合、x の各要素は、対応する回数だけ繰り返されます。これにより、繰り返しを細かく制御できます。
# Different number of repeats per element
fruits <- c('apple', 'banana', 'cherry')
counts <- c(3, 1, 2)
fruit_basket <- rep(fruits, times = counts)
cat('Fruit basket:', fruit_basket, '
')
# apple apple apple banana cherry cherry
# Useful for creating category labels
cat('Length:', length(fruit_basket), '
')rep_len() — 固定長まで繰り返す
rep_len(x, length.out) は、結果が length.out 要素にちょうど達するまでベクトル x を繰り返します。繰り返しは循環的に行われ、必要に応じてベクトルの先頭に戻ります。
# Cycle through seasons to fill 12 months
seasons <- c('Spring', 'Summer', 'Autumn', 'Winter')
year_seasons <- rep_len(seasons, length.out = 12)
cat('12 months by season:', year_seasons, '
')
# Cycle through 1, 2, 3 for 10 items
rotation <- rep_len(1:3, length.out = 10)
cat('Rotation:', rotation, '
')times と each の組み合わせ
times と each を組み合わせて、より複雑な繰り返しパターンを作成できます。R はまず each を適用して各要素を展開し、その後、結果のベクトルを times 回繰り返します。
# each=2 then times=3
vals <- c(1, 2)
result <- rep(vals, each = 2, times = 3)
cat('each=2, times=3:', result, '
')
# 1 1 2 2 repeated 3 times: 1 1 2 2 1 1 2 2 1 1 2 2
cat('Length:', length(result), '
')バランスの取れたグループラベルの作成
rep() の典型的な用途は、実験用のバランスの取れたグループラベルを作成することです。これは、各グループの観測値の個数を等しくしたい場合に使用します。
# 5 subjects per treatment group
treatments <- c('Control', 'LowDose', 'HighDose')
n_per_group <- 5
group_labels <- rep(treatments, each = n_per_group)
cat('Group labels:', group_labels, '
')
cat('Total subjects:', length(group_labels), '
')
# Count per group
for (g in treatments) {
cat(g, ':', sum(group_labels == g), '
')
}論理値の繰り返し
rep() は論理値を含むあらゆるデータ型で使用できます。マスク、フラグ、または TRUE/FALSE の交互パターンを作成する際に便利です。
# Alternating TRUE/FALSE pattern
alternate <- rep(c(TRUE, FALSE), times = 5)
cat('Alternating mask:', alternate, '
')
# Apply mask to select every other element
data_vals <- 10:19
cat('Every other value:', data_vals[alternate], '
')
# Create a block pattern: 3 TRUE then 3 FALSE
block <- rep(c(TRUE, FALSE), each = 3)
cat('Block pattern:', block, '
')行列への rep() による値の入力
rep() を使用すると、パターンのあるデータを行列にすばやく入力できます。matrix() は入力としてベクトルを受け取るため、rep() と組み合わせることで、パターン行列を簡単に作成できます。
# Fill a 3x4 matrix with a repeating pattern
pattern <- rep(c(1, 0), times = 6)
checker <- matrix(pattern, nrow = 3, ncol = 4)
cat('Checkerboard-like matrix:
')
print(checker)
# Fill diagonal-like with rep
fill <- rep(1:4, each = 3)
cat('Repeated fill:', fill, '
')集計表の展開
可変の times と rep() を組み合わせる実用的な用途として、度数表を元のデータベクトルに戻す方法があります。各値が何回出現したかが分かっていれば、rep() で観測値を再構成できます。
# Summary: grade frequencies
grades <- c('A', 'B', 'C', 'D')
frequencies <- c(5, 12, 8, 3)
# Reconstruct raw grade vector
raw_grades <- rep(grades, times = frequencies)
cat('Raw grades (', length(raw_grades), 'students):', raw_grades, '
')
# Verify frequency table
cat('Freq table:
')
print(table(raw_grades))rep() のまとめ
rep() のクイックリファレンスを示します。
rep(x, times = n)— x 全体を n 回繰り返すrep(x, each = n)— 各要素を n 回繰り返すrep(x, times = c(...))— 要素ごとに異なる回数で繰り返すrep_len(x, n)— x を循環させて n 要素ちょうどにする- numeric、character、logical、factor など、あらゆる型で使用できる
x <- c(10, 20, 30)
cat('times=2 :', rep(x, times = 2), '
')
cat('each=2 :', rep(x, each = 2), '
')
cat('var times:', rep(x, times = c(1, 2, 3)), '
')
cat('rep_len :', rep_len(x, 7), '
')クイックチェック
rep(c(1, 2), each = 3) は何を生成しますか?
復習:値の繰り返しに rep() を使用する
すばらしいです。このレッスンの重要なポイントをまとめます。
rep(x, times)はベクトル全体を繰り返し、rep(x, each)は各要素を個別に繰り返すtimesにベクトルを渡すと、要素ごとに異なる回数で繰り返せるrep_len(x, n)は x を循環させて、n 要素をちょうど生成する- 一般的な用途:バランスの取れたグループラベル、マスク、度数表の展開、パターン行列
- numeric、character、logical のデータ型で同じように使用できる
# Create a balanced experiment design
treatments <- c('Placebo', 'Drug_A', 'Drug_B')
subjects_per <- 4
design <- rep(treatments, each = subjects_per)
cat('Experiment design:
')
cat(design, '
')
cat('Total N:', length(design), '
')よくある質問
「値の繰り返しのためのrep()」レッスンは無料ですか?
はい。「値の繰り返しのためのrep()」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、R Academyコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 R Academyコースには全4レッスンが含まれています。
「値の繰り返しのためのrep()」で何を学びますか?
rep()とtimes、each引数を使って値やベクトルを繰り返します。 ブラウザで直接実行するハンズオンコードでR Academyを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
R Academyを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのR Academyは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン3/4です。
「値の繰り返しのためのrep()」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このR Academyレッスンでコードを書いて実行できますか?
はい。すべてのR Academyレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- 整数範囲のためのコロン演算子
- カスタムシーケンスのためのseq()
- 値の繰り返しのためのrep()
- 名前付きベクトルと名前付きシーケンス