Creating Month and Year Columns in R

Hi everyone! I'm new to R and have a quick question if anyone knows the answer. I have a date column in my dataset (its class is a date as well) in the format YYYY-MM-DD. I want to create a Month column in the format M and a Year column in the format YYYY but all my attempts have been unsuccessful. Thank you so much in advance to anyone who may be able to provide some suggestions :slight_smile:

It would be helpful if you provide a reproducible example of what you've tried and what your data looks like. FAQ: How to do a minimal reproducible example ( reprex ) for beginners

Otherwise, I think the lubridate package might be helpful: https://evoldyn.gitlab.io/evomics-2018/ref-sheets/R_lubridate.pdf

Something like this?

library(zoo)
date <- ("2021-01-13")
as.yearmon(date)


> as.yearmon(date)
[1] "Jan 2021"

But yes, a reproducible example would be good.

Hi! Thank you, you were right! I added the lubridate package and was able to do it using:

my_data_inflow = my_data_inflow %>%
mutate(Date = ymd(Date)) %>%
mutate_at(vars(Date), funs(year, month))

Thanks for your help!

Hi! Thank you so much for your help. I ended up using the lubridate package. Here's what I did if anyone is curious!

my_data_inflow = my_data_inflow %>%
mutate(Date = ymd(Date)) %>%
mutate_at(vars(Date), funs(year, month))

I appreciate your time, have a great day!

1 Like

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.