[英]R gsub remove words in column y from words in column x
我正在嘗試使用 gsub 刪除 x 列中 y 列中的單詞/文本。
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]])
你可能會問,但我只有一個repl
, repl[[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) 解決方案適用於非常小的數據集,但我發現它對大型數據集返回錯誤。
Mac 用戶注意:在安裝 qdap 包之前,請確保您的計算機上事先安裝了 java 和 pdk(oracle)軟件。 otw 你會在安裝/嘗試運行 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"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.