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

如何在R语言中拆分列并生成0-1编码的新变量?

问题:将多类别字符串列转换为二进制指示列

原始数据

V1  V2
1   orange, apple
2   orange, lemon
3   lemon, apple
4   orange, lemon, apple
5   lemon
6   apple
7   orange
8   lemon, apple

需求

  • V2列包含三个固定类别:orange、lemon、apple
  • 为每个类别单独创建一列,用1标记该行V2包含对应类别,0标记不包含

尝试的错误方法

使用separate拆分列:

df %>% separate(V2, into = c("orange", "lemon", "apple"))

得到不符合预期的结果:

V1 orange lemon apple
1  1   orange   apple    <NA>
2  2   orange   lemon    <NA>
3  3    lemon   apple    <NA>
4  4   orange   lemon   apple
5  5    lemon    <NA>    <NA>
6  6    apple    <NA>    <NA>
7  7   orange    <NA>    <NA>
8  8    lemon   apple    <NA>

期望结果

V1  orange  lemon   apple
1   1   0   1
2   1   1   0
3   0   1   1
4   1   1   1
5   0   1   0
6   0   0   1
7   1   0   0
8   0   1   1

(注:原期望结果第4行存在笔误,实际该行V2包含三个类别,对应列都应为1)

正确解决方案

方法1:使用separate_rows + pivot_wider(tidyverse风格)

library(tidyr)
library(dplyr)

df %>%
  # 将每行的多类别拆分为单独行
  separate_rows(V2, sep = ", ") %>%
  # 标记存在的类别为1
  mutate(value = 1) %>%
  # 宽表转换,缺失值填充为0
  pivot_wider(names_from = V2, values_from = value, values_fill = 0)

方法2:使用str_detect直接生成指示列

library(dplyr)
library(stringr)

df %>%
  mutate(
    orange = as.integer(str_detect(V2, fixed("orange"))),
    lemon = as.integer(str_detect(V2, fixed("lemon"))),
    apple = as.integer(str_detect(V2, fixed("apple")))
  ) %>%
  # 移除原V2列
  select(-V2)

说明

separate函数的作用是按分隔符将一列拆分为多列,拆分后每个位置的内容对应到指定列,无法实现“判断类别是否存在”的需求。上述两种方法分别通过行转列再宽表转换,或直接字符串匹配的方式,实现了二进制指示列的生成。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 10:20:25