我正在尝试使用gsub将所有大写的单引号/引号替换为平直的单引号。当我在下面运行以下代码时,遇到以下屏幕截图中提供的一些问题。
gsub("’","'",prank_df$Prank, ignore.case=TRUE)
gsub("‘","'",prank_df$Prank, ignore.case=TRUE)
gsub('“','"',prank_df$Prank, ignore.case=TRUE)
这是运行上述gsub的结果:
我想您正在寻找一种灵活表达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