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

在R中实现类似Excel INDEX/MATCH的行列匹配查询方法

在R中实现类似Excel INDEX/MATCH的行列定位查找功能

场景1:通过行号+列号提取查找表的值

先创建示例数据:

# 主数据表
main_df <- data.frame(
  ID = 1:3,
  target_row = c(4, 2, 5),
  target_col = c(1, 3, 2)
)

# 查找表
lookup_df <- data.frame(
  name = c("john", "mike", "sarah", "sam", "kelly"),
  city = c("boston", "new york", "chicago", "los angeles", "dallas"),
  food = c("pizza", "pasta", "hoagie", "sushi", "ice cream")
)

直接用lookup_df[main_df$target_row, main_df$target_col]会返回矩阵而非单个对应值,这是因为R默认会生成行号列号的交叉组合结果。以下是两种可行解决方案:

方法1:矩阵索引

将行号和列号组合成2列矩阵作为索引,直接提取对应位置的值:

main_df$result <- lookup_df[cbind(main_df$target_row, main_df$target_col)]

运行后结果符合预期:

> main_df
  ID target_row target_col    result
1  1          4          1       sam
2  2          2          3      pasta
3  3          5          2     dallas

方法2:mapply逐行处理

通过mapply遍历每一组行号和列号,逐行提取值:

main_df$result <- mapply(function(r, c) lookup_df[r, c], 
                         main_df$target_row, main_df$target_col)

场景2:通过当前行+列名提取查找表的值

创建示例数据:

# 主数据表(目标行为当前行,与查找表行索引一一对应)
main_df2 <- data.frame(
  ID = 1:3,
  target_row = rep("当前行", 3),
  target_col = c("name", "food", "city")
)

# 查找表与场景1一致

方法1:dplyr行分组处理

用rowwise()按行分组,结合cur_group_rows()定位当前行,再通过列名提取:

library(dplyr)

main_df2 <- main_df2 %>%
  rowwise() %>%
  mutate(result = lookup_df[cur_group_rows(), target_col]) %>%
  ungroup()

方法2:列名转列号+矩阵索引

先将列名转换为对应列号,再用矩阵索引提取:

col_indices <- match(main_df2$target_col, colnames(lookup_df))
main_df2$result <- lookup_df[cbind(1:nrow(main_df2), col_indices)]

方法3:purrr逐行映射

用map2_chr(字符型返回)遍历行索引和列名:

library(purrr)

main_df2$result <- map2_chr(1:nrow(main_df2), main_df2$target_col, 
                            ~ lookup_df[.x, .y])

运行后结果:

> main_df2
  ID target_row target_col  result
1  1    当前行       name    john
2  2    当前行       food    pasta
3  3    当前行       city   chicago

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 13:35:31