Reputation: 533
format(Sys.Date(),"%m")
returns "07"
, but I'd like it to return "7"
while still returning two characters when needed. adding width=8
to the argument list doesn't help, nor does anything else I've tried.
My end goal is to make the stock quote reading function on p. 182 of R in a Nutshell work properly.
Upvotes: 1
Views: 165
Reputation: 7023
You can use gsub
to remove the leading zeros:
> gsub('^0','',format(Sys.Date(),"%m"),perl=TRUE)
[1] "7"
> gsub('^0','',format(as.Date('2010-10-10'),"%m"),perl=TRUE)
[1] "10"
Upvotes: 0
Reputation: 1099
Many ways to do it, but substr() might work best. Combine with ifelse() for two digits.
as.character(as.numeric(format(Sys.Date(),"%m")))
as.character(as.POSIXlt(Sys.Date())$mon + 1)
substr(format(Sys.Date(),"%m"), 2, 2)
Upvotes: 3