Kim Jenkins
Kim Jenkins

Reputation: 438

r remove character before space in a string

I have a column within a dataframe where some values are like this

   Col1
   Y 183.21
   500.23

   432.89
   Y 428.29


   Y500

I am looking for a way to remove only those Y prior to those strings that have Y and some characters separated by a space ( Y 183.21, Y 428.29 ) . Not the Y that is not separated by the space (Y500) but only Ys that are separated by space ( Y 183.21, Y 428.29 ). The expected output would be

   Col1
   183.21
   500.23

   432.89
   428.29


   Y500

I tried some examples but unsuccessful. Any advice or tips are much appricated.

Upvotes: 0

Views: 237

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 389355

We can use sub assuming you have only one match

sub("Y ", "", df$Col1)

#[1] "183.21" "500.23" "432.89" "428.29" "Y500"  

Upvotes: 1

MFR
MFR

Reputation: 2077

We can use package stringi

library(stringi)

new.df<-stri_replace_all(df,"" ,fixed = "Y " )

Upvotes: 2

Related Questions