我创建了一个数据框(来自csv文件),用于纠正我正在处理的文本中的拼写错误:

df1 <- data.frame(
  old_text = c("typo1",
               "typo2",
               "typo3"), 
  fixed_text = c("typo1_fixed", 
                 "typo2_fixed", 
                 "typo3_fixed"))

我现在正在try 浏览实际文本(位于单独的数据框中),如果有拼写错误,请进行修复:

df2 <- data.frame(
  text= c("typo1", "Hi", "typo2", "Bye", "typo3"))

我try 了mapply,但不起作用:

df2$text[grepl(df1$old_text, df2$text)] = mapply(function(x,y) gsub(x,y,df2$text[grepl(df1$old_text, df2$text)]), df1$old_text, df1$new_text)

"Error in mapply(function(x, y) gsub(x, y, df2$text[grepl(df1$old_text,  : 
  zero-length inputs cannot be mixed with those of non-zero length"

任何帮助都将不胜感激!

推荐答案

使用stringr::str_replace_all,可以使用模式和替换的命名向量:

library(stringr)
df2$result = str_replace_all(string = df2$text, pattern = setNames(df1$fixed_text, nm = df1$old_text))
df2
#    text      result
# 1 typo1 typo1_fixed
# 2    Hi          Hi
# 3 typo2 typo2_fixed
# 4   Bye         Bye
# 5 typo3 typo3_fixed  

对于base R,我将使用for循环.您的mapply错误是因为输入错误(df1$new_text应该是df1$fixed_text),但由于grepl...很难让mapply多次修改单个列.但是for循环写起来很快——参见下面的方法2.

如果像本例中那样搜索完全匹配的字符串,则根本不需要regex.不需要正则表达式就可以看到"a" == "a",只需要正则表达式函数就可以看到"abc"包含"a"`.参见下面的方法3.

# Method 1
library(stringr)
df2$result1 = str_replace_all(string = df2$text, pattern = setNames(df1$fixed_text, nm = df1$old_text))

# Method 2
df2$result2 = df2$text 
for(i in 1:nrow(df1)) {
  df2$result2 = gsub(pattern = df1$old_text[i], replacement = df1$fixed_text[i], x = df2$result2)
}

# Method 3
df2$results3 = df2$text
matches = match(df2$text, df1$old_text) 
df2$results3[!is.na(matches)] = df1$fixed_text[na.omit(matches)]

df2
#    text     result1     result2    results3
# 1 typo1 typo1_fixed typo1_fixed typo1_fixed
# 2    Hi          Hi          Hi          Hi
# 3 typo2 typo2_fixed typo2_fixed typo2_fixed
# 4   Bye         Bye         Bye         Bye
# 5 typo3 typo3_fixed typo3_fixed typo3_fixed

(即使是在字符串中搜索,如果要进行没有regex特殊字符的精确匹配,也可以使用gsubstringr::fixed()函数或fixed = TRUE)参数来加快速度.)

R相关问答推荐

如何从其他前面列中减go 特定列的平均值?

如何替换R中数据集列中的各种字符串

如何使用shinyChatR包配置聊天机器人

R等效于LABpascal(n,1)不同的列符号

根据多个条件增加y轴高度以适应geom_text标签

如何在观测缺失的地方添加零

R函数,用于生成伪随机二进制序列,其中同一数字在一行中不出现超过两次

如何使用tryCatch执行语句并忽略警告?

计算满足R中条件的连续列

try 将 colored颜色 编码添加到ggploly的标题中

在使用tidyModels和XGBoost的二进制分类机器学习任务中,所有模型都失败

条形图顶部与其错误条形图不对齐

R如何计算现有行的总和以添加新的数据行

R -如何分配夜间GPS数据(即跨越午夜的数据)相同的开始日期?

多元正态分布的计算

在ggplot2图表中通过端点连接点

如何在shiny 的应用程序 map 视图宣传单中可视化单点

在一个multiplot中以非对称的方式在R中绘制多个图

如何在类应用函数中访问函数本身

以列名的字符向量作为参数按行应用自定义函数