如何在R语言中替换字符串中的单词并返回新字符串?[已关闭]

nkkqxpd9  于 2022-12-20  发布在  R语言
关注(0)|答案(1)|浏览(219)

7天前关闭。
Improve this question
我有句话-"送礼时,[最好]"

I need to replace [Best] with {better; ideal; most effective} three words and return 3 sentences ,in a list.
"When giving a Gift, it is better"
"When giving a Gift, it is ideal"
"When giving a Gift, it is most effective"

我如何在R中实现它。

oxiaedzo

oxiaedzo1#

使用gsub

snt <-  "When giving a Gift, it is [Best] to"

alt <- list('better', 'ideal', 'moste effective')

lapply(alt, \(x) gsub('\\[Best\\]', x, sentence))
# [[1]]
# [1] "When giving a Gift, it is better to"
# 
# [[2]]
# [1] "When giving a Gift, it is ideal to"
# 
# [[3]]
# [1] "When giving a Gift, it is moste effective to"

相关问题