【发布时间】:2020-12-28 11:54:15
【问题描述】:
从这里解决的线程继续:matching strings regex exact match(感谢@Onyambu 更新代码)。
我需要完全匹配字符串 - 即使有特殊字符。
注意 - 抱歉,这是关于此问题的第三个问题。我快到了,但现在我不知道如何处理特殊字符,而且我仍在提高在 r 中操作字符串的技能。
为了清晰而更新:
我有一个这样的匹配词/字符串表:
codes <- structure(
list(
column1 = structure(
c(2L, 3L, NA),
.Label = c("",
"4+", "4 +"),
class = "factor"
),
column2 = structure(
c(1L,
3L, 2L),
.Label = c("old", "the money", "work"),
class = "factor"
),
column3 = structure(
c(3L, 2L, NA),
.Label = c("", "wonderyears",
"woke"),
class = "factor"
)
),
row.names = c(NA,-3L),
class = "data.frame"
)
还有一个包含一列字符串的数据集。 我想看看字符串中的每个记录中是否包含任何代码:
strings<- structure(
list(
SurveyID = structure(
1:4,
.Label = c("ID_1", "ID_2",
"ID_3", "ID_4"),
class = "factor"
),
Open_comments = structure(
c(2L,
4L, 3L, 1L),
.Label = c(
"I need to pick up some apples",
"The system works",
"Flag only if there is a 4 with a plus",
"Show me the money"
),
class = "factor"
)
),
class = "data.frame",
row.names = c(NA,-4L)
)
我目前正在使用以下代码将代码与字符串匹配:
strings[names(codes)] <- lapply(codes, function(x)
+(grepl(paste0("\\b", na.omit(x), "\\b", collapse = "|"), strings$Open_comments)))
输出:
SurveyID Open_comments column1 column2 column3
1 ID_1 The system works 0 0 0
2 ID_2 Show me the money 0 1 0
3 ID_3 Flag only if there is a 4 with a plus 1 0 0
4 ID_4 I need to pick up some apples 0 0 0
问题 - 第 3 行 ID_3 如果字符串包含“4+”或“4+”,我只想标记它,但无论如何它都会被标记。 有没有办法准确地捕捉到它?
【问题讨论】:
-
预期输出是什么
-
4 +和4+在 column1 中。是错字吗 -
I need to pick up 4 apples is being highlighted in column 1 even though it doesn't have a +.。输出中的 column1 显示为 1。 -
嗨@akrun。 4 的列中不应该有 1,只有当它是 4+ 或 4+,但不是 4 本身时。这有意义吗?
-
那么,输出应该是
1 0 0 0吧?
标签: r regex string stringr stringi