Feng Chen Feng Chen - 1 month ago 18
R Question

how to delete a space between a number and a character using r and stringr

I am using R and stringr to do some string replacement. My text is like "xxxxxx xxxx xxxxxx 1.5L xxxxx" or "xxxxxx xxxx xxxxxx 1.5 L xxxxx". My question is: how to delete the space between 1.5 and L? or How to add a space between them? Thanks a lot.

Answer

We can do this with a single capture group using sub

sub("(\\d+)\\s+", "\\1", str1)
#[1] "xxxxxx xxxx xxxxxx 1.5L xxxxx" "xxxxxx xxxx xxxxxx 1.5L xxxxx"

data

str1 <- c("xxxxxx xxxx xxxxxx 1.5L xxxxx" , "xxxxxx xxxx xxxxxx 1.5 L xxxxx")