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

如何在R的mutate中传递条目(分组条目)至函数实现数据分类?

问题:为目标表匹配对应类别并生成新列

我正在编写代码,需要将目标表中的条目与代码表对比,确定每个条目所属的类别。

代码表示例

df_code <- data.frame("Colour" = c("Blue", "Red", "Yellow"), "Shape" = c("Triangle", "Circle", "Square"),  "Letter" = c("Alpha", "Beta", "Charlie"))

该表的列标题为类别名称,各列中的取值对应目标表中需归为该类别的条目。

目标表示例

df_target <- data.frame("ID" = c(1:3), "Label" = c("Red", "Triangle", "Beta"))

已定义的匹配函数

findInCategory <- function (code = df_code, entry) {
  entry.location <- which(code == entry, arr.ind = T)
  category <- colnames(code)[entry.location[2]]
  return(category)
}

我需要结合dplyr的group_by(Label)和mutate()函数,为df_target创建Category列,为每一行分配对应的类别。请问如何在以下代码的mutate中传递当前条目到函数:

df_target_mutated <- df_target %>% mutate(metacategory = findInCategory(code, **An argument here**))

期望结果

ID    Label Category
1  1      Red   Colour
2  2 Triangle    Shape
3  3     Beta   Letter

解决方案

你不需要使用group_by(Label),因为每个Label都是独立条目,直接逐行调用函数即可,这里提供两种高效实现方式:

方式一:使用purrr::map_chr(推荐)

借助purrr的map_chr函数遍历Label列的每个元素,将其作为参数传入findInCategory,返回字符向量作为新列:

library(dplyr)
library(purrr)

df_target_mutated <- df_target %>%
  mutate(Category = map_chr(Label, ~findInCategory(entry = .x)))

方式二:使用rowwise()

如果不想引入purrr包,可以用rowwise()让dplyr按行处理,此时mutate中调用函数时会自动取当前行的Label值:

library(dplyr)

df_target_mutated <- df_target %>%
  rowwise() %>%
  mutate(Category = findInCategory(entry = Label)) %>%
  ungroup()

补充说明

  • 原函数中code参数默认值为df_code,如果当前环境中存在该对象,调用时可以省略这个参数;若需明确指定,可写成findInCategory(code = df_code, entry = .x)。
  • 两种方式运行后都能得到你期望的df_target_mutated结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 17:57:28