【发布时间】:2019-07-04 23:55:12
【问题描述】:
我一直在思考这个问题,尝试了很多 map、Reduce 等,但到目前为止都没有成功。
我正在寻找一种实用、优雅的方法来替换 gsub 的序列,如
text_example <- c(
"I'm sure dogs are the best",
"I won't, I can't think otherwise",
"We'll be happy to discuss about dogs",
"cant do it today tho"
)
text_example %>%
gsub(pattern = "'ll", replacement = " will") %>%
gsub(pattern = "can'?t", replacement = "can not") %>%
gsub(pattern = "won'?t", replacement = "will not") %>%
gsub(pattern = "n't", replacement = " not") %>%
gsub(pattern = "'m", replacement = " am") %>%
gsub(pattern = "'s", replacement = " is") %>%
gsub(pattern = "dog", replacement = "cat") %>%
变成某种形式的东西
text_example %>%
???(dict$pattern, dict$replacement, gsub())
为了一个可重现的例子,dict 可以是一个 data.frame,例如
dict <- structure(
list(
pattern = c("'ll", "can'?t", "won'?t", "n't", "'m", "'s", "dog"),
replacement = c(" will", "can not", "will not", " not", " am", " is", "cat")
),
row.names = c(NA, -7L),
class = "data.frame"
)
(我知道执行的替换可能在语言上不正确,但现在不是问题)
当然是残酷的
for(i in seq(nrow(dict))) {
text_example <- gsub(dict$pattern[i], dict$replacement[i], text_example)
}
会起作用,我知道有几十个库可以通过某些特定功能解决这个问题。但我想了解如何以简单、实用的方式处理此类递归和问题,尽可能接近基础 R。我喜欢我的 lambda!
提前感谢您的帮助。
【问题讨论】:
-
chartr(): 如果您的模式和替换是单个字母,则相关。 -
qdap::mgsub似乎相关。mgsub(dict$pattern, dict$replacement, text_example, fixed = FALSE) -
@WiktorStribiżew 感谢
qdap的建议,但从我问题的最后一部分开始:“我知道有几十个库可以通过某些特定功能解决这个问题。但我想了解如何以简单、实用的方式处理递归和此类问题,并尽可能接近基础 R。”我还没有找到任何满足这个标准的合适答案。因此,我不认为它是重复的。 -
@WiktorStribiżew 如果你深入了解,
mgsub有一个“brutal”循环。所以不清楚有什么好处。这个问题要求超出此范围。 -
对“函数式”可能存在误解:我的问题不是“是否有函数”而是“是否有函数式编程方法,即传递 gsub() 作为映射的参数,lapply ,减少...函数”-adv-r.had.co.nz/Functional-programming.html 中解释了更多内容。在其他链接的问题中有几个有趣的想法,但仍然......不是我要问的:(
标签: r functional-programming lapply gsub