0

I am trying to create a column which returns the month of a given observation.

My dataframe is called:" FF5_Class"

I tried to run the following code:

FF5_class$Month <- FF5_class %>% month(date)

However, i received the following error message:"

"Error in as.POSIXlt.default(x, tz = tz(x)) : do not know how to convert 'x' to class “POSIXlt”

A snip from my data is like this:

date    Month
2000-01 
2000-02 
2000-03 
2000-04 
2000-05 
2000-06 
2000-07 
2000-08 
2000-09 
2000-10 
2000-11 
2000-12 
2001-01 
2001-02 
2001-03 
2001-04 
2001-05 
2001-06 
2001-07 
2001-08 
2001-09 
2001-10 
2001-11 
2001-12 

How can I do this? Thank you very much.

  • I have already posted a link on your previous question on how to extract month (from that link: `format(as.Date(paste0("2017-10", "-01")), "%m")`). So please don't repost the same question here. Thanks. – Henrik Mar 07 '21 at 17:47

1 Answers1

1

We can use couple of ways to do this. Regex option would be to remove the characters until the - with sub on the 'date' column

FF5_class$Month <- sub(".*-", "", FF5_class$date))

Or convert to a Date class after pasteing the day, then use format

FF5_class$Month <- format(as.Date(paste0(FF5_class$date, '-01')), '%m')

month works only a Date object and not on a character class

akrun
  • 874,273
  • 37
  • 540
  • 662