user3242036
user3242036

Reputation: 705

Obtaining year and month from date column in R

I have a date column where dates look like this: 19940818 19941215

What is the proper command to extract the year and month from them?

Upvotes: 0

Views: 976

Answers (2)

Rich Scriven
Rich Scriven

Reputation: 99331

If your data is e.g.

(df <- data.frame(date = c("19940818", "19941215")))
#      date
#1 19940818
#2 19941215

To add two columns, one for month and one for year, you can do

within(df, {
    year <- substr(date, 1, 4)
    month <- substr(date, 5, 6)
})
#       date month year
# 1 19940818    08 1994
# 2 19941215    12 1994

I don't see a need to convert to Date class here since all you want is a substring of the date column.

Upvotes: 2

akrun
akrun

Reputation: 886948

Another option is to use extract from tidyr. Using df from @Richard Scriven's post

library(tidyr)
extract(df, date, c('year', 'month'), '(.{4})(.{2}).*', remove=FALSE)
#      date year month
#1 19940818 1994    08
#2 19941215 1994    12

Upvotes: 1

Related Questions