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()
运行后得到的结果和你需求的输出完全一致:
| regex | text | result |
|---|---|---|
| cat | asdf.cat/asdf | 1 |
| dog | asdf=asdf | 0 |
| mouse | asdf=mouse asdf | 1 |
内容的提问来源于stack exchange,提问作者Ellie Sparling
相关产品推荐
相关产品推荐

