R match() 関数 - 要素のマッチング
R match() 関数は、あるベクトルの要素が別のベクトル内で最初に出現する位置を検索するために使用されます。
match() は %in% 演算子に似ていますが、論理値ではなく位置を返します。
match() 関数の構文は次のとおりです:
match(x, table, nomatch = NA_integer_)
引数の説明:
x検索する要素のベクトル。
table検索対象のベクトル。
nomatchマッチング失敗時に返す値。デフォルトは NA。
例
# 要素の位置を検索
fruits <- c("りんご", "バナナ", "みかん", "ぶどう", "スイカ")
wanted <- c("バナナ", "スイカ", "レモン")
# wanted の要素が fruits 内のどの位置にあるか検索
positions <- match(wanted, fruits)
print("マッチング結果:")
print(positions)
# 対応する検索:位置を使って実際の値を取得
print("見つかった果物:")
print(fruits[positions[!is.na(positions)]])
fruits <- c("りんご", "バナナ", "みかん", "ぶどう", "スイカ")
wanted <- c("バナナ", "スイカ", "レモン")
# wanted の要素が fruits 内のどの位置にあるか検索
positions <- match(wanted, fruits)
print("マッチング結果:")
print(positions)
# 対応する検索:位置を使って実際の値を取得
print("見つかった果物:")
print(fruits[positions[!is.na(positions)]])
上記のコードを実行すると、出力結果は次のとおりです:
[1] "匹配结果:" [1] 2 5 NA [1] "找到的水果:" [1] "香蕉" "西瓜"
match() は、あるベクトルに基づいて別のデータを並べ替えるためによく使用されます:
例
# 学生の成績表
student_names <- c("張三", "李四", "王五", "趙六")
scores <- c(88, 92, 76, 85)
names(scores) <- student_names
# 特定の順序で成績を並べる
wanted_order <- c("王五", "趙六", "張三", "李四")
idx <- match(wanted_order, names(scores))
print("指定された順序で並べた成績:")
print(scores[idx])
student_names <- c("張三", "李四", "王五", "趙六")
scores <- c(88, 92, 76, 85)
names(scores) <- student_names
# 特定の順序で成績を並べる
wanted_order <- c("王五", "趙六", "張三", "李四")
idx <- match(wanted_order, names(scores))
print("指定された順序で並べた成績:")
print(scores[idx])
上記のコードを実行すると、出力結果は次のとおりです:
[1] "按指定顺序排列的成绩:" 王五 赵六 张三 李四 76 85 88 92その他の拡張
R 言語の例