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

在R语言中将布尔列映射为非固定列的实现方法

在R语言中实现布尔列到多条件列的映射

原始数据

数据表格

idreason1reason2reason3reason4
10110
20001
30001

生成原始数据的R代码

df <- data.frame(
  id = c(1, 2, 3),
  reason1 = c(0, 0, 0),
  reason2 = c(1, 0, 0),
  reason3 = c(1, 0, 0),
  reason4 = c(0, 1, 1)
)

映射规则

  • reason1 值为1时对应 Rain
  • reason2 值为1时对应 Wind
  • reason3 值为1时对应 Thunder
  • reason4 值为1时对应 None

目标结果

目标数据表格

idconditioncondition2condition3condition4
1WindThunderNANA
2NoneNANANA
3NoneNANANA

目标数据的R代码示例

df_new <- data.frame(
  id = c(1, 2, 3),
  condition = c('Wind', 'None', 'None'),
  condition2 = c('Thunder', NA, NA),
  condition3 = c(NA, NA, NA),
  condition4 = c(NA, NA, NA),
  stringsAsFactors = FALSE
)

实现方法

方法一:Base R 实现

# 定义映射关系
reason_map <- c(
  reason1 = "Rain",
  reason2 = "Wind",
  reason3 = "Thunder",
  reason4 = "None"
)

# 提取reason列,替换为对应标签
reason_cols <- df[, grep("reason", names(df))]
label_matrix <- matrix(reason_map[col(reason_cols)], nrow = nrow(reason_cols))
label_matrix[reason_cols == 0] <- NA

# 按行整理非NA值,填充到新列
condition_list <- apply(label_matrix, 1, function(x) {
  non_na <- x[!is.na(x)]
  length(non_na) <- 4  # 对应4个condition列
  non_na
})

# 转置并合并到原始id列
df_result <- cbind(df["id"], t(condition_list))
names(df_result)[-1] <- paste0("condition", 1:4)

# 查看结果
df_result

方法二:Tidyverse 工具包实现

先安装并加载tidyverse:

library(tidyverse)

# 定义映射
reason_map <- tribble(
  ~reason_col, ~label,
  "reason1", "Rain",
  "reason2", "Wind",
  "reason3", "Thunder",
  "reason4", "None"
)

df_result <- df %>%
  pivot_longer(cols = starts_with("reason"), names_to = "reason_col", values_to = "value") %>%
  filter(value == 1) %>%
  left_join(reason_map, by = "reason_col") %>%
  group_by(id) %>%
  mutate(condition_num = paste0("condition", row_number())) %>%
  pivot_wider(
    id_cols = id,
    names_from = condition_num,
    values_from = label,
    values_fill = NA,
    names_expand = TRUE
  ) %>%
  ungroup() %>%
  # 补充缺失的condition列
  complete(id, fill = list(condition1 = NA, condition2 = NA, condition3 = NA, condition4 = NA)) %>%
  select(id, condition1, condition2, condition3, condition4)

# 查看结果
df_result

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 23:40:58