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

如何基于列名列从多列中可读地生成数据框新列?

问题:根据指定列名提取对应行值并新增列

需求说明

需要在数据框中新增列b,每行的b值为该行a列指定的列(如col1或col2)对应的取值,要求实现代码可读性强,且能适配大量此类“值列”,无需逐个枚举列名。

示例输入

library(tidyverse)

df1 = tibble(a=c("col1","col1","col2"),
            col1=c(1,3,5),
            col2=c(2,4,6))
df1
# ## A tibble: 3 × 3
# #     a   col1  col2
# # <chr>  <dbl> <dbl>
# #1 col1      1     2
# #2 col1      3     4
# #3 col2      5     6

目标输出

b=c(1,3,6)
df2=cbind(df1,b)
df2
#     a col1 col2 b
#1 col1    1    2 1
#2 col1    3    4 3
#3 col2    5    6 6

现有可用但可读性差的方案

for (i in c(1:nrow(df1))) {
  df1$b[i] = df1[[df1$a[i]]][i]
}

df1

失败的简洁写法尝试

  • 运行后将a列内容直接复制到b列:
df3 = mutate(df1, "b" = {{a}})
df3
  • 运行报错:
df3 = mutate(df1, "b" = [[{{a}}]])
df3

Error: unexpected '[[' in "df3 = mutate(df1, "b" = [["

推荐解决方案(tidyverse风格,可读性强)

以下几种方案均无需枚举列名,适配任意数量的“值列”:

方案1:rowwise() + pick()

df1 %>%
  rowwise() %>%
  mutate(b = pick(all_of(a)) %>% pull()) %>%
  ungroup()

方案2:rowwise() + cur_data()

df1 %>%
  rowwise() %>%
  mutate(b = cur_data()[[a]]) %>%
  ungroup()

方案3:purrr::pmap()

df1 %>%
  mutate(b = pmap_dbl(., function(a, ...) {
    data = tibble(...)
    data[[a]]
  }))

内容的提问来源于stack exchange,提问作者Joseph O'Toole

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 21:43:19