On Jun 5, 2009, at 3:56 PM, Marc Belisle wrote:
Hi there,
I have 3 numeric variables: day (e.g., 05), month (e.g., 06), year
(e.g.,
2009).
I would like to create a (string) variable of the following form:
month/day/year (e.g., 06/05/2009).
I would be grateful to anyone who could point me toward a solution.
Sincerely,
Marc
If you want the result just as text:
day <- 5
month <- 6
year <- 2009
> sprintf("%02d/%02d/%4d", day, month, year)
[1] "05/06/2009"
Note that the day/month integers will of course not have the leading
zeros, so using sprintf() allows you to specify that the results
should include them (the '%02d' in the format string).
See ?sprintf for more information.
If you further want to use them as actual date objects, you can use
as.Date() on the result:
> as.Date(sprintf("%02d/%02d/%4d", day, month, year), format = "%d/%m/
%Y")
[1] "2009-06-05"
Note that the above is now of Class 'Date':
> str(as.Date(sprintf("%02d/%02d/%4d", day, month, year), format =
"%d/%m/%Y"))
Class 'Date' num 14400
which then enables you to perform date based operations on the results.
See ?as.Date for more information on converting text to dates.
HTH,
Marc Schwartz
______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.