-2

I have a dataframe with a date column

date
2008-01-01
2008-01-02
2008-01-03
2008-01-04

how can I create a new column that only contains the year from these dates?

Frank
  • 66,179
  • 8
  • 96
  • 180

1 Answers1

1

If you convert your data frame into a data table

df <- data.table(date = as.Date(c('2008-01-01', 
                                  '2008-01-02',
                                  '2008-01-03',
                                  '2008-01-04')))

You can use its nice assignment and use the stringr package to get the year

library(stringr)
df[,year := str_match(date, '[0-9]{4}')[,1]]
Alexander Heath
  • 116
  • 1
  • 4