【问题标题】:R: functional approach to multiple consecutive gsubR:多个连续 gsub 的函数方法
【发布时间】:2019-07-04 23:55:12
【问题描述】:

我一直在思考这个问题,尝试了很多 mapReduce 等,但到目前为止都没有成功。

我正在寻找一种实用、优雅的方法来替换 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


【解决方案1】:

也许以下内容可以满足您的需求。
它的灵感来自您评论中的链接Functional Programming
虽然我不喜欢输出,但它是一个列表,其元素与数据框 dict 的行一样多,只有最后一个是感兴趣的。

new_text <- function(pattern, replacement, text) {
  txt <- text
  function(pattern, replacement) {
    txt <<- gsub(pattern, replacement, txt)
    txt
  }
}

Replace <- new_text(p, r, text = text_example)

Map(Replace, as.list(dict[[1]]), as.list(dict[[2]]))

【讨论】:

    【解决方案2】:

    您可以使用mapply 来实现并行应用效果:

    mapply(dict$pattern, dict$replacement, function(pttrn, rep) gsub(pttrn, rep, text_example))
    

    (您可能想使用SIMPLIFY=FALSE

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-03
      • 2019-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-04
      • 1970-01-01
      相关资源
      最近更新 更多