gsub 替换中的函数 [英] Function in gsub replacement
问题描述
是否可以在 gsub
替换短语中应用函数?假设在 str_to_title
之后我们有
Is it possible to apply function in gsub
replacement phrase ? Let's say after str_to_title
we have
这是一个地狱般的Blahblah蛋糕
我想从 str_to_title
函数的效果中忽略某些词,这样我就有
I would like ignore certain words from the effect of str_to_title
function, so that I would have
This is one Hell of a blahblah Cake
我知道 str_to_title 有自己的异常列表,但我想通过将某些短语恢复为小写来自定义该列表.
I am aware that str_to_title has its own list of exception, but I would like to customize that list by reverting some phrase back to lowercase.
我目前的做法是
gsub("( Is | One | BlahBlah )", tolower("\\1"), str_to_title(x))
但是 gsub
不会看到 tolower
函数.一个想法如何实现这一目标?我们如何用作用于匹配字符串的函数替换正则表达式?
but gsub
will not see the tolower
function. An idea how t achieve this ? How can we replace regex with a function acting on the matched string ?
推荐答案
您可以使用 \\L
将它们转换为小写:
You can prefix the replacement with \\L
to convert them to lower case:
s = "This Is One Hell Of A Blahblah Cake"
gsub("(\\bIs\\b|\\bOne\\b|\\bBlahblah\\b)", "\\L\\1", s, perl = T)
# [1] "This is one Hell Of A blahblah Cake"
或者如@joran 所评论的,您可以使用 gsubfn
包:
Or as commented @joran, you can use gsubfn
package:
library(gsubfn)
options(gsubfn.engine = "R")
gsubfn("\\bIs\\b|\\bOne\\b|\\bBlahblah\\b", ~ tolower(x), s)
# [1] "This is one Hell Of A blahblah Cake"
这篇关于gsub 替换中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!