简体   繁体   English

R-如何用一个单词替换两个单词?

[英]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的数据帧,它有很多行,只有2列,第1列有两个字,将被第2列一个字取代

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. 像这样,假设有很多行n ..我已经有了这个变量,所以与wf无关。 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 ? 而且我有一个Corpus ,其中有2个文档包含许多文本数据,因此我必须从wf找到word1并替换为word2 ,我该怎么做?

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 然后我想在corpus找到word1并替换为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 但是在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 方法1:for循环和gsub函数

You can use gsub function to replace word1 with word2 row by row. 您可以使用gsub函数逐行将word1替换为word2。 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. 您只要记住并了解R和gsub函数中for循环的结构,就可以解决问题,尽管效率不高,但有效。

Method 2: mapvalues function in plyr package 方法2:plyr包中的mapvalues函数

The following code substitutes the 1,2,3(vector b ) in vector x with vector a . 下面的代码替换的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.

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