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

如何基于条件向R数据框列追加分类文本?无需循环实现

实现代码

你可以通过如下两种无显式循环的方案实现需求,分类规则可灵活扩展:

方案1:tidyverse 实现(代码可读性更高)

# 加载依赖包
library(dplyr)
library(stringr)

# 构造原始数据
df <- data.frame(
  animals = c("monkey", "humpback whale", "river trout", "seagull"),
  categories = NA_character_
)

# 定义分类规则,后续新增分类只需往列表中添加元素即可
category_rules <- list(
  mammal = c("whale", "monkey", "dog"),
  swimming = c("whale", "trout", "dolphin")
)

# 执行分类匹配
df <- df %>%
  rowwise() %>%
  mutate(
    categories = {
      matched <- names(category_rules)[sapply(category_rules, \(rule) any(str_detect(animals, rule)))]
      ifelse(length(matched) > 0, paste(matched, collapse = ","), "")
    }
  ) %>%
  ungroup()

方案2:base R 实现(无需额外安装包)

# 构造原始数据
df <- data.frame(
  animals = c("monkey", "humpback whale", "river trout", "seagull"),
  categories = NA_character_
)

category_rules <- list(
  mammal = c("whale", "monkey", "dog"),
  swimming = c("whale", "trout", "dolphin")
)

# 执行分类匹配
df$categories <- sapply(df$animals, \(x) {
  matched <- names(category_rules)[sapply(category_rules, \(rule) any(grepl(rule, x)))]
  ifelse(length(matched) > 0, paste(matched, collapse = ","), "")
}, USE.NAMES = FALSE)

两种方案运行后得到的df都和你预期的输出结果完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 11:15:08