[英]R - How to replace two word with one word?
讓我們舉個例子
我有一個稱為wf的數據幀,它有很多行,只有2列,第1列有兩個字,將被第2列一個字取代
wf
word1 word2
dikesh faldu dikeshfaldu
any thing anything
xyz asv xyzasv
....
像這樣,假設有很多行n ..我已經有了這個變量,所以與wf無關。 而且我有一個Corpus
,其中有2個文檔包含許多文本數據,因此我必須從wf
找到word1
並替換為word2
,我該怎么做?
假設
w <- read.csv("xyz.csv")
w <- as.vector(w)
corpus <- Corpus(vectorSource(w))
然后我想在corpus
找到word1
並替換為word2
讓
w <- "hello, dikesh faldu i want to replace word1 with word2 in this text data how can i do this xyz asv . where word1 is occured in this document i want to replace with word2"
我可以用這個
for (i in 1:nrow(wf)){
w <- gsub(wf[i,1],wf[i,2],w)
}
但是在wf的第一列中沒有兩個詞
我想要這樣的輸出
hello, dikeshfaldu i want to replace word1 with word2 in this text data how can i do this xyzasv . where word1 is occured in this document i want to replace with word2
您可以使用gsub函數逐行將word1替換為word2。 您只要記住並了解R和gsub函數中for循環的結構,就可以解決問題,盡管效率不高,但有效。
下面的代碼替換的1,2,3-(向量b
)在矢量x
與矢量a
。
library(plyr)
x = 1:4
a=c("A","B","C")
b=1:3
mapvalues(x,b,a)
[1] "A" "B" "C" "4"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.