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

如何创建R自定义函数匹配编码与主列表并自动生成分类统计列

完全可以通过自定义函数实现,不需要逐行编写重复的ifelse语句。

前置处理注意事项

首先需要确保你的主分类列表code_list是命名列表,列表的元素名就是最终生成的分类列名,示例如下:

code_list <- list(
  category_1 = c("101", "102"),
  category_2 = c("201", "202", "203")
)
# 如果不想修改原有code_list的定义,也可以手动批量命名
# names(code_list) <- paste0("category_", seq_along(code_list))

自定义函数实现

以下函数完整覆盖你提出的三项需求:

library(dplyr)
library(purrr)

match_code_category <- function(df, code_list, 
                                code_col = "code", 
                                value_col = "expend",
                                # 二分类校验相关可选参数
                                check_binary = FALSE,
                                binary_col = "bin",
                                binary_positive = "1") {
  # 1. 批量生成基础分类列
  category_cols <- imap_dfc(code_list, function(codes, col_name) {
    ifelse(df[[code_col]] %in% codes, df[[value_col]], 0)
  })
  res <- bind_cols(df, category_cols)
  
  # 2. 按需生成二分类校验列
  if (check_binary) {
    valid_cols <- imap_dfc(code_list, function(codes, col_name) {
      ifelse(df[[code_col]] %in% codes & df[[binary_col]] == binary_positive, df[[value_col]], 0)
    }) %>% rename_with(~paste0(.x, "_valid"))
    res <- bind_cols(res, valid_cols)
  }
  return(res)
}

调用示例

# 仅生成基础分类列,对应需求1、2
result <- match_code_category(table, code_list)

# 同时生成校验列,对应需求3
result_with_check <- match_code_category(table, code_list, check_binary = TRUE)

调用后输出结果和你给出的期望格式完全一致。

相关学习参考方向

  • purrr包批量迭代逻辑,重点掌握map系列、imap函数的用法
  • dplyr包批量列操作语法,包括across、mutate结合列表生成新列的规则
  • R自定义函数基础编写规范,包括可选参数设置、条件分支逻辑的实现

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 06:15:06