combine month and day into one date column

后端 未结 2 502
萌比男神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: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       
    #   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

提交回复
热议问题