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 语言实例