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

如何用dplyr管道根据location列创建location_type二元列?

解决方法

你的代码问题出在contains("River")的用法上——contains()是dplyr中用于列选择的函数,不能直接用来检测字符串内容。要判断location字段是否包含"River",需要用字符串匹配工具,推荐结合stringr包的str_detect()函数来实现。

方法1:使用ifelse

library(dplyr)
library(stringr)

df %>%
  mutate(location_type = ifelse(str_detect(location, "River"), "river", "lake"))

方法2:使用case_when(更灵活,适合多场景扩展)

如果之后需要添加更多分类规则,case_when会更易维护:

df %>%
  mutate(location_type = case_when(
    str_detect(location, "River") ~ "river",
    TRUE ~ "lake"  # 所有不满足上面条件的情况都归为lake
  ))

额外说明

  • 如果还没安装stringr包,先执行install.packages("stringr")完成安装。
  • 若需要忽略大小写匹配(比如同时匹配"river"、"RIVER"),可以修改str_detect的参数:
    str_detect(location, regex("River", ignore_case = TRUE))
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 03:42:04