Ad

Remove Character Based On Condition And Position In String - R

I cleaning up a dataset with a character variable like this:

df <- c("2015  000808", "2013  000041", "2015  000005", "2015  301585", "2015  311585", "2014  380096", "2013  100041")

So I can achieve this result, where the 000s in front of the second number are removed and each number is pasted together:

"2015808"
"201341"
"20155"
"2015301585"
"2015311585"
"2014380096"
"2013100041"

I am stuck trying to find the best way to remove the 0s that occur before the number in the second part of the string. I have looked at gsub and substring but I am bit confused how to remove a pattern of zeros based on their position as well as on conditions? Something along the lines of "remove one or more zeros only if they precede number 1-9 and are in position 7-11".

Ad

Answer

We may use read.table to read as two columns and then paste

do.call(paste0, read.table(text = df, header = FALSE))
[1] "2015808"    "201341"     "20155"      "2015301585" "2015311585" "2014380096" "2013100041"

Or with sub

sub("\\s+0*", "", df)
[1] "2015808"    "201341"     "20155"      "2015301585" "2015311585" "2014380096" "2013100041"
Ad
source: stackoverflow.com
Ad