I have a dataframe with one column in numeric format: 2022, 2021,2020, 2019....and more years
How can I convert it to year but with date format?
Thanks
I have a dataframe with one column in numeric format: 2022, 2021,2020, 2019....and more years
How can I convert it to year but with date format?
Thanks
I am not sure what your goal is. A Date must have a month and a day. It is easy enough to assign a fixed day and month as in the following code.
DF <- data.frame(Year = c(2022, 2021, 2020), Value = 1:3)
str(DF)
'data.frame': 3 obs. of 2 variables:
$ Year : num 2022 2021 2020
$ Value: int 1 2 3
DF$Year <- as.Date(paste(DF$Year,"01-01", sep = "-"))
str(DF)
'data.frame': 3 obs. of 2 variables:
$ Year : Date, format: "2022-01-01" "2021-01-01" ...
$ Value: int 1 2 3
You cannot simultaneously have the value as a Date and display only the year value, if that is your goal.
Yes, I want to achieve only year, but this solution also works fine. Thanks!
You can use lubridate::make_date()
to do this. For example
lubridate::make_date(year = 2020:2022)
# [1] "2020-01-01" "2021-01-01" "2022-01-01"
Also try the unite() as below
year <- data.frame(year=c(2020:2022),month=1,day=1)
year2 <- year %>% unite(date,year,month,day,sep='-',remove = F) %>% mutate(date=as.Date(date))
str(year2)
'data.frame': 3 obs. of 4 variables:
$ date : Date, format: "2020-01-01" "2021-01-01" "2022-01-01"
$ year : int 2020 2021 2022
$ month: num 1 1 1
$ day : num 1 1 1
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.
If you have a query related to it or one of the replies, start a new topic and refer back with a link.