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

多条件mutate生成星巴克数据category与Caffeine列的技术问询

星巴克数据集处理:生成分类与咖啡因标记列

需求说明

基于星巴克数据集,通过mutate生成两个新列:

  • category列:根据product_name的内容进行分类
  • Caffeine列:根据caffeine_mg的值标记,规则为caffeine_mg>0时为"Yes",caffeine_mg=0时为"No"

原代码存在的问题

  1. 多字符串匹配错误:grepl(c("coffee","Coffee","Caffè"), product_name)写法无效,grepl的pattern参数不支持直接传入字符向量,需用正则表达式的|合并多个匹配项。
  2. 条件判断运算符错误:case_when中caffeine_mg=0是赋值操作,判断相等必须用==。

修正后的完整代码

# 读取星巴克数据集
sbucks <- read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2021/2021-12-21/starbucks.csv')

# 生成目标新列
sbucks_new <- sbucks %>% 
  mutate(category = case_when(
    grepl("Tea", product_name) ~ "Tea",
    grepl("coffee|Coffee|Caffè", product_name) ~ "Coffee",
    grepl("Smoothie", product_name) ~ "Smoothie",
    grepl("Hot Chocolate", product_name) ~ "Hot Chocolate",
    grepl("Espresso", product_name) ~ "Espresso",
    grepl("Refreshers", product_name) ~ "Refreshers",
    TRUE ~ "Others"
  )) %>% 
  mutate(Caffeine = case_when(
    caffeine_mg == 0 ~ "No",
    caffeine_mg > 0 ~ "Yes"
  ))

关键修改说明

  • category列优化:将多字符串匹配改为coffee|Coffee|Caffè的正则形式,确保能匹配所有含咖啡相关关键词的产品;同时注意匹配顺序,若某产品名称包含多个关键词,会按代码中的顺序匹配第一个符合条件的分类。
  • Caffeine列修复:把赋值符号=替换为相等判断符==,保证条件逻辑正确执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 09:01:01