9

Assume I have created a variable containing date and time:

a <- ymd_hms("2014-01-01 12:23:34")

How do I create another variable that only has the date? That is, what should I do to transform a's value to be identical to b's value where b is

b <- ymd("2014-01-01")
paljenczy
  • 4,779
  • 8
  • 33
  • 46

2 Answers2

15

You can just use round_date

round_date(a, "day")
[1] "2014-01-02 UTC"

EDIT

You do need to be careful with rounding the time though. For complete equivalence here you would need to use floor_date.

identical(ymd("2014-01-01"), floor_date(a, "day"))
[1] TRUE
cdeterman
  • 19,630
  • 7
  • 76
  • 100
  • 5
    Why would he need all this complication? Why not just `as.Date(a)`? `lubridate` was presumably designed to make it easier to work with dates, not to over-complicate it. – David Arenburg Feb 25 '15 at 21:38
  • @DavidArenburg To me, for example, it helps to stick to a limited set of concepts. I always remember `floor_date`, but I'd have to look up if it's `as.Date` or `as.date` (what's with the dots and the capitalization?). And whatever it returns may not be compatible with what I'm already doing. In R, it always feels like there are a dozen ways to achieve one thing. Sticking functions from `lubridate` (or, more generally, `tidyverse`) helps me tremendously in being more productive. – slhck Apr 29 '19 at 17:22
  • 5
    @slhck This is because Hadley renamed all the R functions with cute name and then RStudio heavily promoted tidyverse and now all the new R users think it''s the standard and everything else is confusing. I feel much more productive using base R and a single package, e.g. data.table (and sometimes other packages according to my needs) instead of huge bunch of packages bundled together (i.e. tidyverse) that all have endless amount of different functions that you need to memorize and that constantly being renamed/deprecated, that are slow, mask functions from different packages, unstable and etc. – David Arenburg Apr 30 '19 at 07:10
8

Using date() is much shorter and avoids any issues with rounding.

library(lubridate)
date(a)
[1] "2014-01-01"
Nakx
  • 1,460
  • 1
  • 23
  • 32