rdatetimeformatas.dateyearmonth

How to convert character column to date?


My data frame:

  yearmonth basinflow
  <chr>         <dbl>
1 1966-01   0.000105 
2 1966-02   0.0000946
3 1966-03   0.816    
4 1966-04   5.17     
5 1966-05   0.102    
6 1966-06   0.0729   

I want to add a column with just the month values, but converting the yearmonth to a date with as.Date is not working.

as.Date(df_Month$yearmonth, format = "%Y-%m")

[1] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
 [35] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA

And result is this. What can I try? Or is there a way to only call the month portion without it being a date?


Solution

  • We need a day as well for Date class which we can paste and then either use %Y-%m-%d or skip the format as the default format is %Y-%m-%d

    as.Date(paste0(df_Month$yearmonth, "-01"), format = "%Y-%m-%d")