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

自闭症网瘾萝莉.ら 提交于 2019-12-02 06:04:12

Normally gsub takes three arguments 1) pattern, 2) replacement and 3) vector to replace values.

The pattern must be a single string. And the same for the replacement. The only part of the function that is open to multiple values is the vector. We call it vectorized because of this.

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

The pattern argument is not vectorized, but we can use mapply to complete the task.

mapply and 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]])

You may be asking, but I only have one repl, how does repl[[2]] and repl[[3]] work? The function noticed that for us and repeated 'repl' until it equaled the length of the others.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!