R语言如何匹配number列值与列名新增列提取对应单元格值
解决方案
你可以通过行+列匹配定位的方式实现需求,不需要使用字符串提取类函数,以下两种常用实现方式都可以达到效果:
方法1:基础R实现(运行效率最高)
通过矩阵索引直接定位每行要取的单元格:
# 构造示例数据 df <- structure(list(number = 1:3, a_1 = c(1L, 4L, 7L), a_2 = c(2L, 5L, 8L), a_3 = c(3L, 6L, 9L)), class = "data.frame", row.names = c(NA, -3L)) # 新增new_col列 df$new_col <- df[cbind(seq_len(nrow(df)), df$number + 1)]
说明:这里
df$number +1是因为你的a_1/a_2/a_3刚好是第2/3/4列,和number值差1,如果列序不固定可以替换为match(paste0("a_", df$number), colnames(df))动态匹配列位置。
方法2:tidyverse 行级运算实现
如果你习惯用dplyr语法,可以用行级运算动态获取对应列的值:
library(dplyr) df <- df %>% rowwise() %>% mutate(new_col = get(paste0("a_", number))) %>% ungroup()
两种方法运行后得到的结果都符合你的预期:
number a_1 a_2 a_3 new_col 1 1 1 2 3 1 2 2 4 5 6 5 3 3 7 8 9 9
内容的提问来源于stack exchange,提问作者TarJae
相关产品推荐
相关产品推荐

