Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R paste: ignore sep if argument is an empty string

Tags:

r

I'm trying to paste together lines of addresses to a single address string. However, some lines are blank ("") and this means that an extra sep gets inserted and makes the address look ugly. For example:

addr.df <- data.frame(street1=c("22B","Windsor Castle"),street2=c("Baker Street",""),city=c("London","Windsor"))

with(addr.df,paste(street1,street2,city,sep=", "))
[1] "22B, Baker Street, London" "Windsor Castle, , Windsor"

Notice the extra , in the second address. Is there a way round this that doesn't involve a period of regexp induced tourettes?

like image 736
James Avatar asked Feb 16 '12 16:02

James


1 Answers

I don't think you can avoid a little bit of regex-ing.

gsub('(, )+',', ',with(addr.df,paste(street1,street2,city,sep=", ")))

(the regex says: replace more than one "comma space" with a single "comma space")

like image 111
Justin Avatar answered Sep 20 '22 18:09

Justin