Join two numeric columns to create a Year-month variable

前端 未结 3 1608
慢半拍i
慢半拍i 2021-01-29 04:17

I have two numeric columns. One contains a year, one a month number. I want to join these two and make a Year-month column that is of the proper Date type. To give a background,

相关标签:
3条回答
  • 2021-01-29 04:29

    You could consider the yearmon class in the zoo package:

    library(zoo) zoo::as.yearmon(paste(year, month, sep='-'))

    0 讨论(0)
  • 2021-01-29 04:37

    In order to be a proper date type, you need a month, day, and year. I usually just throw a "1" in there for the day, since every month has a first day...

    df <- data.frame(year=c("2015", "2015", "2014"),
                     month=c("4", "2", "9"),
                     stringsAsFactors=FALSE)
    df$date <- as.Date(paste(df$month, "01", df$year, sep="_"), format="%m_%d_%Y")
    df <- df[order(df$date), ]
    
    0 讨论(0)
  • 2021-01-29 04:48

    Just add a 01 in your paste and use as.Date

    as.Date(paste(year, month, '01', sep= '-'))
    
    0 讨论(0)
提交回复
热议问题