简体   繁体   中英

R - How to replace two word with one word?

Lets Take example

I have one data frame called wf which has many rows and only 2 column 1st column has two word which will be relaced by 2nd column one word

wf
word1              word2
dikesh faldu    dikeshfaldu
any thing       anything
xyz asv         xyzasv
....

like this there are many rows suppose n..I have this variable already so nothing to do with wf okay. and i have one Corpus which has 2 document many text data so i have to find word1 and replace with word2 from wf how can i do this ?

let suppose

w <- read.csv("xyz.csv")
w <- as.vector(w)
corpus <- Corpus(vectorSource(w))

then i want to find word1 in corpus and replace with word2

let

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"

i can use this

for (i in 1:nrow(wf)){
w <- gsub(wf[i,1],wf[i,2],w)
}

but its not working for two words are there in the first column in wf

i want output like this

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

Method 1: for loop and gsub function

You can use gsub function to replace word1 with word2 row by row. You just remember and understanding the structure of for loop in R and gsub function and the question can be solved ,though not so effecient but effectively.

Method 2: mapvalues function in plyr package

The following code substitutes the 1,2,3(vector b ) in vector x with vector a .

library(plyr)
x = 1:4
a=c("A","B","C")
b=1:3
mapvalues(x,b,a)
[1] "A" "B" "C" "4"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM