Prafulla
Prafulla

Reputation: 585

How to replace single word line in multiple lines?

I have a data frame of some strings. Some lines has single word which I want to replace with blank. I am able to retrieve the word but at the time of replacing them I get warning message

Warning message: In gsub(pattern = text[lengths(gregexpr("[[:alpha:]]+", text)) == : argument 'pattern' has length > 1 and only the first element will be used

Only first word gets replaces and rest are remains as it is. I want replace all the single words in the data frame.

Code I am using as below.

text <- c("Because I could not stop for Death -",
          "Word1",
          "He kindly stopped for me -",
          "Word2",
          "The Carriage held but just Ourselves - ",
          "word3",
          "and Immortality")

gsub(pattern = text[lengths(gregexpr("[[:alpha:]]+", text)) == 1], "", text)

I am expecting below output.

"Because I could not stop for Death -",
          "He kindly stopped for me -",
          "The Carriage held but just Ourselves - ",
          "and Immortality"

Upvotes: 0

Views: 356

Answers (3)

RavinderSingh13
RavinderSingh13

Reputation: 133538

Could you please try following and let me know if this helps you.

text <- c("Because I could not stop for Death -",
          "Word1",
          "He kindly stopped for me -",
          "Word2",
          "The Carriage held but just Ourselves - ",
          "word3",
          "and Immortality")

code for getting OP's required output:

text[!grepl("[Ww]ord[0-9]+", text)] 

Output will be as follows.

[1] "Because I could not stop for Death -"    "He kindly stopped for me -"             
[3] "The Carriage held but just Ourselves - " "and Immortality"

For grepl from help page:

grepl returns a logical vector (match or not for each element of x).

Upvotes: 0

Onyambu
Onyambu

Reputation: 79238

a=gsub("^\\w+$","",text)
[1] "Because I could not stop for Death -"    ""                                       
[3] "He kindly stopped for me -"              ""                                       
[5] "The Carriage held but just Ourselves - " ""                                       
[7] "and Immortality"   

grep("\\w",a,value = T)
[1] "Because I could not stop for Death -"    "He kindly stopped for me -"             
[3] "The Carriage held but just Ourselves - " "and Immortality"  

or you can simply do

grep("\\w+\\s",text,value = T)
[1] "Because I could not stop for Death -"    "He kindly stopped for me -"             
[3] "The Carriage held but just Ourselves - " "and Immortality"  

Upvotes: 1

Sotos
Sotos

Reputation: 51592

A simple logical indexing will do the trick here since the words you want to keep seem to be at positions 1, 3, 5, ... and so on, i.e.

text[c(TRUE, FALSE)]
#[1] "Because I could not stop for Death -"    "He kindly stopped for me -"             
#[3] "The Carriage held but just Ourselves - " "and Immortality"

Upvotes: 1

Related Questions