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

R语言中dplyr的mutate+case_when+grepl匹配cash.other结果异常

问题解决:cash.other的正确映射方法

问题原因

case_when是按顺序判断条件的,一旦前面的条件满足就会返回对应值,不会执行后续条件。你的代码中,grepl("cash", tolower(values))会先匹配到"cash.other"(因为字符串包含"cash"),直接返回"Cash",导致后面grepl("cash.other", ...)的条件完全没机会触发。

解决方案

把更具体的匹配条件放在前面,也就是把"cash.other"的判断移到"cash"和"other"的条件之前。另外注意你代码里的笔误:"Lond"应该是"Loan"。

修正后的代码:

df <- df %>%
  mutate(values = case_when(
    grepl("loan", tolower(values))  ~ "Loan",
    grepl("cash.other", tolower(values)) ~ "Cash_Other", # 提前具体匹配条件
    grepl("cash", tolower(values))  ~ "Cash",
    grepl("equity", tolower(values)) ~ "Equity",
    grepl("other", tolower(values)) ~ "Other",
    grepl("commercial.news", tolower(values)) ~ "Commercial_News",
    grepl("money.news", tolower(values)) ~ "Money_News",
    TRUE ~ as.character(values)
  ))

更严谨的优化方案

如果是精确匹配整个字符串(而非包含子串),建议用==代替grepl,避免意外匹配:

df <- df %>%
  mutate(values = case_when(
    tolower(values) == "loan"  ~ "Loan",
    tolower(values) == "cash.other" ~ "Cash_Other",
    tolower(values) == "cash"  ~ "Cash",
    tolower(values) == "equity" ~ "Equity",
    tolower(values) == "other" ~ "Other",
    tolower(values) == "commercial.news" ~ "Commercial_News",
    tolower(values) == "money.news" ~ "Money_News",
    TRUE ~ as.character(values)
  ))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 18:42:39