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

R语言dplyr:如何将含"ref"的列值替换为reference,其余为test?

解决方法

你的代码存在两个关键问题导致未达到预期效果:

  1. 拼写错误:把目标替换值reference误写为refernce
  2. case_when缺少默认分支逻辑,未匹配到"ref"的行会生成NA,而不是需求中的"test"

修正后的完整代码如下:

library(dplyr)

# 读取文本文件数据
farmdata <- read.delim("C:/Users/Documents/farmdata.txt")

# 处理location列,生成新列或直接替换原列
farmdata <- farmdata %>% 
  mutate(location_new = case_when(
    grepl("ref", location) ~ "reference",  # 匹配所有含"ref"的内容
    TRUE ~ "test"  # 其余所有情况统一替换为"test"
  ))

额外说明:

  • 若需要忽略大小写匹配(比如识别"Ref"、"REF"这类变体),可将grepl("ref", location)修改为grepl("ref", location, ignore.case = TRUE)
  • 如果想直接覆盖原location列而非新增location_new,只需把代码中的location_new替换为location即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 21:45:57