tags:

views:

42

answers:

2

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.

+3  A: 

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)
apeescape
Hmm. Thanks. I've been playing around manually with the command to Nutshell's get.quotes and then doing a manual read.csv, and I think that was a false alarm. I'm not sure that's the problem, but I'll check it out.Perhaps my real question should have been how to get that function to work.
Bill
What are your errors? looks like the book is Google Preview-able: http://oreilly.com/catalog/9780596801717/preview
apeescape
The substr() example will only return the last digit of the the numeric month, which is not the desired result for October to December.
nullglob
m <- format(Sys.Date(), "%m");substr(m, ifelse(as.numeric(m) < 10, 2, 1), 2)
apeescape
A: 

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"
nullglob