使用gsub用大括号和引号替换大括号和引号

问题描述 投票:0回答:1

我正在尝试使用gsub将所有大写的单引号/引号替换为平直的单引号。当我在下面运行以下代码时,遇到以下屏幕截图中提供的一些问题。

gsub("’","'",prank_df$Prank, ignore.case=TRUE) gsub("‘","'",prank_df$Prank, ignore.case=TRUE) gsub('“','"',prank_df$Prank, ignore.case=TRUE)

这是尝试上述功能之前的输出:enter image description here

这是运行上述gsub的结果:

enter image description here

r gsub
1个回答
0
投票

我想您正在寻找一种灵活表达gsub的方式。您可以看一下qdap::mgsub功能,该功能可以检查矢量化的图案,替换和字符对象。我可以举一个愚蠢的例子:

str <- "This string ‘has’ non “standard“ elements"

df = data.frame(str = rep(str,5))

qdap::mgsub(pattern = c("‘", "’", '“'),
      replacement = c("'","'",'"'),
      df$str)
[1] "This string 'has' non \"standard\" elements" "This string 'has' non \"standard\" elements"
[3] "This string 'has' non \"standard\" elements" "This string 'has' non \"standard\" elements"
[5] "This string 'has' non \"standard\" elements"

顺便说一句,如果您想在字符串中使用大引号("),R将对它们进行换行。使用打印功能时cat,您将看到预期的输出:

cat(qdap::mgsub(pattern = c("‘", "’", '“'),
+             replacement = c("'","'",'"'),
+             df$str), sep = "\n")
This string 'has' non "standard" elements
This string 'has' non "standard" elements
This string 'has' non "standard" elements
This string 'has' non "standard" elements
This string 'has' non "standard" elements
© www.soinside.com 2019 - 2024. All rights reserved.