You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R语言中按条件提取矩阵每行目标值并生成结果列

解决方案

你可以用R语言的apply()函数逐行处理矩阵,结合简单的条件判断实现需求,具体代码如下:

# 定义矩阵和向量
A <- matrix(1:20, nrow = 5, ncol = 4, byrow = TRUE)
B <- c(1,4,11,14,15,20)

# 把矩阵转为数据框
df <- as.data.frame(A)

# 写一个处理单行的函数
get_row_result <- function(row) {
  # 提取当前行里在B中的所有元素
  matched_vals <- row[row %in% B]
  if (length(matched_vals) > 0) {
    # 有匹配就取第一个
    return(matched_vals[1])
  } else {
    # 没匹配就取该行第一列的值
    return(row[1])
  }
}

# 给数据框添加result列
df$result <- apply(df, 1, get_row_result)

# 查看最终结果
print(df)

代码说明

  • row %in% B:判断当前行每个元素是否在向量B里,返回布尔值组成的向量
  • matched_vals <- row[row %in% B]:筛选出当前行所有和B匹配的元素
  • 根据匹配元素的长度判断:有匹配就取第一个,无匹配则取该行第一列的值
  • apply(df, 1, get_row_result):对数据框的每一行(参数1代表按行处理)应用上面的函数

运行后会得到你想要的结果:

V1 V2 V3 V4 result
1  1  2  3  4      1
2  5  6  7  8      5
3  9 10 11 12     11
4 13 14 15 16     14
5 17 18 19 20     20

如果喜欢更简洁的写法,也可以用sapply结合ifelse实现,逻辑完全一致:

df$result <- sapply(1:nrow(df), function(i) {
  current_row <- df[i, ]
  first_match <- current_row[current_row %in% B][1]
  ifelse(is.na(first_match), current_row[1], first_match)
})

内容的提问来源于stack exchange,提问作者user3354212

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 03:52:17