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

R语言如何用grepl匹配dataframe两列内容逐行生成0/1结果列

实现逐行正则匹配生成结果列的方案

基础R实现

你之前用到的Map/mapply逻辑是正确的,只需要把返回的逻辑值直接转为整数赋值给新列即可,不需要套filter筛选:

# 正则匹配模式
df$result <- as.integer(mapply(grepl, pattern = df$regex, x = df$text))

# 若仅需要纯字符串匹配(忽略正则元字符特殊含义,适配含大量特殊字符的text列),新增fixed参数
df$result <- as.integer(mapply(grepl, pattern = df$regex, x = df$text, fixed = TRUE))

dplyr 实现

如果习惯用管道操作,可以用rowwise指定逐行运算:

library(dplyr)
df <- df %>%
  rowwise() %>%
  mutate(result = as.integer(grepl(regex, text, fixed = FALSE))) %>% # fixed参数按需调整
  ungroup()

运行后得到的结果和你需求的输出完全一致:

regextextresult
catasdf.cat/asdf1
dogasdf=asdf0
mouseasdf=mouse asdf1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 07:27:03