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

如何根据样本二进制列取值,将对应列名用逗号拼接生成汇总新列

解决方案

方法1:tidyverse 简洁实现(推荐)

直接按行匹配取值为1的属性列名,自动过滤无效值,无多余逗号:

library(tidyverse)

# 示例数据
df <- tibble(
  sample_id = c(1,2,3),
  type_1 = c(0,1,1),
  type_2 = c(0,1,1),
  type_3 = c(1,0,1)
)

df <- df %>%
  mutate(type = pmap_chr(select(., starts_with("type_")), ~ {
    vals <- c(...)
    paste(names(vals)[vals == 1], collapse = ", ")
  }))

如果属性列没有统一前缀,可以直接指定列范围:将select(., starts_with("type_"))替换为select(., type_1:type_3)即可。

方法2:rowwise 语法实现(逻辑更直观)

df <- df %>%
  rowwise() %>%
  mutate(type = paste(
    names(select(cur_data(), type_1:type_3))[c_across(type_1:type_3) == 1],
    collapse = ", "
  )) %>%
  ungroup()

方法3:原有if_else思路修复

如果你想沿用之前创建中间列的实现,只需要将空值设为NA,拼接后清理多余逗号即可:

df %>%
  mutate(
    col1 = if_else(type_1 == 1, "type_1", NA_character_),
    col2 = if_else(type_2 == 1, "type_2", NA_character_),
    col3 = if_else(type_3 == 1, "type_3", NA_character_),
    type = paste(col1, col2, col3, sep = ", ") %>% 
      str_remove_all("(^, |, $|, (?=,))")
  )

小提示:如果某行所有二进制属性取值都为0,上述方法会返回空字符串,可额外添加if_else(type == "", "无匹配属性", type)自定义占位值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 08:36:07