0

I have a dataframe column which have pattern like

   | NA

I want to replace this and text after this with blank space.

  | NA | 0 | 4

So above string should be replaced by blank space. I used following code.

  df$string <- gsub("| NA" , "",df$string) 

But its nit workinh for the string after this pattern.

Neil
  • 7,937
  • 22
  • 87
  • 145

1 Answers1

1

Use this:

df$string <- gsub("\\| NA.*$" , "", df$string)

The pipe | symbol is a regex metacharacter (alternation). So it needs to be escaped in order to match it literally.

The regex I used \\| NA.*$ will match your desired pattern and anything following it to the end of the line, and will replace it with empty string.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360