1

I have a variable in a dataframe variable as

v1 <- c("01-Feb-09", "01-Jan-10", "03-Mar-11")

I want to extract a Year, such that it remains as 2009, 2010, 2011. How can I achieve that?

I tried to convert it to date using as.Date() not working.

Bakang
  • 55
  • 6
  • 3
    What exactly did your `as.Date()` code look like? Did you supply a format string? `as.Date(v1, format = "%d-%b-%y")`? Then you can extract the year using: https://stackoverflow.com/questions/36568070/extract-year-from-date. If you are using base R that would be `as.numeric(format(as.Date(v1, format = "%d-%b-%y"), "%Y"))`. There's a lot of helper packages that can make this easier. – MrFlick Apr 20 '23 at 13:00
  • 1
    It can be done with base R, but the library `lubridate` is fantastic for working with dates. You can make it date with `lubridate::dmy(v1)` (dmy = day month year). you can extract the year with `lubridate::year(lubridate::dmy(v1))` – Kat Apr 20 '23 at 13:00

0 Answers0