2

I have year, month, and day as separate numeric values and would like to create a date object. In most languages like C# or javascript I can do something like

let x=new Date(2010,11,19);

to initialize a date. What's the R equivalent of this? Obviously I can do

as.Date(paste0(year,'-',month,'-',day))

But it seems pointlessly dumb to convert to character in order to convert to date, right? Surely there is a way to cut out the unnecessary extra string conversion?

Matthew
  • 4,149
  • 2
  • 26
  • 53
  • 1
    The functions `lubridate::make_date` and `ISOdate` both do this – camille Dec 19 '19 at 16:09
  • Does this answer your question? [How to convert in both directions between year,month,day and dates in R?](https://stackoverflow.com/questions/12976542/how-to-convert-in-both-directions-between-year-month-day-and-dates-in-r) – camille Dec 19 '19 at 16:10

1 Answers1

6

We can use ISOdate which returns datetime object (POSIXct) which can changed to Date class with as.Date

as.Date(ISOdate(year, month, day))
#[1] "2010-11-19"

data

year <- 2010
month <- 11
day <- 19
akrun
  • 874,273
  • 37
  • 540
  • 662