R 从字符串中删除相邻的重复项

R 从字符串中删除相邻的重复项,r,string,duplicates,R,String,Duplicates,我在分析歌词。这些通常包含“拉拉”和“哦哦哦”。基本上没有意义的词。我想删除这些重复的单词,或者至少首先识别它们。 下面是一些几乎可以完成这项工作的代码 test <- data.frame(c("la la la yeah the meaning of life vive la France yeah yeah yeah")) names(test) <- "V1" test$V1 <- as.character(test$V1) d <- unlist(strspl

我在分析歌词。这些通常包含“拉拉”和“哦哦哦”。基本上没有意义的词。我想删除这些重复的单词,或者至少首先识别它们。 下面是一些几乎可以完成这项工作的代码

test <- data.frame(c("la la la yeah the meaning of life vive la France yeah yeah yeah"))
names(test) <- "V1"
test$V1 <- as.character(test$V1)

d <- unlist(strsplit(test$V1, split=" "))
test$V2 <- paste(d[-which(duplicated(d))], collapse = ' ')
test$V2

test我们可以在这里尝试使用
gsub
和肯定的先行断言,该断言检查相邻的重复单词:

input <- "la la la yeah the meaning of life vive la France yeah yeah yeah"
output <- gsub("(\\S+)( \\1)+", "", input, perl=TRUE)
output <- gsub("^\\s+|\\s+$", "", output)
output

[1] "yeah the meaning of life vive la France"

input也许您需要
rle
来识别顺序并只选择长度为1的单词

sapply(strsplit(test$V1, split=" "), function(x) {
   paste(with(rle(x), values[lengths == 1]), collapse = " ")
})
#[1] "yeah the meaning of life vive la France"

@RonakShah谢谢…当我回答时,我读到的只是标题,它指的是相邻的副本。OP没有清楚显示预期的输出。谢谢,我不知道rle功能。它确实做得很好。谢谢谢谢,老实说,我从来没有见过复选标记选项。我真没注意到:-(我也会在我的答案上标出前面的回答。谢谢