Search code examples
rdatelubridate

how to convert numeric only year in Date in R?


I have a data-frame with column year numeric, but i would like to convert it in year date.

my data-frame

library(tidyverse)
    
date2<-c('01/01/2000','08/08/2000','16/03/2001')
name<-c('A','B','C')
    
df<-data.frame(date2,name)

but when I perform the command mutate:

df2<-df%>%
  mutate(date2=dmy(date2))%>%
  mutate(Year2=year(date2))

str(df2)

'data.frame':   3 obs. of  3 variables:
 $ date2: Date, format: "2000-01-01" "2000-08-08" "2001-03-16"
 $ name : chr  "A" "B" "C"
 $ Year2: num  2000 2000 2001

but I would like Year2 to be Date and not numeric.

How to solve this?


Solution

  • You could use round_date, [EDIT] or better floor_date to round to the start of the year(see comment & answer below):

    library(lubridate)
    
    df2 <- df %>%
      mutate(date2 = dmy(date2)) %>%
      mutate(year_internal = round_date(date2,'year')) %>%
      mutate(year_out = format(year_internal,'%Y'))
    
    df2 %>% select(date2, name, year_internal, year_out)
    
           date2 name year_internal year_out
    1 2000-01-01    A    2000-01-01     2000
    2 2000-08-08    B    2001-01-01     2001
    3 2001-03-16    C    2001-01-01     2001