[R] gsub and regex to tidy comma-limited values

Daren Tan darentan76 at gmail.com
Sat Mar 14 10:42:13 CET 2009

I am cleaning up comma-limited values, so that only one comma
separates each value. Using the example below, as much as I try with
regex, I can't remove the last comma. I hope to have a one-liner
solution, if possible.

gsub("^,*|,*$|(,)*", "\\1", ",,,apple,,orange,,,,,lemon,strawberry,,,,")
[1] "apple,orange,lemon,strawberry,"

More information about the R-help mailing list