Search code examples
rdate-format

R: date format with just year and month


I have a dataframe with monthly data, one column containing the year and one column containing the month. I'd like to combine them into one column with Date format, going from this:

Year    Month     Data
2020        1       54
2020        2       58
2020        3       78
2020        4       59

To this:

   Date    Data
2020-01      54
2020-02      58
2020-03      78
2020-04      59

Solution

  • I think you can't represent a Date format in R without showing the day. If you want a character column, like in your example, you can do:

    > x <- data.frame(Year = c(2020,2020,2020,2020), Month = c(1,2,3,4), Data = c(54,58,78,59))
    > x$Month <- ifelse(nchar(x$Month == 1), paste0(0, x$Month), x$Month) # add 0 behind.
    > x$Date <- paste(x$Year, x$Month, sep = '-')
    > x
      Year Month Data    Date
    1 2020    01   54 2020-01
    2 2020    02   58 2020-02
    3 2020    03   78 2020-03
    4 2020    04   59 2020-04
    > class(x$Date)
    [1] "character"
    

    If you want a Date type column you will have to add:

    x$Date <- paste0(x$Date, '-01')
    x$Date <- as.Date(x$Date, format = '%Y-%m-%d')
    
    x
    
    class(x$Date)