gsub() 整列覆盖另一列

gsub() an entire column over another column

我有一个 df:

df <- data.frame(
    x=c("ABC Inc", "DCV", "FGZ", "JH7 j11"),
    y=c("ABC - fasjdlkjs", "DCV . (INC) .. kdhkfhksf", "FGZ / qiuwy72gs", "JH7 j11 dhd"),
    target=c("fasjdlkjs", "inc kdhkfhksf", "qiuwy gs", "dhd")
)

其中 xy

的一个接近但不精确的子集

我想将 x 中的所有内容 gsub() 到 y 中的 ""(空白),同时还删除 numbers/punctuation.

我想要的输出存储在 target

我认为这会奏效,但没有:

df <- mutate(target = gsub(pattern=x, replacement="", y))

编辑:

排序为:Y - X = Target

这(现在 - 感谢@Frank)转换大小写 tolower。下面,s 通过用空格

拆分 x 字符串来构建要从 x 列进行测试的字符串
df$res <- mapply(function(a, b) {
    s <- paste(c(unlist(strsplit(as.character(a)," ")), "[[:punct:]]"), collapse="|")
    tolower(gsub("[[:digit:]]+", " ", gsub(s, "", b)))
  }, df$x, df$y)

df
#         x                        y        target              res
# 1 ABC Inc          ABC - fasjdlkjs     fasjdlkjs        fasjdlkjs
# 2     DCV DCV . (INC) .. kdhkfhksf inc kdhkfhksf   inc  kdhkfhksf
# 3     FGZ          FGZ / qiuwy72gs      qiuwy gs         qiuwy gs
# 4 JH7 j11              JH7 j11 dhd           dhd              dhd