Reputation: 617
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?
Upvotes: -1
Views: 2214
Reputation: 41210
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
Upvotes: 3
Reputation: 617
I verified that round_date()
brings problems because it leases dates from the year 2000 to 2001, this can be a problem in the statistics.
Based on another post I found the floor_date()
that rounds up for the same year.
date2<-c('01/01/2000','08/08/2000','16/03/2001')
name<-c('A','B','C')
df<-data.frame(date2,name)
df2 <- df %>%
mutate(date2 = dmy(date2)) %>%
mutate(year_date = floor_date(date2,'year'))
df2
see that 200-08-08 is now rounded up to the year 2000
date2<date> name<chr> year_date<date>
2000-01-01 A 2000-01-01
2000-08-08 B 2000-01-01
2001-03-16 C 2001-01-01
Upvotes: 1