To change character to date

I am having a data frame with date variable.
Its format is "2020-09-04". I need this column with 2020-09" year and month field.

I used substr to make this happen, as

substr(data$date,1,7)

got the desired output but the date field changes to character variable.

I tried formatting it using as.date, format but either it is giving me same format or NA when changed to date type. Any help please.

The date class requires a valid date value so you can't use just year and month, maybe if you explain your ultimate goal, someone could give you an alternative approach.

Thanks andresrcs. I need year and month to sum up values based on month for particular year. This will help me to analysis data on month basis which the goal.

There are other ways to perform time aggregation without losing the date class, take a look at the tsibble package.

If you need more specific help, please provide a proper REPRoducible EXample (reprex) illustrating your issue.

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.