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

基于列值的行操作创建变量:匹配code与type列对的迭代实现

解决方案

步骤1:批量匹配code与type列对

首先提取所有code_*和对应的type_*列,无需手动指定每一组:

# 获取所有code列及对应后缀
code_cols <- grep("^code_", names(df), value = TRUE)
suffixes <- sub("^code_", "", code_cols)
type_cols <- paste0("type_", suffixes)

步骤2:实现规则逻辑(Base R版本)

编写行处理函数,按优先级应用规则:

compute_new_var <- function(row, code_cols, type_cols) {
  has_B_yes <- FALSE
  has_A_yes <- FALSE
  has_C_yes <- FALSE
  all_B_no <- TRUE # 修正原规则3的矛盾条件,改为检查所有type=B的code都是no

  for (i in seq_along(code_cols)) {
    code_val <- row[code_cols[i]]
    type_val <- row[type_cols[i]]
    
    if (code_val == "yes" && type_val == "B") has_B_yes <- TRUE
    if (code_val == "yes" && type_val == "A") has_A_yes <- TRUE
    if (code_val == "yes" && type_val == "C") has_C_yes <- TRUE
    if (type_val == "B" && code_val == "yes") all_B_no <- FALSE
  }

  # 按规则优先级赋值
  if (has_B_yes) {
    return("0")
  } else if (has_A_yes) {
    return("1")
  } else if (all_B_no && has_C_yes) {
    return("1")
  } else {
    return(NA) # 其他情况可根据需求修改
  }
}

# 应用到所有行
df$new_var <- apply(df, 1, compute_new_var, code_cols = code_cols, type_cols = type_cols)

步骤3:实现规则逻辑(dplyr + purrr版本,更高效)

如果习惯tidyverse语法,可使用以下方式:

library(dplyr)
library(purrr)

# 配对code和type列
col_pairs <- map2(code_cols, type_cols, ~list(code = .x, type = .y))

df <- df %>%
  rowwise() %>%
  mutate(
    # 检查各条件
    has_B_yes = any(map_lgl(col_pairs, ~get(.x$code) == "yes" && get(.x$type) == "B")),
    has_A_yes = any(map_lgl(col_pairs, ~get(.x$code) == "yes" && get(.x$type) == "A")),
    has_C_yes = any(map_lgl(col_pairs, ~get(.x$code) == "yes" && get(.x$type) == "C")),
    all_B_no = all(map_lgl(col_pairs, ~!(get(.x$type) == "B") || get(.x$code) == "no")),
    # 按优先级生成new_var
    new_var = case_when(
      has_B_yes ~ "0",
      has_A_yes ~ "1",
      all_B_no && has_C_yes ~ "1",
      TRUE ~ NA_character_
    )
  ) %>%
  ungroup() %>%
  select(-has_B_yes, -has_A_yes, -has_C_yes, -all_B_no) # 清理中间变量

关于规则3的说明

原规则3的描述存在逻辑矛盾:"所有对应type_为B或C的code_均为no"与"存在code_=yes且type_=C"无法同时成立。上述代码已将其修正为"所有type_为B的code_均为no,且存在code_=yes且type_=C",若实际需求不同,可直接修改all_B_no的判断逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 03:24:54