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?
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?
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]]