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

如何在R语言中编写函数将分类变量多水平合并为两类

将多分类变量合并为二分类的R函数实现

单个列的快速处理

如果仅需处理单个列(比如示例中的column1),用base R的ifelse()就能快速实现需求:

# 给数据框新增二分类列
df$column1_binary <- ifelse(df$column1 == "bad", "bad", "others")

# 验证处理结果
table(df$column1_binary)

执行后,column1_binary列会保留所有"bad"值,其余水平统一转为"others"。

通用函数(支持多列批量处理)

如果需要批量处理多个分类变量,可以编写一个通用函数,灵活指定每列要保留的水平:

collapse_to_binary <- function(data, cols, keep_values) {
  # 遍历每个目标列
  for (col in cols) {
    new_col <- paste0(col, "_binary")
    # 保留指定值,其余统一转为"others"
    data[[new_col]] <- ifelse(data[[col]] %in% keep_values[[col]], data[[col]], "others")
    # 转为因子类型(可选,适合后续统计分析场景)
    data[[new_col]] <- factor(data[[new_col]], levels = c(unique(keep_values[[col]]), "others"))
  }
  return(data)
}

函数使用示例

针对你的示例数据,处理column1的操作如下:

# 指定要处理的列和对应保留值
target_cols <- c("column1")
keep_vals <- list(column1 = "bad")

# 应用函数得到处理后的数据框
df_processed <- collapse_to_binary(df, target_cols, keep_vals)

# 查看处理结果
table(df_processed$column1_binary)

如果需要处理多列(比如column2要保留"john"和"ben"),只需调整参数即可:

target_cols <- c("column1", "column2")
keep_vals <- list(column1 = "bad", column2 = c("john", "ben"))

df_processed <- collapse_to_binary(df, target_cols, keep_vals)

Tidyverse风格实现(dplyr)

若习惯使用tidyverse工具链,用dplyr::across()可以更简洁地完成批量处理:

library(dplyr)

collapse_to_binary_dplyr <- function(data, cols, keep_values) {
  data %>%
    mutate(across(all_of(cols), ~ case_when(
      .x %in% keep_values[[cur_column()]] ~ .x,
      TRUE ~ "others"
    ), .names = "{col}_binary"))
}

# 使用方式与base R版本一致
df_processed_dplyr <- collapse_to_binary_dplyr(df, target_cols, keep_vals)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 22:55:28