[R] from 3 numeric variables to a string
Marc Schwartz
marc_schwartz at me.com
Fri Jun 5 23:09:03 CEST 2009
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
More information about the R-help
mailing list