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

如何在R中基于数据框某列的子字符串创建分类新列?

在R语言中基于子字符串创建新列的解决方案

问题分析

你之前的代码错误在于使用==进行精确匹配,而非检测字符串中是否包含目标子串,同时未按规则优先级处理判断逻辑——需先判断是否同时包含Acoustic和Satellite(优先级最高),再判断是否包含Acoustic/Radio/PIT,最后处理其余情况。

解决方案

方法1:Base R 嵌套ifelse

# 先判断是否同时包含Acoustic和Satellite
df$Type <- ifelse(grepl("Acoustic", df$Combination) & grepl("Satellite", df$Combination),
                  "Both",
                  # 再判断是否包含Acoustic/Radio/PIT中的任意一个
                  ifelse(grepl("Acoustic|Radio|PIT", df$Combination),
                         "receiver based",
                         # 其余情况
                         "non receiver based"))

方法2:dplyr 包的case_when(更清晰的多条件判断)

若习惯使用tidyverse工具,case_when会让逻辑更直观:

library(dplyr)

df <- df %>%
  mutate(Type = case_when(
    # 优先级1:同时包含Acoustic和Satellite
    grepl("Acoustic", Combination) & grepl("Satellite", Combination) ~ "Both",
    # 优先级2:包含Acoustic/Radio/PIT任意一个
    grepl("Acoustic|Radio|PIT", Combination) ~ "receiver based",
    # 其余情况
    TRUE ~ "non receiver based"
  ))

代码说明

  • grepl(pattern, x):检测字符串x中是否包含指定pattern,返回布尔值(TRUE/FALSE)。
  • 正则表达式Acoustic|Radio|PIT表示匹配任意一个目标子串。
  • 条件判断必须按优先级从高到低排列,否则会出现逻辑覆盖错误(比如先判断单一子串会覆盖"Both"的情况)。

结果验证

可抽取部分行验证结果:

# 查看不同类型的结果
unique(df[, c("Combination", "Type")])

示例结果:

CombinationType
BRUV_Acoustic_SatelliteBoth
Stationary_Radioreceiver based
Animalborne_Archivalnon receiver based
Stationary_Acoustic_PITreceiver based

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 09:09:59