How to match a string and white space in R

duvvurum picture duvvurum · Jul 15, 2016 · Viewed 21.6k times · Source

I have a dataframe with columns having values like:

"Average 18.24" "Error 23.34". My objective is to replace the text and following space from these. in R. Can any body help me with a regex pattern to do this?

I am able to successfully do this using the [A-Z]. But i am not able to combine the white space. [A-Z][[:space:]] no luck. Your help is appreciated.

Answer

akrun picture akrun · Jul 15, 2016

We can use sub. Use the pattern \\D+ to match all non-numeric characters and then use '' in the replacement to remove those.

sub("\\D+", '', v2)
#[1] "18.24" "23.34"

Or match one or more word characters followed by one or more space and replace with ''.

 sub("\\w+\\s+", "", v2)
 #[1] "18.24" "23.34"

Or if we are using stringr

library(stringr)
word(v2, 2)
#[1] "18.24" "23.34"

data

v2 <- c("Average 18.24" ,"Error 23.34")