Feng Chen Feng Chen - 1 year ago 90
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 Source

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"


str1 <- c("xxxxxx xxxx xxxxxx 1.5L xxxxx" , "xxxxxx xxxx xxxxxx 1.5 L xxxxx")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download