0

I have this df

Date;count
2014-10-15;1
2014-12-01;1
2015-01-14;1
2015-03-15;1
2015-07-20;1
2015-10-15;1
2016-01-02;1
2016-01-03;1
2016-02-15;1
2016-04-15;1

The Date is in %Y-%m-%d format and I created another column with just month and year using the dplyr package. This new column has the correct data as character,so I added a new command to convert this column:

df<-df %>%
  mutate(monthyear = format(Date, "%m-%Y")) %>%
  mutate_at(vars(monthyear), as.Date, format = "%m-%Y")

It turns out that the output of the monthyear column is NA. I tried converting this column to factor before converting to date and NA continues. I also tried

df<-df %>%
  mutate(monthyear = format(Date, "%m-%Y"))

and then run the commands

df$monthyear <- as.Date(df$monthyear, format = "%m-%Y")

or

df$monthyear <- as.Date(paste0("1/", df$monthyear), format = "%d/%m/%Y")

In all cases my output is NA in all rows.

ISalvi
  • 123
  • 4

1 Answers1

1

It won't get converted to Date class unless we have all the three components i.e. day, month, and year. When we do the monthyear, it loses the 'day' part. If we need to reconvert, have to add a day

df %>%
  mutate(monthyear = format(Date, "%m-%Y")) %>%
  mutate_at(vars(monthyear), ~ as.Date(paste0("1-", .x), format = "%d-%m-%Y")))
akrun
  • 874,273
  • 37
  • 540
  • 662