1

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?

Kayla
  • 59
  • 5

3 Answers3

1

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")
akrun
  • 874,273
  • 37
  • 540
  • 662
1

Do you need to convert to date first? You can just extract the month form the string. This will extract everything after the '-' from the string as a numeric type.

as.numeric(gsub(".*-","",df_Month$yearmonth))

0

This question was answered here using the zoo::as.yearmon() function and/or the above solution.

L. South
  • 141
  • 8