繁体   English   中英

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

[英]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

方法1:for循环和gsub函数

您可以使用gsub函数逐行将word1替换为word2。 您只要记住并了解R和gsub函数中for循环的结构,就可以解决问题,尽管效率不高,但有效。

方法2:plyr包中的mapvalues函数

下面的代码替换的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