How to remove a zero (0) after a slash (/) in the context of a date

I am merging two datasets and need to standardize how the dates appear. From searching another forum I was able to figure out how to remove a leading zero using this

mutate(new_column = str_remove(old_column, "^0+"))

however I am still stuck with these zeros after a /, for example 9/01/2010. I want to make it read as 9/1/2010.

Or, if there is a way to go from 09/01/2010 to 9/1/2010 that would be ideal. I tried to accomplish that by using this

mutate(new_column = as.Date(old_column, format = "%m/%d/%y")) but for some reason, that turned all of the years into 2020.

Use "%Y" rather than "%y": %y is for a 2-digit year, so it only keeps the 20 in 2010 and interprets it as 2020.

That approach can work. IMO the easiest is to do this in two steps: first use str_remove to remove the leading zero, then use str_replace to remove any zero following /. There are other ways to do it which may be more efficient (in execution speed), but I find them harder to read.

str_remove("09/01/2010",
               "^0") %>%
  str_replace("/0", "/")

Add a + if you want to remove several 0 at once (I don't think it's your case though).

Just a thought - before merging both datasets, why don't you transform the dates in both sets to a compatible date format, e.g. by using the lubridate package. And only merge in a second step. (Instead of trying to modify one dataset to be in line with the other dataset).

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.