R gsub 从 x 列中的单词中删除 y 列中的单词

R gsub remove words in column y from words in column x

我正在尝试使用 gsub 删除 y 列中 x 列中的单词/文本。

x = c("a","b","c")
y = c("asometext", "some, a b text", "c a text")
df = cbind(x,y)
df = data.frame(df)
df$y = gsub(df$x, "", df$y)

如果我 运行 上面的代码,它只删除第 x 列第 1 行的文本,而不是所有行:

> df
  x             y
1 a      sometext
2 b some,  b text
3 c       c  text

我希望最终结果是:

> df
  x             y
1 a      sometext
2 b      some,   text
3 c      text

因此,应从 y 列中删除 x 列中的所有单词/字母。这可以用 gsub 实现吗?

通常 gsub 采用三个参数 1) 模式,2) 替换和 3) 向量来替换值。

模式必须是单个字符串。更换也一样。函数中唯一对多个值开放的部分是向量。因此我们称它为矢量化。

gsub(df$x, "", df$y)  #doesn't work because 'df$x' isn't one string

模式参数未向量化,但我们可以使用mapply来完成任务。

mapply 和 gsub (bffs)

x = c("a","b","c")
y = c("asometext", "some, a b text", "c a text")
repl = ""

#We do
mapply(gsub, x, repl, y)

#On the inside
gsub(x[[1]], repl[[1]], y[[1]])
gsub(x[[2]], repl[[2]], y[[2]])
gsub(x[[3]], repl[[3]], y[[3]])

你可能会问,我只有一个replrepl[[2]]repl[[3]]怎么用?该函数为我们注意到并重复 'repl' 直到它等于其他的长度。

这是一个使用 str_remove_all 的解决方案:

library(stringr)    
x  = c("a","b","c")
y  = c("asometext", "some, a b text", "c a text")
df = cbind(x,y)
df = data.frame(df,stringsAsFactors = F)

# creating a format of "[abc]" to use in str_remove_all
comb_a = paste0("[",paste(df$x,collapse = ""),"]")

df$y = sapply(df$y, function(r) str_remove_all(r, comb_a) )
df

我在一个非常大的数据集上尝试了上述答案,发现这段代码效果最好:

x = c("a","b","c")
y = c("asometext", "some, a b text", "c a text")

library(qdap)

z<- mgsub(x, "", y) 

给出了所需的解决方案:

z: "sometext", "some,  text", "  text"

这是因为 mgsub 函数是 gsub 的包装器,它采用搜索词向量和替换向量或单个值,我发现它比 gsub 更强大,尤其是在处理大数据集时。它完成了 gsub 需要 2-3 行代码才能完成的工作。

虽然上面的 gsub(paste0) 解决方案适用于非常小的数据集,但我发现它对于大型数据集 returns 错误。

Mac 用户请注意:在安装 qdap 包之前,请确保您的计算机上预先安装了 java 和 pdk (oracle) 软件。 otw 当 installing/trying 到 运行 qdap 包时你会 运行 出错,因为它是基于 java 的。

这是使用 for 循环实现的一种方法

output <- y
for (i in 1:3){
    output <- gsub(pattern = x[i],
                 replacement = "",
                 output)
}
print(output)

您将得到的结果:

    print(output)
[1] "sometext"     "some,   text" "  text"