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

如何基于命名向量为R数据框新增Label列(tidyverse方案优先)

解决方案(优先使用tidyverse工具)

方法1:用dplyr::mutate + dplyr::recode快速匹配

先构建水果名→标签的反向映射,再通过recode完成列填充:

library(tidyverse)

# 原数据定义
vector <- c("Apple","Banana","Cucumber","Durian")
name <- c("A","B","C","D")
names(vector) <- name

df <- data.frame("Fruit" = c("Banana","Durian","Apple","Cucumber"),
                 "Price" = c("$4.00", "$2.00","$1.50","$1.00"))

# 构建反向映射向量:水果名对应标签
fruit_to_label <- setNames(names(vector), vector)

# 新增Label列
df <- df %>%
  mutate(Label = recode(Fruit, !!!fruit_to_label))

# 输出结果
print(df)

运行后得到目标结果:

Fruit Price Label
1   Banana $4.00     B
2   Durian $2.00     D
3    Apple $1.50     A
4 Cucumber $1.00     C

方法2:用dplyr::left_join直观匹配(适合复杂映射场景)

把向量转成映射表,通过左连接完成标签匹配,可读性更强:

library(tidyverse)

# 原数据定义
vector <- c("Apple","Banana","Cucumber","Durian")
name <- c("A","B","C","D")
names(vector) <- name

df <- data.frame("Fruit" = c("Banana","Durian","Apple","Cucumber"),
                 "Price" = c("$4.00", "$2.00","$1.50","$1.00"))

# 构建映射表
label_mapping <- tibble(Fruit = vector, Label = names(vector))

# 左连接匹配标签
df <- df %>%
  left_join(label_mapping, by = "Fruit")

# 输出结果
print(df)

补充说明

  • 方法1适合简单一对一映射,代码更紧凑;!!!用于解引用映射向量,让recode识别每一组对应关系。
  • 方法2适合需要扩展映射规则的场景,映射表的形式更便于维护和修改。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 02:22:48