combine month and day into one date column

后端 未结 2 504
萌比男神i
萌比男神i 2021-02-08 04:37

Using R, I\'d like to combine into one column (date) the month nb (month) and the day nb (day) contained in two different columns and use the created column in a date format.

相关标签:
2条回答
  • 2021-02-08 05:19

    I assume here that by "date format" you just mean a string that looks like a date, rather than a proper date class in R.

    data <- data.frame( Month=c(1,5,2), Day=c(1,2,3) )
    data$MonthDay <- paste( month.abb[data$Month], data$Day, sep="-" )
    data
    #   Month Day MonthDay
    # 1     1   1    Jan-1
    # 2     5   2    May-2
    # 3     2   3    Feb-3
    
    0 讨论(0)
  • 2021-02-08 05:23

    Try this...

    df <- data.frame( Month = sample(1:12 , 10 , repl = TRUE ) , Day = sample(1:30 , 10 , repl = TRUE ) )
    df$Date <- as.Date( paste( df$Month , df$Day , sep = "." )  , format = "%m.%d" )
    
    df
    #      Month Day       Date
    #   1      1   8 2013-01-08
    #   2      1  17 2013-01-17
    #   3      7  23 2013-07-23
    #   4     11  21 2013-11-21
    #   5      3  30 2013-03-30
    #   6     12  15 2013-12-15
    #   7      2  30       <NA>
    #   8      7  10 2013-07-10
    #   9      1  16 2013-01-16
    #   10     8   1 2013-08-01
    

    I got some NAs because I made up random dates, some of which don't exist, such as 30th Feb

    0 讨论(0)
提交回复
热议问题